From 2bfc5c7f79a2c90cad91512d16d57b469f4bf107 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:17:19 +1300 Subject: [PATCH 01/27] Prepare exact selected-owner authorization and settlement --- .../account-service/runtime-and-data.md | 2 +- .../world-management-service/api-contracts.md | 2 + .../player-access-and-session.md | 2 +- ..._owner_intake_authorization_producer.proto | 37 + ...cted_owner_intake_authorization_read.proto | 34 + ...cted_owner_intake_settlement_service.proto | 30 + ...ake_world_closure_authorization_read.proto | 35 + ...selected_source_intake_terminal_read.proto | 34 + ...selected_source_intake_terminal_read.proto | 34 + .../selected_owner_world_inventory_read.proto | 38 + ...ntakeAuthorizationProducerGrpcService.java | 196 ++ ...nerIntakeAuthorizationReadGrpcService.java | 88 + ...edOwnerIntakeAuthorizationReadService.java | 75 + ...lectedOwnerIntakeAuthorizationService.java | 296 +++ ...ectedOwnerIntakeSettlementGrpcService.java | 90 + ...tSelectedOwnerIntakeSettlementService.java | 413 +++ ...wnerIntakeSourceReservationRepository.java | 381 ++- ...ldClosureAuthorizationReadGrpcService.java | 88 + ...eWorldClosureAuthorizationReadService.java | 72 + ...cted_owner_intake_final_authorizations.sql | 457 ++++ ...ected_owner_intake_terminal_settlement.sql | 500 ++++ ...ected_owner_intake_terminal_settlement.sql | 708 ++++++ ...eAuthorizationPostgresIntegrationTest.java | 2207 +++++++++++++++++ ...eAuthorizationProducerGrpcServiceTest.java | 312 +++ ...ntakeAuthorizationReadGrpcServiceTest.java | 232 ++ ...nerIntakeAuthorizationReadServiceTest.java | 299 +++ ...wnerIntakeAuthorizationRepositoryTest.java | 29 + ...edOwnerIntakeAuthorizationServiceTest.java | 692 ++++++ ...dOwnerIntakeSettlementGrpcServiceTest.java | 235 ++ ...ectedOwnerIntakeSettlementServiceTest.java | 650 +++++ ...IntakeSourceReservationRepositoryTest.java | 13 + ...osureAuthorizationReadGrpcServiceTest.java | 222 ++ ...ldClosureAuthorizationReadServiceTest.java | 159 ++ .../AccountControlUiOwnerSourcesFixture.java | 4 +- ...tedOwnerIntakeAuthorizationGrpcClient.java | 157 ++ ...tSelectedOwnerIntakeSettlementReceipt.java | 319 +++ ...keWorldClosureAuthorizationGrpcClient.java | 160 ++ .../SelectedOwnerEmptySourceInputs.java | 156 ++ ...lectedOwnerIntakeAuthorizationBinding.java | 257 ++ ...ntakeAuthorizationProducerCredentials.java | 120 + ...erIntakeAuthorizationProducerEvidence.java | 220 ++ ...IntakeAuthorizationProducerProtoCodec.java | 152 ++ ...tedOwnerIntakeAuthorizationReadClient.java | 7 + ...dOwnerIntakeAuthorizationReadEvidence.java | 69 + ...OwnerIntakeAuthorizationReadGrpcCodec.java | 104 + ...SelectedOwnerIntakeSettlementEvidence.java | 123 + ...electedOwnerIntakeSettlementGrpcCodec.java | 140 ++ ...keWorldClosureAuthorizationReadClient.java | 7 + ...WorldClosureAuthorizationReadEvidence.java | 72 + ...orldClosureAuthorizationReadGrpcCodec.java | 104 + ...ationEmptySelectedSourceIntakeReceipt.java | 717 ++++++ ...electedSourceIntakeTerminalReadClient.java | 160 ++ ...ectedSourceIntakeTerminalReadEvidence.java | 95 + ...ctedSourceIntakeTerminalReadGrpcCodec.java | 138 ++ ...ntityEmptySelectedSourceIntakeReceipt.java | 880 +++++++ ...electedSourceIntakeTerminalReadClient.java | 7 + ...ectedSourceIntakeTerminalReadEvidence.java | 95 + ...ctedSourceIntakeTerminalReadGrpcCodec.java | 139 ++ ...electedSourceIntakeTerminalReadClient.java | 162 ++ ...SelectedOwnerWorldInventoryReadClient.java | 7 + ...lectedOwnerWorldInventoryReadEvidence.java | 125 + ...ectedOwnerWorldInventoryReadGrpcCodec.java | 180 ++ ...WorldSelectedOwnerInventoryGrpcClient.java | 150 ++ ...wnerIntakeAuthorizationGrpcClientTest.java | 87 + ...ectedOwnerIntakeSettlementReceiptTest.java | 154 ++ ...rldClosureAuthorizationGrpcClientTest.java | 100 + .../SelectedOwnerEmptySourceInputsTest.java | 895 +++++++ ...edOwnerIntakeAuthorizationBindingTest.java | 448 ++++ ...eAuthorizationProducerCredentialsTest.java | 103 + ...keAuthorizationProducerProtoCodecTest.java | 256 ++ ...erIntakeAuthorizationReadEvidenceTest.java | 177 ++ ...rIntakeAuthorizationReadGrpcCodecTest.java | 174 ++ ...electedOwnerIntakeClientLifecycleTest.java | 28 +- ...tedOwnerIntakeSettlementGrpcCodecTest.java | 200 ++ ...dClosureAuthorizationReadEvidenceTest.java | 57 + ...ClosureAuthorizationReadGrpcCodecTest.java | 184 ++ ...wnerWorldInventoryRecipientFieldsTest.java | 486 ++++ ...SourceIntakeTerminalReadGrpcCodecTest.java | 247 ++ ...ourceIntakeTerminalReadClientMtlsTest.java | 168 ++ ...ourceIntakeTerminalReadClientMtlsTest.java | 168 ++ ...dOwnerWorldInventoryReadGrpcCodecTest.java | 40 + ...SelectedOwnerInventoryReadGrpcService.java | 142 ++ ...orldSelectedOwnerInventoryReadService.java | 90 + ...SelectedOwnerInventoryReadServiceTest.java | 504 ++++ 84 files changed, 18385 insertions(+), 11 deletions(-) create mode 100644 protos/account/v1/selected_owner_intake_authorization_producer.proto create mode 100644 protos/account/v1/selected_owner_intake_authorization_read.proto create mode 100644 protos/account/v1/selected_owner_intake_settlement_service.proto create mode 100644 protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto create mode 100644 protos/automation-scripting/v1/automation_selected_source_intake_terminal_read.proto create mode 100644 protos/entity-management/v1/entity_selected_source_intake_terminal_read.proto create mode 100644 protos/world-management/v1/selected_owner_world_inventory_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java create mode 100644 services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_final_authorizations.sql create mode 100644 services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_terminal_settlement.sql create mode 100644 services/account-service/src/main/resources/db/migration/V1009__entity_selected_owner_intake_terminal_settlement.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntityEmptySelectedSourceIntakeReceipt.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index d5b9068bdb..e69b679bdf 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 intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement in forward V1006–V1009. It preserves the actual V1005 combined parent and prior protection/disposal guards. These components remain unregistered and unqualified; 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/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 4fbc8795ef..d2eb46df13 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -2,6 +2,8 @@ ## Implementation Status +The prepared recipient-specific inventory read verifies the exact Entity or Automation workload and independently reads Account's held World-closure authorization before reading the original retained World inventory. It is separate from the ordinary Game Design publication read and adds no mutation or runtime registration. Qualification remains pending in the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). + The standalone published-spawn requirements read is prepared as unregistered source. It consumes the exact authenticated Game Design release and frozen World selector, accepts only the exact same-namespace Entity workload, and returns immutable design requirements rather than runtime actor or placement authority. Qualification and producer limitations belong to [the World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#published-spawn-requirements-read-preparation). The original StartSession canonical preparation, exact execution recovery and lifecycle-read components are prepared as standalone, unregistered source. Their current qualification and producer dependencies belong to [the World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#original-startsession-world-preparation-and-recovery). Production Game Design complete-launch reads remain denied; these components do not enable deployment, activation, admission or Entity placement. The existing [World creation workflow](./world-creation-workflow.md) and [runtime storage contracts](./runtime-and-data.md) retain target-state 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 a309fa61f7..9caa623ba1 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. New forward Account V1006–V1009 follow the actual V1005 plus Saga parent; existing publication, World participation, protection and disposal history remains unchanged. The prepared upgrade proofs retain parent rows, source bytes, history and xmin, but have not run. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. Qualification and publication are pending; no selected-full attestation 4 or genuine Gameplay handoff is complete, 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/protos/account/v1/selected_owner_intake_authorization_producer.proto b/protos/account/v1/selected_owner_intake_authorization_producer.proto new file mode 100644 index 0000000000..3e7d745341 --- /dev/null +++ b/protos/account/v1/selected_owner_intake_authorization_producer.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered producer for the distinct Entity and Automation intake authorization. +service AccountSelectedOwnerIntakeAuthorizationProducerService { + rpc AuthorizeSelectedOwnerIntake(SelectedOwnerIntakeAuthorizationProducerRequest) + returns (SelectedOwnerIntakeAuthorizationProducerResponse); +} + +enum SelectedOwnerIntakeAuthorizationProducerOwner { + SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_UNSPECIFIED = 0; + SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_ENTITY_MANAGEMENT = 1; + SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_AUTOMATION_SCRIPTING = 2; +} + +message SelectedOwnerIntakeAuthorizationProducerRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent per-transport correlation; not the stable intake or selected Draft identity. + string transport_request_id = 3; + string intake_request_id = 4; + SelectedOwnerIntakeAuthorizationProducerOwner owner = 5; + // Complete canonical DraftCommitBinding JSON bytes. + bytes selected_draft_binding = 6; +} + +message SelectedOwnerIntakeAuthorizationProducerResponse { + // Exact unchanged request echo. + SelectedOwnerIntakeAuthorizationProducerRequest request = 1; + // Complete canonical SelectedOwnerIntakeAuthorizationBinding bytes and its SHA-256 digest. + bytes intake_authorization_binding = 2; + string intake_authorization_digest = 3; +} diff --git a/protos/account/v1/selected_owner_intake_authorization_read.proto b/protos/account/v1/selected_owner_intake_authorization_read.proto new file mode 100644 index 0000000000..5a9da9e5fc --- /dev/null +++ b/protos/account/v1/selected_owner_intake_authorization_read.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone read of a distinct finalized Entity or Automation intake authorization. This method +// samples that the exact Account authorization and source participation remain held at read time; +// it does not prove continuous commit protection, owner inventory, or terminal settlement. +service AccountSelectedOwnerIntakeAuthorizationReadService { + rpc ReadHeldSelectedOwnerIntakeAuthorization( + ReadHeldSelectedOwnerIntakeAuthorizationRequest) + returns (ReadHeldSelectedOwnerIntakeAuthorizationResponse); +} + +message ReadHeldSelectedOwnerIntakeAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Derived from the closed Entity or Automation owner in the complete original binding. + string intended_reader = 4; + // ENTITY_INTAKE_RETENTION or AUTOMATION_INTAKE_RETENTION, derived from that same owner. + string retention_purpose = 5; + // Complete canonical SelectedOwnerIntakeAuthorizationBinding bytes and their SHA-256 digest. + bytes original_intake_authorization_binding = 6; + string intake_authorization_digest = 7; +} + +message ReadHeldSelectedOwnerIntakeAuthorizationResponse { + // Echo the complete request tuple unchanged. Only held=true is a successful result. + ReadHeldSelectedOwnerIntakeAuthorizationRequest request = 1; + bool held = 2; +} diff --git a/protos/account/v1/selected_owner_intake_settlement_service.proto b/protos/account/v1/selected_owner_intake_settlement_service.proto new file mode 100644 index 0000000000..d6e7925ae5 --- /dev/null +++ b/protos/account/v1/selected_owner_intake_settlement_service.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered command for settling one finalized Entity or Automation intake operation. +service AccountSelectedOwnerIntakeSettlementService { + rpc SettleSelectedOwnerIntake(SelectedOwnerIntakeSettlementRequest) + returns (SelectedOwnerIntakeSettlementResponse); +} + +message SelectedOwnerIntakeSettlementRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent transport correlation; the retained authorization remains the settlement key. + string transport_request_id = 3; + // Complete canonical Account authorization bytes and their SHA-256 digest. + bytes original_intake_authorization_binding = 4; + string intake_authorization_digest = 5; +} + +message SelectedOwnerIntakeSettlementResponse { + // Exact unchanged request echo. + SelectedOwnerIntakeSettlementRequest request = 1; + // Complete immutable Account settlement receipt bytes and their SHA-256 digest. + bytes settlement_receipt = 2; + string settlement_receipt_digest = 3; +} diff --git a/protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto b/protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto new file mode 100644 index 0000000000..fc32c17503 --- /dev/null +++ b/protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone World read of a finalized Entity or Automation intake authorization. This samples +// the original Account authorization and source participation at read time; it does not prove +// continuous commit protection, complete World inventory, or terminal settlement. +service AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService { + rpc ReadHeldSelectedOwnerWorldClosureAuthorization( + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest) + returns (ReadHeldSelectedOwnerWorldClosureAuthorizationResponse); +} + +message ReadHeldSelectedOwnerWorldClosureAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Always the exact same-namespace World Management workload. + string intended_reader = 4; + // ENTITY_INTAKE_WORLD_CLOSURE_READ or AUTOMATION_INTAKE_WORLD_CLOSURE_READ, derived from the + // original binding's owner. + string closure_read_purpose = 5; + // Complete canonical original SelectedOwnerIntakeAuthorizationBinding bytes and SHA-256 digest. + bytes original_intake_authorization_binding = 6; + string intake_authorization_digest = 7; +} + +message ReadHeldSelectedOwnerWorldClosureAuthorizationResponse { + // Echo the complete request unchanged. Only held=true is a successful result. + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest request = 1; + bool held = 2; +} diff --git a/protos/automation-scripting/v1/automation_selected_source_intake_terminal_read.proto b/protos/automation-scripting/v1/automation_selected_source_intake_terminal_read.proto new file mode 100644 index 0000000000..095934762f --- /dev/null +++ b/protos/automation-scripting/v1/automation_selected_source_intake_terminal_read.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package automation_scripting.v1; +option java_package = "net.firedevops.firemud.automationscripting.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only the same-namespace Account workload may read. +service AutomationSelectedSourceIntakeTerminalReadService { + rpc ReadSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest) + returns (ReadSelectedSourceIntakeTerminalResponse); +} + +message ReadSelectedSourceIntakeTerminalRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string terminal_read_purpose = 5; + bytes original_intake_authorization_binding = 6; + string intake_authorization_digest = 7; +} + +enum AutomationSelectedSourceIntakeTerminalResult { + AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED = 0; + AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY = 1; +} + +message ReadSelectedSourceIntakeTerminalResponse { + ReadSelectedSourceIntakeTerminalRequest request = 1; + AutomationSelectedSourceIntakeTerminalResult result = 2; + bytes committed_empty_receipt = 3; + string receipt_digest = 4; +} diff --git a/protos/entity-management/v1/entity_selected_source_intake_terminal_read.proto b/protos/entity-management/v1/entity_selected_source_intake_terminal_read.proto new file mode 100644 index 0000000000..4c0905b3dd --- /dev/null +++ b/protos/entity-management/v1/entity_selected_source_intake_terminal_read.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package entity_management.v1; +option java_package = "net.firedevops.firemud.entitymanagement.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only the same-namespace Account workload may read. +service EntitySelectedSourceIntakeTerminalReadService { + rpc ReadSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest) + returns (ReadSelectedSourceIntakeTerminalResponse); +} + +message ReadSelectedSourceIntakeTerminalRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string terminal_read_purpose = 5; + bytes original_intake_authorization_binding = 6; + string intake_authorization_digest = 7; +} + +enum EntitySelectedSourceIntakeTerminalResult { + ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED = 0; + ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY = 1; +} + +message ReadSelectedSourceIntakeTerminalResponse { + ReadSelectedSourceIntakeTerminalRequest request = 1; + EntitySelectedSourceIntakeTerminalResult result = 2; + bytes committed_empty_receipt = 3; + string receipt_digest = 4; +} diff --git a/protos/world-management/v1/selected_owner_world_inventory_read.proto b/protos/world-management/v1/selected_owner_world_inventory_read.proto new file mode 100644 index 0000000000..f6f57d9111 --- /dev/null +++ b/protos/world-management/v1/selected_owner_world_inventory_read.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +import "world-management/v1/world_selected_draft_publication_freeze_service.proto"; + +// Standalone recipient-specific read of the retained World inventory for selected Entity or +// Automation source intake. This is read-only and does not alter the Game Design publication read. +service WorldSelectedOwnerInventoryReadService { + rpc ReadSelectedOwnerWorldInventory(ReadSelectedOwnerWorldInventoryRequest) + returns (ReadSelectedOwnerWorldInventoryResponse); +} + +message ReadSelectedOwnerWorldInventoryRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical Account owner-intake authorization binding and its digest. + bytes original_intake_authorization_binding = 4; + string intake_authorization_digest = 5; + // Exact original selected-publication freeze request and committed acknowledgement. + BeginVersionPublicationFreezeRequest freeze_request = 6; + BeginVersionPublicationFreezeResponse freeze_acknowledgement = 7; + // Original Entity/Automation recipient and the distinct recipient-specific closure purpose. + string intended_reader = 8; + string closure_read_purpose = 9; +} + +message ReadSelectedOwnerWorldInventoryResponse { + int32 schema_version = 1; + // Complete request echo; only the public World inventory projection follows. + ReadSelectedOwnerWorldInventoryRequest request = 2; + bytes canonical_public_inventory = 3; + string public_inventory_digest = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.java new file mode 100644 index 0000000000..ec0e14b1a0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.java @@ -0,0 +1,196 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered same-namespace Game Design selected-owner intake producer. */ +public final class AccountSelectedOwnerIntakeAuthorizationProducerGrpcService + implements BindableService { + private final AccountSelectedOwnerIntakeAuthorizationService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountSelectedOwnerIntakeAuthorizationProducerGrpcService( + AccountSelectedOwnerIntakeAuthorizationService owner, + AccountHostedTermsService terms, + String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** Peer authentication precedes protected metadata parsing and all evidence decoding. */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationProducerServiceImplBase() { + @Override + public void authorizeSelectedOwnerIntake( + SelectedOwnerIntakeAuthorizationProducerRequest request, + StreamObserver observer) { + AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.this + .authorizeSelectedOwnerIntake(request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + String method = call.getMethodDescriptor().getFullMethodName(); + if (!SelectedOwnerIntakeAuthorizationProducerCredentials.allowedMethod(method)) { + call.close(sanitized(Status.UNIMPLEMENTED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + if (hasAmbientSql()) { + call.close(sanitized(Status.FAILED_PRECONDITION), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final SelectedOwnerIntakeAuthorizationProducerCredentials.Credential credential; + try { + credential = + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + headers, method); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + Context context = + Context.current() + .withValue( + SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY, + credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void authorizeSelectedOwnerIntake( + SelectedOwnerIntakeAuthorizationProducerRequest wire, + StreamObserver observer) { + final AuthenticatedRequest authenticated; + try { + authenticated = request(wire); + } catch (StatusRuntimeException denied) { + deny(observer, Status.fromCode(denied.getStatus().getCode())); + return; + } + var request = authenticated.request(); + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + + final SelectedOwnerIntakeAuthorizationProducerResponse response; + try { + var binding = + owner.authorizeWithEnvironmentCapture( + authenticated.originalCreatorCredential(), + request.intakeRequestId(), + request.owner(), + request.selected(), + terms::captureCurrentEnvironmentBoundary); + var result = + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest()); + response = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse(result); + } catch (RuntimeException unavailable) { + deny(observer, statusOf(unavailable)); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private AuthenticatedRequest request(SelectedOwnerIntakeAuthorizationProducerRequest wire) { + Status denied = peerDenial(); + if (denied != null) throw sanitized(denied).asRuntimeException(); + if (hasAmbientSql()) throw sanitized(Status.FAILED_PRECONDITION).asRuntimeException(); + + var protectedCredential = SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) throw sanitized(Status.UNAUTHENTICATED).asRuntimeException(); + final String credential; + try { + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + throw sanitized(Status.UNAUTHENTICATED).asRuntimeException(); + } + try { + return new AuthenticatedRequest( + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromRequest(wire), credential); + } catch (IllegalArgumentException malformed) { + throw sanitized(Status.INVALID_ARGUMENT).asRuntimeException(); + } + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + return Status.PERMISSION_DENIED; + } + return null; + } + + private static boolean hasAmbientSql() { + return TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive(); + } + + private static Status statusOf(RuntimeException error) { + if (error instanceof StatusRuntimeException status) + return Status.fromCode(status.getStatus().getCode()); + if (error instanceof IllegalArgumentException) return Status.FAILED_PRECONDITION; + return Status.UNAVAILABLE; + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private static Status sanitized(Status status) { + return status.withDescription( + "Account selected-owner intake authorization denied or unavailable"); + } + + private record AuthenticatedRequest( + SelectedOwnerIntakeAuthorizationProducerEvidence.Request request, + String originalCreatorCredential) { + @Override + public String toString() { + return "AuthenticatedSelectedOwnerIntakeAuthorizationRequest[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..e6c722e107 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcService.java @@ -0,0 +1,88 @@ +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.AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Standalone receiver: authenticate the exact owner workload before parsing or looking up data. */ +public final class AccountSelectedOwnerIntakeAuthorizationReadGrpcService + extends AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationReadServiceImplBase { + private final AccountSelectedOwnerIntakeAuthorizationReadService owner; + private final String namespace; + + public AccountSelectedOwnerIntakeAuthorizationReadGrpcService( + AccountSelectedOwnerIntakeAuthorizationReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-owner authorization reader is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readHeldSelectedOwnerIntakeAuthorization( + ReadHeldSelectedOwnerIntakeAuthorizationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String peerUri = peer.uri(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !(peerUri.equals("spiffe://firemud/ns/" + namespace + "/sa/entity-management-service") + || peerUri.equals( + "spiffe://firemud/ns/" + namespace + "/sa/automation-scripting-service"))) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() + > SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + final SelectedOwnerIntakeAuthorizationReadEvidence.Request decoded; + try { + decoded = SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(decoded.targetNamespace()) || !peerUri.equals(decoded.intendedReader())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + try { + owner.requireHeld(decoded); + observer.onNext(SelectedOwnerIntakeAuthorizationReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java new file mode 100644 index 0000000000..1895937609 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java @@ -0,0 +1,75 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +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 held-retention read; it neither creates authority nor settles participation. + */ +public final class AccountSelectedOwnerIntakeAuthorizationReadService { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final TransactionTemplate ownerTransaction; + private final String namespace; + + public AccountSelectedOwnerIntakeAuthorizationReadService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.repository = + Objects.requireNonNull(repository, "source reservation repository is required"); + 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); + } + + /** Confirms the exact finalized authorization and source locks in an independent transaction. */ + public void requireHeld(SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "authorization-read request is required"); + requirePeer(namespace, request.intendedReader()); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + try { + ownerTransaction.execute( + ignored -> { + repository.readHeldFinalAuthorization(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException changedOrAbsent) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } + } + + static void requirePeer(String namespace, String expectedReader) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !peer.uri().equals(expectedReader) + || !(expectedReader.equals( + "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service") + || expectedReader.equals( + "spiffe://firemud/ns/" + namespace + "/sa/automation-scripting-service"))) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java new file mode 100644 index 0000000000..463201b390 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java @@ -0,0 +1,296 @@ +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 java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +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.gamedesign.SelectedOwnerIntakeSourceClient; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +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 distinct Account producer for selected Entity and Automation intake authority. */ +public final class AccountSelectedOwnerIntakeAuthorizationService { + private static final int MAX_CREATOR_CREDENTIAL_LENGTH = 16384; + + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final SelectedOwnerIntakeSourceClient sources; + private final String namespace; + private final TransactionTemplate ownerTransaction; + + public AccountSelectedOwnerIntakeAuthorizationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountSelectedOwnerIntakeSourceReservationRepository repository, + SelectedOwnerIntakeSourceClient sources, + PlatformTransactionManager transactions, + String namespace) { + this.actors = Objects.requireNonNull(actors, "actors"); + this.fences = Objects.requireNonNull(fences, "fences"); + this.repository = Objects.requireNonNull(repository, "repository"); + this.sources = Objects.requireNonNull(sources, "sources"); + 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 distinct source-read operation, obtains exact selected content outside SQL, and + * finalizes that same operation under a freshly captured current creator and held-source vector. + * Exact final recovery happens before the mutable environment supplier is invoked. + */ + public SelectedOwnerIntakeAuthorizationBinding authorizeWithEnvironmentCapture( + String originalCreatorCredential, + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + Supplier environmentCapture) { + requireGameDesignPeer(); + outsideSql(); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + requireOwner(owner); + Objects.requireNonNull(selected, "selected Draft binding is required"); + Objects.requireNonNull(environmentCapture, "current Account environment capture is required"); + + Optional retained = + findScope(originalCreatorCredential, intakeRequestId, owner, selected); + SelectedOwnerIntakeSourceReadScope scope = null; + if (retained.isPresent()) { + scope = retained.orElseThrow(); + var recovery = recover(scope); + if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) + throw denied("Original selected-owner intake reservation was aborted"); + if (recovery.state() + == AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED) { + var original = + findFinalAuthorization(scope) + .orElseThrow( + () -> denied("Finalized selected-owner intake authorization is unavailable")); + return readFinalAuthorization(original); + } + } else { + var initialEnvironment = requireEnvironment(environmentCapture.get()); + scope = + reserveSourceRead( + originalCreatorCredential, intakeRequestId, owner, selected, initialEnvironment); + var recovery = recover(scope); + if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) + throw denied("Original selected-owner intake reservation was aborted"); + if (recovery.state() + == AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED) { + var original = + findFinalAuthorization(scope) + .orElseThrow( + () -> denied("Finalized selected-owner intake authorization is unavailable")); + return readFinalAuthorization(original); + } + } + + var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(namespace, scope); + SelectedOwnerIntakeSourceReadScope reservationScope = scope; + outsideSql(); + // The authenticated Game Design client enforces exact request echo, wire closure, six-family + // content integrity and the absence of SQL or transaction synchronization during this call. + var received = sources.read(request); + var content = requireExactContent(request, received); + + var finalizationEnvironment = requireEnvironment(environmentCapture.get()); + SelectedOwnerIntakeAuthorizationBinding finalized; + try { + finalized = + actors.withCurrent( + originalCreatorCredential, + selected.target().canonicalTenantId(), + finalizationEnvironment, + current -> + repository.finalizeSourceRead( + reservationScope, + content, + current, + () -> + fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected))); + } catch (RuntimeException finalizationFailure) { + // A commit acknowledgement can be lost after the immutable authorization commits. Recover + // only the exact same content and operation; never allocate a replacement scope or fence. + Optional committed; + try { + committed = findFinalAuthorization(reservationScope); + } catch (RuntimeException readFailure) { + if (readFailure != finalizationFailure) finalizationFailure.addSuppressed(readFailure); + throw finalizationFailure; + } + if (committed.isEmpty() + || !java.util.Arrays.equals( + committed.orElseThrow().content().canonicalBytes(), content.canonicalBytes())) { + throw finalizationFailure; + } + finalized = committed.orElseThrow(); + } + return readFinalAuthorization(finalized); + } + + private SelectedOwnerIntakeSourceReadScope reserveSourceRead( + String originalCreatorCredential, + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + CapturedEnvironmentBoundary environment) { + return actors.withCurrent( + originalCreatorCredential, + selected.target().canonicalTenantId(), + environment, + current -> + repository.reserveSourceRead( + intakeRequestId, + owner, + selected, + current, + namespace, + () -> + fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected))); + } + + private Optional findScope( + String originalCreatorCredential, + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected) { + requireGameDesignPeer(); + outsideSql(); + if (originalCreatorCredential == null + || originalCreatorCredential.isEmpty() + || originalCreatorCredential.length() > MAX_CREATOR_CREDENTIAL_LENGTH + || !StandardCharsets.US_ASCII.newEncoder().canEncode(originalCreatorCredential)) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + String tokenHash = + AccountControlUiIssuanceRepository.hash( + originalCreatorCredential.getBytes(StandardCharsets.US_ASCII)); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.findSourceReadScope( + intakeRequestId, owner, selected, namespace, tokenHash))); + } + + private AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recover( + SelectedOwnerIntakeSourceReadScope scope) { + requireScope(scope); + outsideSql(); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.recoverSourceRead(scope))); + } + + private Optional findFinalAuthorization( + SelectedOwnerIntakeSourceReadScope scope) { + requireScope(scope); + outsideSql(); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.findFinalAuthorization(scope))); + } + + private SelectedOwnerIntakeAuthorizationBinding readFinalAuthorization( + SelectedOwnerIntakeAuthorizationBinding requested) { + Objects.requireNonNull(requested, "finalized selected-owner authorization is required"); + requireScope(requested.content().scope()); + outsideSql(); + ownerTransaction.execute( + ignored -> { + repository.readFinalAuthorization(requested); + return null; + }); + return requested; + } + + private SelectedOwnerIntakeSourceContent requireExactContent( + SelectedOwnerIntakeSourceReadEvidence.Request request, + SelectedOwnerIntakeSourceContent received) { + if (received == null || !request.scope().equals(received.scope())) + throw denied("Game Design returned substituted selected-owner source content"); + try { + var checked = + SelectedOwnerIntakeSourceContent.fromStored( + received.canonicalBytes(), request.scope(), received.digest()); + for (String family : + java.util.List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + if (checked.snapshotBytes(family).length == 0) + throw new IllegalArgumentException("Selected-owner source family is empty"); + } + return checked; + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact complete selected-owner source content is required") + .withCause(invalid) + .asRuntimeException(); + } + } + + 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 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 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 static CapturedEnvironmentBoundary requireEnvironment( + CapturedEnvironmentBoundary environment) { + return Objects.requireNonNull(environment, "current Account environment is required"); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected-owner Account phases require independent transactions") + .asRuntimeException(); + } + } + + private static RuntimeException denied(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcService.java new file mode 100644 index 0000000000..0fedc11b04 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcService.java @@ -0,0 +1,90 @@ +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.AccountSelectedOwnerIntakeSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Game Design-only transport; Account alone owns the durable settlement. */ +public final class AccountSelectedOwnerIntakeSettlementGrpcService + extends AccountSelectedOwnerIntakeSettlementServiceGrpc + .AccountSelectedOwnerIntakeSettlementServiceImplBase { + private final AccountSelectedOwnerIntakeSettlementService owner; + private final String namespace; + + public AccountSelectedOwnerIntakeSettlementGrpcService( + AccountSelectedOwnerIntakeSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "Account settlement owner service required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account namespace required"); + } + this.namespace = namespace; + } + + @Override + public void settleSelectedOwnerIntake( + SelectedOwnerIntakeSettlementRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/game-design-service"; + if (SessionContext.hasAuthenticatedCallerContext() || !expectedPeer.equals(peer.uri())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + + final SelectedOwnerIntakeSettlementEvidence.Request request; + try { + request = SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + + final SelectedOwnerIntakeSettlementResponse response; + try { + var receipt = owner.settle(request.authorizationBinding()); + response = + SelectedOwnerIntakeSettlementGrpcCodec.toResponse( + new SelectedOwnerIntakeSettlementEvidence.Result(request, receipt)); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (IllegalArgumentException inconsistent) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError( + status + .withDescription("Account selected-owner settlement denied or unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java new file mode 100644 index 0000000000..deaabc463f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java @@ -0,0 +1,413 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +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 composition for settling one exact finalized selected-owner intake operation. + * + *

The Account source reservation repository owns source-lock ordering and immutable settlement + * persistence. This service only permits its pending participation to advance after an exact + * authenticated owner COMMITTED_EMPTY receipt has been read outside SQL. + */ +public final class AccountSelectedOwnerIntakeSettlementService { + private static final String AUTOMATION_READER = "automation-scripting-service"; + private static final String ENTITY_READER = "entity-management-service"; + private static final String GAME_DESIGN_CALLER = "game-design-service"; + private static final String ACCOUNT_READER = "account-service"; + + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final AutomationSelectedSourceIntakeTerminalReadClient automationClient; + private final EntitySelectedSourceIntakeTerminalReadClient entityClient; + private final TransactionTemplate ownerTransaction; + private final String namespace; + + public AccountSelectedOwnerIntakeSettlementService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + AutomationSelectedSourceIntakeTerminalReadClient automationClient, + PlatformTransactionManager transactionManager, + String namespace) { + this(repository, automationClient, null, transactionManager, namespace); + } + + public AccountSelectedOwnerIntakeSettlementService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + AutomationSelectedSourceIntakeTerminalReadClient automationClient, + EntitySelectedSourceIntakeTerminalReadClient entityClient, + PlatformTransactionManager transactionManager, + String namespace) { + this.entityClient = entityClient; + this.repository = Objects.requireNonNull(repository, "source reservation repository required"); + this.automationClient = Objects.requireNonNull(automationClient, "Automation client required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + ownerTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager required")); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Settles or recovers the exact finalized owner authorization selected by Game Design. + * + *

The authorization is a lookup key, not caller authority. Account revalidates its complete + * retained value before checking for an immutable prior settlement or contacting Automation. + */ + public AccountSelectedOwnerIntakeSettlementReceipt settle( + SelectedOwnerIntakeAuthorizationBinding original) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + requireOriginalBinding(original); + + Lookup lookup = + ownerTransaction.execute( + ignored -> { + try { + repository.readFinalAuthorization(original); + Optional prior = + Objects.requireNonNull( + repository.findSettlement(original), + "Account settlement lookup returned no result"); + return new Lookup(prior.orElse(null)); + } catch (IllegalArgumentException absentOrChanged) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact finalized selected-owner authorization is unavailable") + .withCause(absentOrChanged) + .asRuntimeException(); + } + }); + if (lookup == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account authorization transaction returned no result") + .asRuntimeException(); + } + if (lookup.prior() != null) { + return requireSettlement(lookup.prior(), original, null); + } + + if (original.owner() == Owner.ENTITY_MANAGEMENT) { + return settleEntity(original); + } + + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(namespace, original); + requireNoAmbientTransaction(); + AutomationSelectedSourceIntakeTerminalReadEvidence remote; + try { + remote = automationClient.read(request); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Automation terminal evidence is unavailable") + .withCause(unavailable) + .asRuntimeException(); + } + AutomationSelectedSourceIntakeTerminalReadEvidence exactEvidence = + requireExactTerminal(request, original, remote); + + requireNoAmbientTransaction(); + AccountSelectedOwnerIntakeSettlementReceipt committed = + ownerTransaction.execute(ignored -> repository.settleCommittedEmpty(exactEvidence)); + requireSettlement(committed, original, exactEvidence); + + // This independent lookup is deliberately lookup-only. An unknown first commit remains + // unresolved; replaying settleCommittedEmpty here could conceal its outcome. + requireNoAmbientTransaction(); + AccountSelectedOwnerIntakeSettlementReceipt readback = + ownerTransaction.execute( + ignored -> + Objects.requireNonNull( + repository.findSettlement(original), + "Account settlement readback returned no result") + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Committed Account settlement is not readable") + .asRuntimeException())); + requireSettlement(readback, original, exactEvidence); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription("Committed Account settlement readback differs") + .asRuntimeException(); + } + return readback; + } + + private AccountSelectedOwnerIntakeSettlementReceipt settleEntity( + SelectedOwnerIntakeAuthorizationBinding original) { + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(namespace, original); + requireNoAmbientTransaction(); + final EntitySelectedSourceIntakeTerminalReadEvidence remote; + try { + remote = entityClient.read(request); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Entity terminal evidence is unavailable") + .withCause(unavailable) + .asRuntimeException(); + } + final EntitySelectedSourceIntakeTerminalReadEvidence exact; + try { + if (remote == null + || !request.equals(remote.request()) + || !workloadUri(namespace, ACCOUNT_READER).equals(remote.request().intendedReader()) + || !EntitySelectedSourceIntakeTerminalReadEvidence.TERMINAL_READ_PURPOSE.equals( + remote.request().terminalReadPurpose())) { + throw new IllegalArgumentException("Entity changed the complete terminal-read request"); + } + var receipt = remote.receipt(); + byte[] bytes = receipt.canonicalBytes(); + var canonical = EntityEmptySelectedSourceIntakeReceipt.fromStored(bytes); + if (bytes.length == 0 + || bytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + || !Arrays.equals(bytes, canonical.canonicalBytes()) + || !DraftAuthorizationFenceBinding.digest(bytes).equals(receipt.receiptDigest()) + || !canonical.receiptDigest().equals(receipt.receiptDigest()) + || !"COMMITTED_EMPTY".equals(receipt.outcome()) + || !namespace.equals(receipt.targetNamespace()) + || !original.operationId().equals(receipt.operationId()) + || !original.fenceId().equals(receipt.fenceId()) + || !original.intakeRequestId().equals(receipt.intakeRequestId()) + || !original.tenantId().equals(receipt.canonicalTenantId()) + || !original.versionId().equals(receipt.canonicalVersionId()) + || !original.selected().commitId().equals(receipt.selectedCommitId()) + || !Arrays.equals(original.canonicalBytes(), receipt.authorizationBindingBytes()) + || !original.digest().equals(receipt.authorizationBindingDigest())) { + throw new IllegalArgumentException( + "Entity terminal differs from the original authorization"); + } + exact = new EntitySelectedSourceIntakeTerminalReadEvidence(request, canonical); + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact original Entity terminal is required") + .withCause(invalid) + .asRuntimeException(); + } + requireNoAmbientTransaction(); + var committed = + ownerTransaction.execute(ignored -> repository.settleEntityCommittedEmpty(exact)); + requireSettlement(committed, original, exact); + requireNoAmbientTransaction(); + var readback = + ownerTransaction.execute( + ignored -> + Objects.requireNonNull( + repository.findSettlement(original), "Account lookup returned no result") + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Committed Account Entity settlement is not readable") + .asRuntimeException())); + requireSettlement(readback, original, exact); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription("Committed Account Entity readback differs") + .asRuntimeException(); + } + return readback; + } + + private void requireGameDesignPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Authenticated Game Design workload is required") + .asRuntimeException(); + } + String expectedUri = workloadUri(namespace, GAME_DESIGN_CALLER); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedUri.equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Game Design workload without end-user context required") + .asRuntimeException(); + } + } + + private void requireOriginalBinding(SelectedOwnerIntakeAuthorizationBinding original) { + if (original == null + || (original.owner() != Owner.AUTOMATION_SCRIPTING + && original.owner() != Owner.ENTITY_MANAGEMENT) + || !namespace.equals(original.targetNamespace()) + || !(original.owner() == Owner.AUTOMATION_SCRIPTING + ? "account-automation-intake-authorization/v1".equals(original.schema()) + && "AUTOMATION_INTAKE_RETENTION".equals(original.purpose()) + && workloadUri(namespace, AUTOMATION_READER).equals(original.intendedReader()) + : entityClient != null + && "account-entity-intake-authorization/v1".equals(original.schema()) + && "ENTITY_INTAKE_RETENTION".equals(original.purpose()) + && workloadUri(namespace, ENTITY_READER).equals(original.intendedReader()))) { + throw Status.FAILED_PRECONDITION + .withDescription("Canonical same-namespace selected-owner authorization is required") + .asRuntimeException(); + } + try { + byte[] bytes = original.canonicalBytes(); + SelectedOwnerIntakeAuthorizationBinding canonical = + SelectedOwnerIntakeAuthorizationBinding.fromStored(bytes); + if (bytes.length == 0 + || bytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + || !Arrays.equals(bytes, canonical.canonicalBytes()) + || !original.digest().equals(canonical.digest())) { + throw new IllegalArgumentException("Noncanonical selected-owner authorization"); + } + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Canonical same-namespace selected-owner authorization is required") + .withCause(invalid) + .asRuntimeException(); + } + } + + private AutomationSelectedSourceIntakeTerminalReadEvidence requireExactTerminal( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request, + SelectedOwnerIntakeAuthorizationBinding original, + AutomationSelectedSourceIntakeTerminalReadEvidence remote) { + if (remote == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Automation returned no terminal evidence") + .asRuntimeException(); + } + try { + var echoed = remote.request(); + if (!request.equals(echoed) + || echoed.schemaVersion() + != AutomationSelectedSourceIntakeTerminalReadEvidence.SCHEMA_VERSION + || !namespace.equals(echoed.targetNamespace()) + || !request.readRequestId().equals(echoed.readRequestId()) + || !Arrays.equals(original.canonicalBytes(), echoed.binding().canonicalBytes()) + || !workloadUri(namespace, ACCOUNT_READER).equals(echoed.intendedReader()) + || !AutomationSelectedSourceIntakeTerminalReadEvidence.TERMINAL_READ_PURPOSE.equals( + echoed.terminalReadPurpose())) { + throw new IllegalArgumentException("Automation changed the complete terminal-read request"); + } + + AutomationEmptySelectedSourceIntakeReceipt receipt = remote.receipt(); + byte[] receiptBytes = receipt.canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + || !DraftAuthorizationFenceBinding.digest(receiptBytes).equals(receipt.receiptDigest()) + || !"COMMITTED_EMPTY".equals(receipt.outcome()) + || !namespace.equals(receipt.targetNamespace()) + || !original.operationId().equals(receipt.operationId()) + || !original.fenceId().equals(receipt.fenceId()) + || !original.intakeRequestId().equals(receipt.intakeRequestId()) + || !original.tenantId().equals(receipt.canonicalTenantId()) + || !original.versionId().equals(receipt.canonicalVersionId()) + || !original.selected().commitId().equals(receipt.selectedCommitId()) + || !Arrays.equals(original.canonicalBytes(), receipt.authorizationBindingBytes()) + || !original.digest().equals(receipt.authorizationBindingDigest())) { + throw new IllegalArgumentException( + "Automation receipt is not the canonical original terminal"); + } + AutomationSelectedSourceIntakeTerminalReadEvidence exact = + new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt); + if (!Arrays.equals(receiptBytes, exact.receipt().canonicalBytes()) + || !receipt.receiptDigest().equals(exact.receipt().receiptDigest())) { + throw new IllegalArgumentException("Automation terminal receipt changed during validation"); + } + return exact; + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Automation terminal differs from the exact original authorization") + .withCause(invalid) + .asRuntimeException(); + } + } + + private AccountSelectedOwnerIntakeSettlementReceipt requireSettlement( + AccountSelectedOwnerIntakeSettlementReceipt receipt, + SelectedOwnerIntakeAuthorizationBinding original, + Object expectedOwnerTerminal) { + if (receipt == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account terminal settlement receipt is unavailable") + .asRuntimeException(); + } + try { + if (!Arrays.equals(original.canonicalBytes(), receipt.authorizationBinding().canonicalBytes()) + || !original.digest().equals(receipt.authorizationBinding().digest()) + || !original.operationId().equals(receipt.operationId()) + || !namespace.equals(receipt.targetNamespace()) + || !Arrays.equals( + original.canonicalBytes(), + (original.owner() == Owner.ENTITY_MANAGEMENT + ? receipt.entityTerminalEvidence().request().binding() + : receipt.terminalEvidence().request().binding()) + .canonicalBytes())) { + throw new IllegalArgumentException("Account settlement changed the original binding"); + } + AccountSelectedOwnerIntakeSettlementReceipt canonical = + original.owner() == Owner.ENTITY_MANAGEMENT + ? AccountSelectedOwnerIntakeSettlementReceipt.create(receipt.entityTerminalEvidence()) + : AccountSelectedOwnerIntakeSettlementReceipt.create(receipt.terminalEvidence()); + if (!Arrays.equals(canonical.canonicalBytes(), receipt.canonicalBytes()) + || !canonical.digest().equals(receipt.digest()) + || (expectedOwnerTerminal + instanceof AutomationSelectedSourceIntakeTerminalReadEvidence automation + && !receipt.sameImmutableOwnerReceipt(automation)) + || (expectedOwnerTerminal instanceof EntitySelectedSourceIntakeTerminalReadEvidence entity + && !receipt.sameImmutableOwnerReceipt(entity))) { + throw new IllegalArgumentException( + "Account settlement receipt changed its canonical owner value"); + } + return receipt; + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Account settlement receipt differs from the original owner terminal") + .withCause(invalid) + .asRuntimeException(); + } + } + + private static boolean sameSettlement( + AccountSelectedOwnerIntakeSettlementReceipt left, + AccountSelectedOwnerIntakeSettlementReceipt right) { + return left.digest().equals(right.digest()) + && Arrays.equals(left.canonicalBytes(), right.canonicalBytes()); + } + + private static String workloadUri(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Account terminal settlement requires independent transactions") + .asRuntimeException(); + } + } + + private record Lookup(AccountSelectedOwnerIntakeSettlementReceipt prior) {} +} 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 index 85bbbc1e1e..ec50e5e71b 100644 --- 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 @@ -11,21 +11,32 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; 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 net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; 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. */ +/** + * Immutable Entity/Automation preliminary reservations, finalized source retention, and exact + * Automation {@code COMMITTED_EMPTY} terminal settlement. + */ 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 static final String AUTHORIZATIONS = "account_selected_owner_intake_authorizations"; + private static final String AUTHORIZATION_SOURCES = "account_selected_owner_intake_sources"; + private static final String SETTLEMENTS = "account_selected_owner_intake_settlements"; private final DSLContext dsl; @@ -35,6 +46,7 @@ public AccountSelectedOwnerIntakeSourceReservationRepository(DSLContext dsl) { public enum State { RESERVED, + FINALIZED, ABORTED } @@ -173,7 +185,13 @@ Recovery recoverSourceRead(SelectedOwnerIntakeSourceReadScope scope) { Record row = reservation(scope); requireReservation(row, scope); if (aborted(scope)) return new Recovery(scope, State.ABORTED); - return new Recovery(scope, State.RESERVED); + var authorization = authorization(scope.operationId()); + if (authorization == null) return new Recovery(scope, State.RESERVED); + var binding = + SelectedOwnerIntakeAuthorizationBinding.fromStored( + authorization.get("binding_bytes", byte[].class)); + requireAuthorization(authorization, binding); + return new Recovery(scope, State.FINALIZED); } Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) { @@ -181,17 +199,374 @@ Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) { lockReservedSources(scope); Record row = reservation(scope); requireReservation(row, scope); + if (authorization(scope.operationId()) != null) { + throw new IllegalStateException("Finalized owner intake cannot be preliminarily aborted"); + } if (!aborted(scope)) { dsl.execute("INSERT INTO " + ABORTS + " (operation_id) VALUES (?)", scope.operationId()); } return new Recovery(scope, State.ABORTED); } + SelectedOwnerIntakeAuthorizationBinding finalizeSourceRead( + SelectedOwnerIntakeSourceReadScope scope, + SelectedOwnerIntakeSourceContent content, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + Objects.requireNonNull(content, "content"); + Objects.requireNonNull(current, "current"); + Objects.requireNonNull(admission, "admission"); + lockReservedSources(scope); + Record reserved = reservation(scope); + requireReservation(reserved, scope); + requireCurrentReservation(reserved, current); + if (!scope.equals(content.scope())) + throw new IllegalArgumentException("Selected content differs from original source scope"); + if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + + Record row = authorization(scope.operationId()); + if (row != null) { + var original = + SelectedOwnerIntakeAuthorizationBinding.fromStored( + row.get("binding_bytes", byte[].class)); + if (!Arrays.equals(original.content().canonicalBytes(), content.canonicalBytes())) + throw new IllegalArgumentException( + "Intake request identity conflicts with original selected content"); + requireAuthorization(row, original); + return original; + } + + List sourceVector = current.source().sources(); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, sourceVector); + admission.run(); + dsl.execute( + "INSERT INTO " + + AUTHORIZATIONS + + " (operation_id, fence_id, intake_request_id, owner, target_namespace, actor_account_uuid, " + + "tenant_uuid, version_uuid, content_bytes, content_digest, binding_bytes, binding_digest, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.owner().name(), + binding.targetNamespace(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.canonicalBytes(), + binding.digest(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + AccountControlUiAuthority.canonical(current.source().outboxCheckpoints())); + for (SourceEvidence source : binding.sources()) { + dsl.execute( + "INSERT INTO " + + AUTHORIZATION_SOURCES + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + requireAuthorization( + dsl.fetchOne( + "SELECT * FROM " + AUTHORIZATIONS + " WHERE operation_id = ? FOR UPDATE", + binding.operationId()), + binding); + return binding; + } + + Optional findFinalAuthorization( + SelectedOwnerIntakeSourceReadScope scope) { + requireTransaction(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record row = authorization(scope.operationId()); + if (row == null) return Optional.empty(); + var binding = + SelectedOwnerIntakeAuthorizationBinding.fromStored(row.get("binding_bytes", byte[].class)); + requireAuthorization(row, binding); + if (!scope.equals(binding.content().scope())) + throw new IllegalArgumentException("Finalized authorization differs from original scope"); + return Optional.of(binding); + } + + /** Historical exact authorization read; settled orders remain recoverable through this path. */ + void readFinalAuthorization(SelectedOwnerIntakeAuthorizationBinding requested) { + readFinalAuthorization(requested, false); + } + + /** + * External HELD reads deny after exact terminal settlement; historical reads remain available. + */ + void readHeldFinalAuthorization(SelectedOwnerIntakeAuthorizationBinding requested) { + readFinalAuthorization(requested, true); + } + + private void readFinalAuthorization( + SelectedOwnerIntakeAuthorizationBinding requested, boolean requireHeld) { + requireTransaction(); + Objects.requireNonNull(requested, "requested"); + Record lookup = authorizationLookup(requested.operationId()); + if (lookup == null + || !Arrays.equals(requested.canonicalBytes(), lookup.get("binding_bytes", byte[].class))) + throw new IllegalArgumentException( + "Original finalized owner authorization absent or changed"); + var original = + SelectedOwnerIntakeAuthorizationBinding.fromStored( + lookup.get("binding_bytes", byte[].class)); + SelectedOwnerIntakeSourceReadScope scope = original.content().scope(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record row = authorization(original.operationId()); + requireAuthorization(row, original); + if (aborted(original.content().scope())) + throw new IllegalArgumentException("Finalized owner authorization cannot be aborted"); + if (requireHeld && settlement(original.operationId()) != null) { + throw new IllegalArgumentException("Settled owner authorization is no longer held"); + } + } + + /** + * Exact committed settlement recovery; callers perform this before any external terminal read. + */ + Optional findSettlement( + SelectedOwnerIntakeAuthorizationBinding requested) { + requireTransaction(); + Objects.requireNonNull(requested, "original selected-owner authorization is required"); + if (requested.owner() != Owner.AUTOMATION_SCRIPTING + && requested.owner() != Owner.ENTITY_MANAGEMENT) { + throw new IllegalArgumentException("Automation terminal settlement required"); + } + SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record order = authorization(requested.operationId()); + requireAuthorization(order, requested); + if (aborted(scope)) + throw new IllegalArgumentException("Finalized owner authorization was aborted"); + Record row = settlement(requested.operationId()); + if (row == null) return Optional.empty(); + return Optional.of(exactSettlement(row, requested, null)); + } + + /** + * Commits one immutable COMMITTED_EMPTY owner receipt after the authenticated owner read has + * completed outside SQL. The read correlation is retained on first write but is not settlement + * identity; a fresh correlation with identical owner receipt bytes recovers the first receipt. + */ + AccountSelectedOwnerIntakeSettlementReceipt settleCommittedEmpty( + AutomationSelectedSourceIntakeTerminalReadEvidence evidence) { + requireTransaction(); + Objects.requireNonNull(evidence, "Automation terminal evidence is required"); + var requested = evidence.request().binding(); + if (requested.owner() != Owner.AUTOMATION_SCRIPTING + || !"COMMITTED_EMPTY".equals(evidence.receipt().outcome())) { + throw new IllegalArgumentException("Exact Automation COMMITTED_EMPTY evidence required"); + } + SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record order = authorization(requested.operationId()); + requireAuthorization(order, requested); + if (aborted(scope)) + throw new IllegalArgumentException("Finalized owner authorization was aborted"); + + Record prior = settlement(requested.operationId()); + if (prior != null) return exactSettlement(prior, requested, evidence); + + AccountSelectedOwnerIntakeSettlementReceipt receipt = + AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + dsl.execute( + "INSERT INTO " + + SETTLEMENTS + + " (operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " + + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + requested.fenceId(), + requested.intakeRequestId(), + requested.owner().name(), + requested.targetNamespace(), + requested.tenantId(), + requested.versionId(), + requested.canonicalBytes(), + requested.digest(), + evidence.request().readRequestId(), + receipt.ownerReceiptBytes(), + receipt.ownerReceiptDigest(), + receipt.canonicalBytes(), + receipt.digest()); + return exactSettlement(settlement(requested.operationId()), requested, evidence); + } + + AccountSelectedOwnerIntakeSettlementReceipt settleEntityCommittedEmpty( + EntitySelectedSourceIntakeTerminalReadEvidence evidence) { + requireTransaction(); + Objects.requireNonNull(evidence, "Entity terminal evidence is required"); + var requested = evidence.request().binding(); + if (requested.owner() != Owner.ENTITY_MANAGEMENT + || !"COMMITTED_EMPTY".equals(evidence.receipt().outcome())) { + throw new IllegalArgumentException("Exact Entity COMMITTED_EMPTY evidence required"); + } + SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record order = authorization(requested.operationId()); + requireAuthorization(order, requested); + if (aborted(scope)) + throw new IllegalArgumentException("Finalized owner authorization was aborted"); + + Record prior = settlement(requested.operationId()); + if (prior != null) return exactSettlement(prior, requested, evidence); + + AccountSelectedOwnerIntakeSettlementReceipt receipt = + AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + dsl.execute( + "INSERT INTO " + + SETTLEMENTS + + " (operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " + + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + requested.fenceId(), + requested.intakeRequestId(), + requested.owner().name(), + requested.targetNamespace(), + requested.tenantId(), + requested.versionId(), + requested.canonicalBytes(), + requested.digest(), + evidence.request().readRequestId(), + receipt.ownerReceiptBytes(), + receipt.ownerReceiptDigest(), + receipt.canonicalBytes(), + receipt.digest()); + return exactSettlement(settlement(requested.operationId()), requested, evidence); + } + + private AccountSelectedOwnerIntakeSettlementReceipt exactSettlement( + Record row, SelectedOwnerIntakeAuthorizationBinding requested, Object retryEvidence) { + if (row == null) throw new IllegalStateException("Account settlement commit readback absent"); + byte[] storedBytes = row.get("receipt_bytes", byte[].class); + var receipt = AccountSelectedOwnerIntakeSettlementReceipt.fromStored(storedBytes); + var original = receipt.authorizationBinding(); + if (!Arrays.equals(original.canonicalBytes(), requested.canonicalBytes()) + || !Arrays.equals(storedBytes, receipt.canonicalBytes()) + || !receipt.digest().equals(row.get("receipt_digest", String.class)) + || !Arrays.equals( + receipt.ownerReceiptBytes(), row.get("terminal_receipt_bytes", byte[].class)) + || !receipt.ownerReceiptDigest().equals(row.get("terminal_receipt_digest", String.class)) + || !receipt.terminalReadRequestId().equals(row.get("terminal_read_request_id", UUID.class)) + || !original.operationId().equals(row.get("operation_id", UUID.class)) + || !original.fenceId().equals(row.get("fence_id", UUID.class)) + || !original.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !original.owner().name().equals(row.get("owner", String.class)) + || !original.targetNamespace().equals(row.get("target_namespace", String.class)) + || !original.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !original.versionId().equals(row.get("version_uuid", UUID.class)) + || !Arrays.equals(original.canonicalBytes(), row.get("binding_bytes", byte[].class)) + || !original.digest().equals(row.get("binding_digest", String.class))) { + throw new IllegalArgumentException("Changed exact selected-owner terminal settlement"); + } + if (retryEvidence instanceof AutomationSelectedSourceIntakeTerminalReadEvidence automation + && !receipt.sameImmutableOwnerReceipt(automation)) { + throw new IllegalArgumentException("Changed Automation owner terminal receipt"); + } + if (retryEvidence instanceof EntitySelectedSourceIntakeTerminalReadEvidence entity + && !receipt.sameImmutableOwnerReceipt(entity)) { + throw new IllegalArgumentException("Changed Entity owner terminal receipt"); + } + return receipt; + } + + private Record settlement(UUID operationId) { + return dsl.fetchOne( + "SELECT * FROM " + SETTLEMENTS + " WHERE operation_id = ? FOR UPDATE", operationId); + } + + private Record authorization(UUID operationId) { + return dsl.fetchOne( + "SELECT * FROM " + AUTHORIZATIONS + " WHERE operation_id = ? FOR UPDATE", operationId); + } + + private Record authorizationLookup(UUID operationId) { + return dsl.fetchOne("SELECT * FROM " + AUTHORIZATIONS + " WHERE operation_id = ?", operationId); + } + + private void requireAuthorization(Record row, SelectedOwnerIntakeAuthorizationBinding binding) { + if (row == null + || !Arrays.equals(binding.canonicalBytes(), row.get("binding_bytes", byte[].class)) + || !binding.digest().equals(row.get("binding_digest", String.class)) + || !Arrays.equals( + binding.content().canonicalBytes(), row.get("content_bytes", byte[].class)) + || !binding.content().digest().equals(row.get("content_digest", String.class)) + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !binding.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !binding.owner().name().equals(row.get("owner", String.class)) + || !binding.targetNamespace().equals(row.get("target_namespace", String.class)) + || !binding.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.versionId().equals(row.get("version_uuid", UUID.class))) { + throw new IllegalArgumentException( + "Original finalized owner authorization absent or changed"); + } + Record reserved = reservation(binding.content().scope()); + requireReservation(reserved, binding.content().scope()); + if (!binding.operationId().equals(reserved.get("operation_id", UUID.class)) + || !binding.fenceId().equals(reserved.get("fence_id", UUID.class)) + || !binding.intakeRequestId().equals(reserved.get("intake_request_id", UUID.class)) + || !binding.owner().name().equals(reserved.get("owner", String.class)) + || !binding.actorAccountId().equals(reserved.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(reserved.get("tenant_uuid", UUID.class)) + || !binding.versionId().equals(reserved.get("version_uuid", UUID.class))) { + throw new IllegalArgumentException( + "Finalized authorization differs from original reservation"); + } + var issuer = issuer(reserved.get("issuance_operation_id", UUID.class)); + if (!issuer.operationId.equals(row.get("issuance_operation_id", UUID.class)) + || !Objects.equals( + reserved.get("issuance_fence", Long.class), row.get("issuance_fence", Long.class)) + || !Arrays.equals(issuer.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(issuer.bundle, row.get("issuance_bundle", byte[].class)) + || !Arrays.equals( + reserved.get("outbox_checkpoints", byte[].class), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Changed finalized creator evidence"); + } + List sources = + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + AUTHORIZATION_SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + binding.operationId()); + if (sources.size() != binding.sources().size()) + throw new IllegalArgumentException("Incomplete finalized source participation"); + for (int index = 0; index < sources.size(); index++) { + SourceEvidence source = binding.sources().get(index); + if (!source.key().equals(sources.get(index).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), sources.get(index).get("source_evidence", byte[].class))) { + throw new IllegalArgumentException("Changed finalized source participation"); + } + } + } + SourceReadCurrentness sourceReadCurrentness(SelectedOwnerIntakeSourceReadScope scope) { requireTransaction(); Record row = reservation(scope); requireReservation(row, scope); if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + if (authorization(scope.operationId()) != null) + throw new IllegalStateException("Finalized owner intake is not a preliminary source read"); 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"); @@ -204,6 +579,8 @@ void readSourceScope(SelectedOwnerIntakeSourceReadScope scope, SourceReadCurrent Record row = reservation(scope); requireReservation(row, scope); if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + if (authorization(scope.operationId()) != null) + throw new IllegalStateException("Finalized owner intake is not a preliminary source read"); 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"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..7e70c238c2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService.java @@ -0,0 +1,88 @@ +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.AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Standalone receiver: authenticate exact World before parsing a caller-carried binding. */ +public final class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService + extends AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceImplBase { + private final AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService owner; + private final String namespace; + + public AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService( + AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "World closure authorization reader is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readHeldSelectedOwnerWorldClosureAuthorization( + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String peerUri = peer.uri(); + String expectedReader = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedReader.equals(peerUri)) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() + > SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + final SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request decoded; + try { + decoded = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(decoded.targetNamespace()) || !peerUri.equals(decoded.intendedReader())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + try { + owner.requireHeld(decoded); + observer.onNext( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java new file mode 100644 index 0000000000..190a47e7b6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +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 World HELD read; it neither creates authority nor settles participation. */ +public final class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final TransactionTemplate ownerTransaction; + private final String namespace; + + public AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.repository = + Objects.requireNonNull(repository, "source reservation repository is required"); + 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); + } + + /** Confirms the exact finalized authorization and source locks in an independent transaction. */ + public void requireHeld( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "World closure authorization-read request is required"); + requirePeer(namespace, request.intendedReader()); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + try { + ownerTransaction.execute( + ignored -> { + repository.readHeldFinalAuthorization(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException changedOrAbsent) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } + } + + static void requirePeer(String namespace, String expectedReader) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + String worldReader = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !worldReader.equals(peer.uri()) + || !worldReader.equals(expectedReader)) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_final_authorizations.sql b/services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_final_authorizations.sql new file mode 100644 index 0000000000..2035ae015c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_final_authorizations.sql @@ -0,0 +1,457 @@ +-- Final Entity/Automation retention authorization. Without an authenticated owner terminal, +-- this order remains held indefinitely; there is deliberately no timeout or local settlement. +CREATE TABLE account_selected_owner_intake_authorizations ( + operation_id UUID PRIMARY KEY + REFERENCES account_selected_owner_intake_source_read_reservations(operation_id), + fence_id UUID NOT NULL UNIQUE, + intake_request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL CHECK (owner IN ('ENTITY_MANAGEMENT', 'AUTOMATION_SCRIPTING')), + target_namespace VARCHAR(63) NOT NULL, + 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, + content_bytes BYTEA NOT NULL CHECK (octet_length(content_bytes) BETWEEN 1 AND 8388608), + content_digest VARCHAR(71) NOT NULL CHECK (content_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_bytes BYTEA NOT NULL CHECK (octet_length(binding_bytes) BETWEEN 1 AND 16777216), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_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(), + finalized_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_sources ( + operation_id UUID NOT NULL REFERENCES account_selected_owner_intake_authorizations(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_lookup + ON account_selected_owner_intake_sources(source_key, operation_id); + +-- [jooq ignore start] +-- Serialize finalization and preliminary abort with the same sorted source-lock then reservation +-- order used by the existing V1006 abort path. +CREATE OR REPLACE 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) + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Only an unfinalized active preliminary owner reservation can be aborted' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_selected_owner_intake_authorization_serialize() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_owner_intake_source_read_reservations%ROWTYPE; +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; + SELECT * INTO STRICT original FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id) + OR NEW.producer_xid <> txid_current() + OR NEW.operation_id IS DISTINCT FROM original.operation_id + OR NEW.fence_id IS DISTINCT FROM original.fence_id + OR NEW.intake_request_id IS DISTINCT FROM original.intake_request_id + OR NEW.owner IS DISTINCT FROM original.owner + OR NEW.actor_account_uuid IS DISTINCT FROM original.actor_account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR NEW.version_uuid IS DISTINCT FROM original.version_uuid + OR NEW.issuance_operation_id IS DISTINCT FROM original.issuance_operation_id + OR NEW.issuance_fence IS DISTINCT FROM original.issuance_fence + OR NEW.source_payload IS DISTINCT FROM original.source_payload + OR NEW.issuance_bundle IS DISTINCT FROM original.issuance_bundle + OR NEW.outbox_checkpoints IS DISTINCT FROM original.outbox_checkpoints THEN + RAISE EXCEPTION 'Finalization must bind the exact active preliminary owner reservation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_selected_owner_intake_authorization_serialize + BEFORE INSERT ON account_selected_owner_intake_authorizations + FOR EACH ROW EXECUTE FUNCTION account_selected_owner_intake_authorization_serialize(); + +CREATE FUNCTION account_selected_owner_intake_authorization_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + q INTEGER := 1; + scope_position INTEGER := 1; + source_position INTEGER := 1; + parsed BYTEA; + scope_bytes BYTEA; + content_bytes BYTEA; + selected_bytes BYTEA; + source_bytes BYTEA; + snapshot_bytes BYTEA; + source_schema TEXT; + text_value TEXT; + scope_schema TEXT; + scope_owner TEXT; + namespace_value TEXT; + operation_value TEXT; + fence_value TEXT; + request_value TEXT; + actor_value TEXT; + selected_digest TEXT; + scope_digest TEXT; + content_digest TEXT; + binding_schema TEXT; + expected_binding_schema TEXT; + recipient_value TEXT; + purpose_value TEXT; + count_text TEXT; + source_count INTEGER; + max_source_count INTEGER; + source_index INTEGER := 0; + family_value TEXT; + family_digest TEXT; + family_schema TEXT; + expected_family_schema TEXT; + snapshot JSONB; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + generation_marker TEXT; + vector JSONB; + seen TEXT[] := ARRAY[]::TEXT[]; + previous_key TEXT; + original account_selected_owner_intake_source_read_reservations%ROWTYPE; + issuer account_control_ui_issuance_operations%ROWTYPE; + expected_schema TEXT; + expected_purpose TEXT; + expected_reader TEXT; + families TEXT[] := ARRAY['COMMAND', 'REALM_POLICY', 'ASSET', 'GAMEPLAY_RULE', 'BRANDING', 'TEMPLATE_CONFIG']; +BEGIN + SELECT * INTO STRICT original FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id; + 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 NEW.binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.binding_bytes), 'hex') + OR NEW.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.content_bytes), 'hex') + 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 original.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(original.scope_bytes), 'hex') + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Finalized authorization requires exact current committed creator evidence' + USING ERRCODE = '23514'; + END IF; + + -- The complete selected-owner authorization frame is closed and content-bound. + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + binding_schema := convert_from(parsed, 'UTF8'); + SELECT frame_value, next_position INTO content_bytes, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO content_digest, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + IF content_bytes IS DISTINCT FROM NEW.content_bytes + OR content_digest IS DISTINCT FROM NEW.content_digest THEN + RAISE EXCEPTION 'Finalized authorization differs from exact selected content' + USING ERRCODE = '23514'; + END IF; + + -- Decode preliminary scope from the content and require the exact retained owner tuple. + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF convert_from(parsed, 'UTF8') <> 'game-design-selected-owner-intake-source/v1' THEN + RAISE EXCEPTION 'Unknown selected owner content schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO scope_bytes, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO scope_digest, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF scope_bytes IS DISTINCT FROM original.scope_bytes + OR scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(scope_bytes), 'hex') THEN + RAISE EXCEPTION 'Selected content scope differs from original reservation' + USING ERRCODE = '23514'; + END IF; + + SELECT frame_value, next_position INTO parsed, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + scope_schema := convert_from(parsed, 'UTF8'); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO scope_owner, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO operation_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO fence_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO request_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO actor_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT frame_value, next_position INTO selected_bytes, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO selected_digest, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + IF scope_owner = 'ENTITY_MANAGEMENT' THEN + expected_schema := 'account-entity-intake-source-read/v1'; + expected_purpose := 'ENTITY_INTAKE_SOURCE'; + expected_reader := 'spiffe://firemud/ns/' || namespace_value || '/sa/account-service'; + expected_binding_schema := 'account-entity-intake-authorization/v1'; + ELSIF scope_owner = 'AUTOMATION_SCRIPTING' THEN + expected_schema := 'account-automation-intake-source-read/v1'; + expected_purpose := 'AUTOMATION_INTAKE_SOURCE'; + expected_reader := 'spiffe://firemud/ns/' || namespace_value || '/sa/account-service'; + expected_binding_schema := 'account-automation-intake-authorization/v1'; + ELSE + RAISE EXCEPTION 'Unknown selected owner domain' USING ERRCODE = '23514'; + END IF; + IF scope_schema IS DISTINCT FROM expected_schema + OR namespace_value !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR operation_value IS DISTINCT FROM NEW.operation_id::TEXT + OR fence_value IS DISTINCT FROM NEW.fence_id::TEXT + OR request_value IS DISTINCT FROM NEW.intake_request_id::TEXT + OR actor_value IS DISTINCT FROM NEW.actor_account_uuid::TEXT + OR selected_digest IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR NEW.owner IS DISTINCT FROM scope_owner + OR NEW.target_namespace IS DISTINCT FROM namespace_value + OR NEW.actor_account_uuid::TEXT IS DISTINCT FROM actor_value + OR NEW.tenant_uuid::TEXT IS DISTINCT FROM convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalTenantId' + OR NEW.version_uuid::TEXT IS DISTINCT FROM convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalVersionId' + THEN + RAISE EXCEPTION 'Selected owner scope fields differ from finalized authorization' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + IF text_value IS DISTINCT FROM expected_reader THEN + RAISE EXCEPTION 'Selected owner Account reader differs from closed scope' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + IF text_value IS DISTINCT FROM expected_purpose + OR scope_position <> octet_length(scope_bytes) + 1 THEN + RAISE EXCEPTION 'Selected owner scope has an unknown purpose or trailing bytes' + USING ERRCODE = '23514'; + END IF; + + -- Exactly six named canonical snapshots, each tied to this exact selected Draft binding. + FOR family_value IN SELECT unnest(families) LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT frame_value, next_position INTO snapshot_bytes, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO family_digest, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF text_value IS DISTINCT FROM family_value + OR octet_length(snapshot_bytes) = 0 + OR family_digest IS DISTINCT FROM 'sha256:' || encode(sha256(snapshot_bytes), 'hex') THEN + RAISE EXCEPTION 'Selected owner content family is missing, unknown, or changed' + USING ERRCODE = '23514'; + END IF; + snapshot := convert_from(snapshot_bytes, 'UTF8')::JSONB; + family_schema := snapshot->>'schema'; + expected_family_schema := CASE family_value + WHEN 'COMMAND' THEN 'game-design-command-source-snapshot/v1' + WHEN 'REALM_POLICY' THEN 'game-design-realm-policy-snapshot/v1' + WHEN 'ASSET' THEN 'game-design-ordinary-asset-source-snapshot/v1' + WHEN 'GAMEPLAY_RULE' THEN 'game-design-gameplay-rule-source-snapshot/v1' + WHEN 'BRANDING' THEN 'game-design-branding-asset-source-snapshot/v1' + ELSE NULL END; + IF jsonb_typeof(snapshot) IS DISTINCT FROM 'object' + OR snapshot->>'bindingJson' IS DISTINCT FROM convert_from(selected_bytes, 'UTF8') + OR snapshot->>'bindingDigest' IS DISTINCT FROM selected_digest + OR (family_value = 'TEMPLATE_CONFIG' + AND (family_schema IS NULL OR family_schema NOT IN ( + 'game-design-template-config-source-snapshot/v1', + 'game-design-template-config-source-snapshot/v2'))) + OR (family_value <> 'TEMPLATE_CONFIG' + AND family_schema IS DISTINCT FROM expected_family_schema) THEN + RAISE EXCEPTION 'Selected owner family differs from exact selected Draft binding' + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF q <> octet_length(content_bytes) + 1 THEN + RAISE EXCEPTION 'Selected owner content has trailing or extra family bytes' + USING ERRCODE = '23514'; + END IF; + + -- Final authorization reader/purpose and all source evidence frames are closed. + SELECT convert_from(frame_value, 'UTF8'), next_position INTO recipient_value, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO purpose_value, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + IF binding_schema IS DISTINCT FROM expected_binding_schema + OR recipient_value IS DISTINCT FROM + (CASE scope_owner WHEN 'ENTITY_MANAGEMENT' + THEN 'spiffe://firemud/ns/' || namespace_value || '/sa/entity-management-service' + ELSE 'spiffe://firemud/ns/' || namespace_value || '/sa/automation-scripting-service' END) + OR purpose_value IS DISTINCT FROM + (CASE scope_owner WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY_INTAKE_RETENTION' + ELSE 'AUTOMATION_INTAKE_RETENTION' END) + OR count_text !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Finalized authorization schema, reader, purpose, or source count is invalid' + USING ERRCODE = '23514'; + END IF; + max_source_count := (octet_length(NEW.binding_bytes) - p) / 4; + IF length(count_text) > length(max_source_count::TEXT) THEN + RAISE EXCEPTION 'Finalized source count exceeds remaining canonical frame capacity' + USING ERRCODE = '23514'; + END IF; + source_count := count_text::INTEGER; + vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; + IF source_count < 1 OR source_count > max_source_count + OR jsonb_typeof(vector) IS DISTINCT FROM 'array' + OR jsonb_array_length(vector) IS DISTINCT FROM source_count + OR (SELECT count(*) FROM account_selected_owner_intake_sources + WHERE operation_id = NEW.operation_id) IS DISTINCT FROM source_count THEN + RAISE EXCEPTION 'Finalized authorization requires the complete current source vector' + USING ERRCODE = '23514'; + END IF; + FOR source_index IN 1..source_count LOOP + SELECT frame_value, next_position INTO source_bytes, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + IF source_bytes IS DISTINCT FROM decode(vector->>(source_index - 1), 'base64') + OR octet_length(source_bytes) > 131072 THEN + RAISE EXCEPTION 'Finalized source differs from current issuer source vector' + USING ERRCODE = '23514'; + END IF; + source_position := 1; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_schema, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + 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 generation_marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF generation_marker = 'PRESENT' THEN + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF text_value !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid finalized source generation' USING ERRCODE = '23514'; + END IF; + ELSIF generation_marker <> 'ABSENT' THEN + RAISE EXCEPTION 'Invalid finalized source generation marker' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF text_value !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid finalized source version' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO generation_marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF generation_marker = 'PRESENT' THEN + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF octet_length(parsed) = 0 THEN + RAISE EXCEPTION 'Invalid finalized source checkpoint stream' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF text_value !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid finalized source checkpoint sequence' USING ERRCODE = '23514'; + END IF; + ELSIF generation_marker <> 'ABSENT' THEN + RAISE EXCEPTION 'Invalid finalized source checkpoint marker' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + IF source_schema <> 'account-draft-source-evidence/v1' + OR source_kind NOT IN ('ISSUER', 'ACCOUNT', 'TENANT', 'MEMBERSHIP', 'GLOBAL_ROLES', 'CREATOR_PARTY', 'HOSTED_TERMS') + OR source_scope = '' OR source_position <> octet_length(source_bytes) + 1 + OR octet_length(parsed) = 0 OR source_key_value = ANY(seen) + OR (previous_key IS NOT NULL AND + account_publication_authorization_source_sort_key(previous_key) >= + account_publication_authorization_source_sort_key(source_key_value)) + OR (source_kind IN ('ACCOUNT', 'GLOBAL_ROLES') AND source_scope IS DISTINCT FROM actor_value) + OR (source_kind = 'TENANT' AND source_scope IS DISTINCT FROM NEW.tenant_uuid::TEXT) + OR (source_kind = 'MEMBERSHIP' AND source_scope IS DISTINCT FROM actor_value || '/' || NEW.tenant_uuid::TEXT) + OR NOT EXISTS (SELECT 1 FROM account_selected_owner_intake_sources held + WHERE held.operation_id = NEW.operation_id AND held.source_key = source_key_value + AND held.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Malformed, changed, or incomplete finalized source evidence' + USING ERRCODE = '23514'; + END IF; + seen := array_append(seen, source_key_value); + previous_key := source_key_value; + END LOOP; + IF p <> octet_length(NEW.binding_bytes) + 1 THEN + RAISE EXCEPTION 'Finalized authorization has trailing bytes' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_selected_owner_intake_authorization_complete + AFTER INSERT ON account_selected_owner_intake_authorizations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_authorization_complete_guard(); + +CREATE FUNCTION account_selected_owner_intake_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Finalized sources must accompany the original Account transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_selected_owner_intake_source_validate + BEFORE INSERT ON account_selected_owner_intake_sources FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_source_insert_guard(); + +CREATE TRIGGER account_selected_owner_intake_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_authorizations + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_authorizations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_sources_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_sources_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_terminal_settlement.sql new file mode 100644 index 0000000000..b437b921b8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_terminal_settlement.sql @@ -0,0 +1,500 @@ +-- Exact Automation COMMITTED_EMPTY terminal settlement. Entity participation and every +-- unresolved/ambiguous owner outcome remain pending indefinitely. +CREATE TABLE account_selected_owner_intake_settlements ( + operation_id UUID PRIMARY KEY + REFERENCES account_selected_owner_intake_authorizations(operation_id), + fence_id UUID NOT NULL UNIQUE, + intake_request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL CHECK (owner = 'AUTOMATION_SCRIPTING'), + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + binding_bytes BYTEA NOT NULL CHECK (octet_length(binding_bytes) BETWEEN 1 AND 16777216), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + terminal_read_request_id UUID NOT NULL, + terminal_receipt_bytes BYTEA NOT NULL CHECK (octet_length(terminal_receipt_bytes) BETWEEN 1 AND 58736640), + terminal_receipt_digest VARCHAR(71) NOT NULL CHECK (terminal_receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) BETWEEN 1 AND 92356608), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + settled_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 (terminal_read_request_id <> '00000000-0000-0000-0000-000000000000') +); + +-- [jooq ignore start] +CREATE FUNCTION account_selected_owner_intake_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_owner_intake_authorizations%ROWTYPE; + reservation account_selected_owner_intake_source_read_reservations%ROWTYPE; + p INTEGER := 1; + q INTEGER := 1; + source_position INTEGER := 1; + receipt_position INTEGER := 1; + parsed BYTEA; + binding_scope BYTEA; + content_bytes BYTEA; + selected_bytes BYTEA; + terminal_binding BYTEA; + owner_receipt BYTEA; + world_request_bytes BYTEA; + world_inventory_bytes BYTEA; + source_bytes BYTEA; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + namespace_value TEXT; + request_id_value UUID; + owner_world_request_id UUID; + count_text TEXT; + count_value INTEGER; + index_value INTEGER; + local_key_value BIGINT; + local_key_text TEXT; + first_local_key_text TEXT; + request_digest_text TEXT; + ignored_text TEXT; + marker TEXT; + retained_timestamp TIMESTAMPTZ; +BEGIN + -- Source writers and settlement serialize on Account's retained source rows in canonical + -- sort order, followed by reservation, final authorization, then this settlement identity. + 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; + SELECT * INTO STRICT reservation + FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + SELECT * INTO STRICT original + FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id FOR UPDATE; + PERFORM operation_id FROM account_selected_owner_intake_settlements + WHERE operation_id = NEW.operation_id FOR UPDATE; + + IF FOUND + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) + OR NEW.operation_id IS DISTINCT FROM original.operation_id + OR NEW.fence_id IS DISTINCT FROM original.fence_id + OR NEW.intake_request_id IS DISTINCT FROM original.intake_request_id + OR NEW.owner IS DISTINCT FROM original.owner + OR NEW.target_namespace IS DISTINCT FROM original.target_namespace + OR NEW.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR NEW.version_uuid IS DISTINCT FROM original.version_uuid + OR original.owner IS DISTINCT FROM 'AUTOMATION_SCRIPTING' + OR reservation.owner IS DISTINCT FROM original.owner + OR reservation.operation_id IS DISTINCT FROM original.operation_id + OR reservation.fence_id IS DISTINCT FROM original.fence_id + OR reservation.intake_request_id IS DISTINCT FROM original.intake_request_id + OR reservation.actor_account_uuid IS DISTINCT FROM original.actor_account_uuid + OR reservation.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR reservation.version_uuid IS DISTINCT FROM original.version_uuid + OR NEW.binding_bytes IS DISTINCT FROM original.binding_bytes + OR NEW.binding_digest IS DISTINCT FROM original.binding_digest + OR original.binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement must bind one exact active Automation authorization' + USING ERRCODE = '23514'; + END IF; + + -- Recheck every finalized source child against both the complete immutable binding and the + -- retained preliminary child vector. A digest or parent-row match alone is insufficient. + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-automation-intake-authorization/v1' THEN + RAISE EXCEPTION 'Settlement original binding is not Automation authorization' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO content_bytes, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'sha256:' || encode(sha256(content_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement original content digest differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'spiffe://firemud/ns/' || original.target_namespace || '/sa/automation-scripting-service' THEN + RAISE EXCEPTION 'Settlement original retention reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'AUTOMATION_INTAKE_RETENTION' THEN + RAISE EXCEPTION 'Settlement original retention purpose differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF count_text !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Settlement original source count is malformed' USING ERRCODE = '23514'; + END IF; + count_value := count_text::INTEGER; + IF count_value > 256 THEN + RAISE EXCEPTION 'Settlement original source vector exceeds its bound' + USING ERRCODE = '23514'; + END IF; + + q := 1; + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'game-design-selected-owner-intake-source/v1' THEN + RAISE EXCEPTION 'Settlement original selected content schema differs' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO binding_scope, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF marker IS DISTINCT FROM 'sha256:' || encode(sha256(binding_scope), 'hex') + OR binding_scope IS DISTINCT FROM reservation.scope_bytes + OR reservation.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(binding_scope), 'hex') + OR original.content_bytes IS DISTINCT FROM content_bytes + OR original.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement original selected scope or content differs' + USING ERRCODE = '23514'; + END IF; + -- The finalized binding contains six exact selected family frames after its scope header. + FOREACH ignored_text IN ARRAY ARRAY['COMMAND', 'REALM_POLICY', 'ASSET', 'GAMEPLAY_RULE', 'BRANDING', 'TEMPLATE_CONFIG'] LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF marker IS DISTINCT FROM ignored_text + OR namespace_value IS DISTINCT FROM 'sha256:' || encode(sha256(parsed), 'hex') THEN + RAISE EXCEPTION 'Settlement selected family snapshot differs' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF q <> octet_length(content_bytes) + 1 THEN + RAISE EXCEPTION 'Settlement selected content has trailing bytes' USING ERRCODE = '23514'; + END IF; + + -- Bind the full preliminary scope tuple and selected-target JSON to all retained columns. + source_position := 1; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-automation-intake-source-read/v1' THEN + RAISE EXCEPTION 'Settlement original preliminary scope schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM 'AUTOMATION_SCRIPTING' THEN + RAISE EXCEPTION 'Settlement original scope owner differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + FOR index_value IN 1..4 LOOP + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF index_value = 1 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.operation_id::TEXT + OR index_value = 2 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.fence_id::TEXT + OR index_value = 3 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.intake_request_id::TEXT + OR index_value = 4 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM original.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Settlement operation scope tuple differs' USING ERRCODE = '23514'; + END IF; + END LOOP; + SELECT frame_value, next_position INTO selected_bytes, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF namespace_value IS DISTINCT FROM NEW.target_namespace + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT THEN + RAISE EXCEPTION 'Settlement original selected scope differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM 'spiffe://firemud/ns/' || NEW.target_namespace || '/sa/account-service' THEN + RAISE EXCEPTION 'Settlement source scope reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM 'AUTOMATION_INTAKE_SOURCE' + OR source_position <> octet_length(binding_scope) + 1 THEN + RAISE EXCEPTION 'Settlement source scope purpose or trailing bytes differ' + USING ERRCODE = '23514'; + END IF; + + FOR index_value IN 1..count_value LOOP + SELECT frame_value, next_position INTO source_bytes, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + 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') IS DISTINCT FROM 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Settlement source evidence schema differs' 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); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + current_sort_key := account_publication_authorization_source_sort_key(source_key_value); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Settlement source vector is duplicated or unordered' + USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + IF NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_sources source + WHERE source.operation_id = NEW.operation_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) + OR NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_sources source + WHERE source.operation_id = NEW.operation_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Settlement source child differs from complete original vector' + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF p <> octet_length(original.binding_bytes) + 1 + OR count_value IS DISTINCT FROM (SELECT count(*) FROM account_selected_owner_intake_sources + WHERE operation_id = NEW.operation_id) + OR count_value IS DISTINCT FROM (SELECT count(*) FROM account_selected_owner_intake_source_read_sources + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Settlement source child vector is incomplete' USING ERRCODE = '23514'; + END IF; + + IF NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') + OR NEW.terminal_receipt_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_receipt_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement or Automation receipt digest differs' USING ERRCODE = '23514'; + END IF; + p := 1; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-selected-owner-intake-settlement/v1' THEN + RAISE EXCEPTION 'Settlement receipt schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Settlement receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF parsed IS DISTINCT FROM NEW.binding_bytes THEN + RAISE EXCEPTION 'Settlement receipt changed original binding bytes' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Settlement receipt changed original binding digest' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Settlement terminal request schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + BEGIN request_id_value := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Settlement terminal read correlation is malformed' USING ERRCODE = '23514'; END; + IF request_id_value = '00000000-0000-0000-0000-000000000000'::UUID + OR request_id_value::TEXT IS DISTINCT FROM ignored_text + OR request_id_value = NEW.operation_id OR request_id_value = NEW.fence_id + OR request_id_value = NEW.intake_request_id + OR request_id_value IS DISTINCT FROM NEW.terminal_read_request_id THEN + RAISE EXCEPTION 'Settlement terminal read correlation differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF namespace_value IS DISTINCT FROM NEW.target_namespace + OR marker IS DISTINCT FROM 'spiffe://firemud/ns/' || NEW.target_namespace || '/sa/account-service' THEN + RAISE EXCEPTION 'Settlement terminal reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM 'AUTOMATION_INTAKE_TERMINAL_READ' THEN + RAISE EXCEPTION 'Settlement terminal read purpose differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO terminal_binding, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF terminal_binding IS DISTINCT FROM NEW.binding_bytes OR marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Settlement terminal request changed original Account binding' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO owner_receipt, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF owner_receipt IS DISTINCT FROM NEW.terminal_receipt_bytes + OR marker IS DISTINCT FROM NEW.terminal_receipt_digest + OR p <> octet_length(NEW.receipt_bytes) + 1 THEN + RAISE EXCEPTION 'Settlement receipt differs from exact Automation terminal bytes' + USING ERRCODE = '23514'; + END IF; + + -- The owner receipt has a closed canonical frame and embeds the complete same binding. + p := 1; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM 'automation-empty-selected-source-intake-receipt/v1' THEN + RAISE EXCEPTION 'Automation terminal receipt schema is not COMMITTED_EMPTY' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Automation terminal receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + FOR index_value IN 1..8 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF index_value = 1 AND marker IS DISTINCT FROM NEW.operation_id::TEXT + OR index_value = 2 AND marker IS DISTINCT FROM NEW.fence_id::TEXT + OR index_value = 3 AND marker IS DISTINCT FROM NEW.intake_request_id::TEXT + OR index_value = 4 AND marker IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR index_value = 5 AND marker IS DISTINCT FROM NEW.version_uuid::TEXT + OR index_value = 6 AND marker IS DISTINCT FROM convert_from(selected_bytes, 'UTF8')::JSONB->>'commitId' THEN + RAISE EXCEPTION 'Automation terminal identity differs from original order' + USING ERRCODE = '23514'; + END IF; + IF index_value = 7 THEN + BEGIN PERFORM marker::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation source revision identity is malformed' + USING ERRCODE = '23514'; END; + IF marker::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR marker::UUID::TEXT IS DISTINCT FROM marker THEN + RAISE EXCEPTION 'Automation source revision identity is noncanonical' + USING ERRCODE = '23514'; + END IF; + ELSIF index_value = 8 AND marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Automation source revision order is noncanonical' + USING ERRCODE = '23514'; + END IF; + END LOOP; + -- Skip source declaration and local key/request metadata, then verify the full bound receipt + -- digest and authorization bytes before consuming the independent World evidence frames. + FOR index_value IN 1..3 LOOP + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF index_value < 3 THEN + local_key_text := convert_from(parsed, 'UTF8'); + BEGIN local_key_value := local_key_text::BIGINT; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation local key is malformed' USING ERRCODE = '23514'; END; + IF local_key_value <= 0 OR local_key_value::TEXT IS DISTINCT FROM local_key_text + OR (index_value = 2 AND local_key_text IS NOT DISTINCT FROM first_local_key_text) THEN + RAISE EXCEPTION 'Automation local key is noncanonical or repeated' + USING ERRCODE = '23514'; + END IF; + IF index_value = 1 THEN first_local_key_text := local_key_text; END IF; + ELSE + request_digest_text := convert_from(parsed, 'UTF8'); + IF request_digest_text !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation caller request digest is malformed' + USING ERRCODE = '23514'; + END IF; + END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM NEW.binding_digest OR parsed IS DISTINCT FROM NEW.binding_bytes THEN + RAISE EXCEPTION 'Automation terminal receipt changed full original binding' + USING ERRCODE = '23514'; + END IF; + IF namespace_value IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Automation terminal namespace differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN owner_world_request_id := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation World read correlation is malformed' USING ERRCODE = '23514'; END; + IF owner_world_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR owner_world_request_id::TEXT IS DISTINCT FROM ignored_text THEN + RAISE EXCEPTION 'Automation World read correlation is noncanonical' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation World request digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_request_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_request_bytes) NOT BETWEEN 1 AND 33554432 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_request_bytes), 'hex') THEN + RAISE EXCEPTION 'Automation World request bytes or digest differ' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation World inventory digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_inventory_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_inventory_bytes) NOT BETWEEN 1 AND 8388608 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_inventory_bytes), 'hex') THEN + RAISE EXCEPTION 'Automation World inventory bytes or digest differ' USING ERRCODE = '23514'; + END IF; + -- COMMITTED_EMPTY is represented only by a complete all-zero three-family census. + FOR index_value IN 1..12 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF count_text !~ '^(0|[1-9][0-9]*)$' OR count_text::BIGINT <> 0 THEN + RAISE EXCEPTION 'Automation COMMITTED_EMPTY receipt contains a nonempty census' + USING ERRCODE = '23514'; + END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF ignored_text !~ '^(?:[0-9]{4}|-[0-9]{4}|-[1-9][0-9]{4,8}|[+][1-9][0-9]{4,8})-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:[.](?:[0-9]{3}|[0-9]{6}|[0-9]{9}))?)?Z$' + OR ignored_text ~ '^-0000-' + OR ignored_text ~ 'T(?:[01][0-9]|2[0-3]):[0-5][0-9]:00Z$' + OR ignored_text ~ '[.]000Z$' + OR ignored_text ~ '[.][0-9]{3}000Z$' + OR ignored_text ~ '[.][0-9]{6}000Z$' + OR p <> octet_length(owner_receipt) + 1 THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp or trailing bytes are invalid' + USING ERRCODE = '23514'; + END IF; + BEGIN retained_timestamp := ignored_text::TIMESTAMPTZ; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp is malformed' + USING ERRCODE = '23514'; END; + IF retained_timestamp IS NULL THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp is absent' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_selected_owner_intake_settlement_validate + BEFORE INSERT ON account_selected_owner_intake_settlements + FOR EACH ROW EXECUTE FUNCTION account_selected_owner_intake_settlement_guard(); +CREATE TRIGGER account_selected_owner_intake_settlement_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_settlements + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_settlement_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +CREATE OR REPLACE FUNCTION account_selected_owner_intake_source_read_is_pending(operation_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_aborts aborted + WHERE aborted.operation_id = operation_value) + AND NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_settlements settled + WHERE settled.operation_id = operation_value); +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1009__entity_selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V1009__entity_selected_owner_intake_terminal_settlement.sql new file mode 100644 index 0000000000..ae4f64334f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1009__entity_selected_owner_intake_terminal_settlement.sql @@ -0,0 +1,708 @@ +-- Add Entity's authenticated closed COMMITTED_EMPTY receipt to the existing immutable family. +-- V1008 Automation rows and receipt bytes are retained exactly; no pending predicate changes. +-- [jooq ignore start] +DO $migration$ +DECLARE + check_row RECORD; + expected_limit TEXT; + changed_count INTEGER := 0; +BEGIN + FOR check_row IN + SELECT constraint_row.conname, attribute_row.attname, + pg_get_constraintdef(constraint_row.oid) AS definition + FROM pg_constraint constraint_row + JOIN pg_attribute attribute_row + ON attribute_row.attrelid = constraint_row.conrelid + AND constraint_row.conkey = ARRAY[attribute_row.attnum]::SMALLINT[] + WHERE constraint_row.conrelid = 'account_selected_owner_intake_settlements'::REGCLASS + AND constraint_row.contype = 'c' + AND attribute_row.attname IN ('owner', 'terminal_receipt_bytes', 'receipt_bytes') + LOOP + expected_limit := CASE check_row.attname WHEN 'owner' THEN 'AUTOMATION_SCRIPTING' + WHEN 'terminal_receipt_bytes' THEN '58736640' ELSE '92356608' END; + IF position(expected_limit IN check_row.definition) = 0 THEN + RAISE EXCEPTION 'Unexpected retained V1008 settlement constraint: %', check_row.conname; + END IF; + EXECUTE format('ALTER TABLE account_selected_owner_intake_settlements DROP CONSTRAINT %I', + check_row.conname); + changed_count := changed_count + 1; + END LOOP; + IF changed_count <> 3 THEN + RAISE EXCEPTION 'Expected all three retained V1008 settlement constraints'; + END IF; +END; +$migration$; +-- [jooq ignore stop] +ALTER TABLE account_selected_owner_intake_settlements + ADD CONSTRAINT selected_owner_settlement_owner_check + CHECK (owner IN ('AUTOMATION_SCRIPTING', 'ENTITY_MANAGEMENT')), + ADD CONSTRAINT selected_owner_settlement_terminal_size_check + CHECK (octet_length(terminal_receipt_bytes) >= 1 AND + ((owner = 'AUTOMATION_SCRIPTING' AND octet_length(terminal_receipt_bytes) <= 58736640) + OR (owner = 'ENTITY_MANAGEMENT' AND octet_length(terminal_receipt_bytes) <= 83886080))), + ADD CONSTRAINT selected_owner_settlement_receipt_size_check + CHECK (octet_length(receipt_bytes) >= 1 AND + ((owner = 'AUTOMATION_SCRIPTING' AND octet_length(receipt_bytes) <= 92356608) + OR (owner = 'ENTITY_MANAGEMENT' AND octet_length(receipt_bytes) <= 117506048))); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_selected_owner_intake_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_owner_intake_authorizations%ROWTYPE; + reservation account_selected_owner_intake_source_read_reservations%ROWTYPE; + p INTEGER := 1; + q INTEGER := 1; + source_position INTEGER := 1; + receipt_position INTEGER := 1; + parsed BYTEA; + binding_scope BYTEA; + content_bytes BYTEA; + selected_bytes BYTEA; + terminal_binding BYTEA; + owner_receipt BYTEA; + world_request_bytes BYTEA; + world_inventory_bytes BYTEA; + source_bytes BYTEA; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + namespace_value TEXT; + request_id_value UUID; + owner_world_request_id UUID; + count_text TEXT; + count_value INTEGER; + index_value INTEGER; + local_key_value BIGINT; + local_key_text TEXT; + first_local_key_text TEXT; + request_digest_text TEXT; + ignored_text TEXT; + marker TEXT; + retained_timestamp TIMESTAMPTZ; + template_snapshot JSONB; + entity_declaration JSONB; + revision_bytes BYTEA; + schema_bytes BYTEA := ''::BYTEA; + schema_digest_text TEXT; + expected_family TEXT; + entity_families TEXT[] := ARRAY['ACTOR_BODY_LAYOUT_ASSIGNMENTS', 'ARCHETYPE_ASSIGNMENTS', 'ARCHETYPE_CONSTRAINTS', 'ARCHETYPE_ROOTS', 'BALANCE_CURVE_ATTACHMENTS', 'BALANCE_CURVE_ROOTS', 'BODY_LAYOUT_MEMBERSHIPS', 'BODY_LAYOUT_ROOTS', 'CRAFTING_INGREDIENT_BINDINGS', 'CRAFTING_RECIPE_RESULT_BINDINGS', 'CRAFTING_RECIPE_ROOTS', 'EQUIPMENT_ATTACHMENT_RULES', 'EQUIPMENT_CAPABILITIES', 'EQUIPMENT_COMPATIBILITY_RULES', 'EQUIPMENT_OCCUPANCY_RULES', 'EQUIPMENT_SLOT_GROUPS', 'EQUIPMENT_SLOT_ROOTS', 'INBOUND_LOOT_BINDINGS', 'ITEM_TEMPLATE_ROOTS', 'LOOT_ITEM_MAPPINGS', 'LOOT_TABLE_ROOTS', 'NPC_TEMPLATE_ROOTS', 'OTHER_ACTOR_TEMPLATE_ROOTS']; +BEGIN + -- Source writers and settlement serialize on Account's retained source rows in canonical + -- sort order, followed by reservation, final authorization, then this settlement identity. + 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; + SELECT * INTO STRICT reservation + FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + SELECT * INTO STRICT original + FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id FOR UPDATE; + PERFORM operation_id FROM account_selected_owner_intake_settlements + WHERE operation_id = NEW.operation_id FOR UPDATE; + + IF FOUND + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) + OR NEW.operation_id IS DISTINCT FROM original.operation_id + OR NEW.fence_id IS DISTINCT FROM original.fence_id + OR NEW.intake_request_id IS DISTINCT FROM original.intake_request_id + OR NEW.owner IS DISTINCT FROM original.owner + OR NEW.target_namespace IS DISTINCT FROM original.target_namespace + OR NEW.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR NEW.version_uuid IS DISTINCT FROM original.version_uuid + OR original.owner NOT IN ('AUTOMATION_SCRIPTING', 'ENTITY_MANAGEMENT') + OR reservation.owner IS DISTINCT FROM original.owner + OR reservation.operation_id IS DISTINCT FROM original.operation_id + OR reservation.fence_id IS DISTINCT FROM original.fence_id + OR reservation.intake_request_id IS DISTINCT FROM original.intake_request_id + OR reservation.actor_account_uuid IS DISTINCT FROM original.actor_account_uuid + OR reservation.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR reservation.version_uuid IS DISTINCT FROM original.version_uuid + OR NEW.binding_bytes IS DISTINCT FROM original.binding_bytes + OR NEW.binding_digest IS DISTINCT FROM original.binding_digest + OR original.binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement must bind one exact active Automation authorization' + USING ERRCODE = '23514'; + END IF; + + -- Recheck every finalized source child against both the complete immutable binding and the + -- retained preliminary child vector. A digest or parent-row match alone is insufficient. + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'account-automation-intake-authorization/v1' ELSE 'account-entity-intake-authorization/v1' END) THEN + RAISE EXCEPTION 'Settlement original binding is not Automation authorization' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO content_bytes, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'sha256:' || encode(sha256(content_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement original content digest differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'spiffe://firemud/ns/' || original.target_namespace || (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN '/sa/automation-scripting-service' ELSE '/sa/entity-management-service' END) THEN + RAISE EXCEPTION 'Settlement original retention reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_RETENTION' ELSE 'ENTITY_INTAKE_RETENTION' END) THEN + RAISE EXCEPTION 'Settlement original retention purpose differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF count_text !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Settlement original source count is malformed' USING ERRCODE = '23514'; + END IF; + count_value := count_text::INTEGER; + IF count_value > 256 THEN + RAISE EXCEPTION 'Settlement original source vector exceeds its bound' + USING ERRCODE = '23514'; + END IF; + + q := 1; + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'game-design-selected-owner-intake-source/v1' THEN + RAISE EXCEPTION 'Settlement original selected content schema differs' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO binding_scope, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF marker IS DISTINCT FROM 'sha256:' || encode(sha256(binding_scope), 'hex') + OR binding_scope IS DISTINCT FROM reservation.scope_bytes + OR reservation.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(binding_scope), 'hex') + OR original.content_bytes IS DISTINCT FROM content_bytes + OR original.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement original selected scope or content differs' + USING ERRCODE = '23514'; + END IF; + -- The finalized binding contains six exact selected family frames after its scope header. + FOREACH ignored_text IN ARRAY ARRAY['COMMAND', 'REALM_POLICY', 'ASSET', 'GAMEPLAY_RULE', 'BRANDING', 'TEMPLATE_CONFIG'] LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF ignored_text = 'TEMPLATE_CONFIG' AND original.owner = 'ENTITY_MANAGEMENT' THEN + template_snapshot := convert_from(parsed, 'UTF8')::JSONB; + END IF; + IF marker IS DISTINCT FROM ignored_text + OR namespace_value IS DISTINCT FROM 'sha256:' || encode(sha256(parsed), 'hex') THEN + RAISE EXCEPTION 'Settlement selected family snapshot differs' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF q <> octet_length(content_bytes) + 1 THEN + RAISE EXCEPTION 'Settlement selected content has trailing bytes' USING ERRCODE = '23514'; + END IF; + + -- Bind the full preliminary scope tuple and selected-target JSON to all retained columns. + source_position := 1; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'account-automation-intake-source-read/v1' ELSE 'account-entity-intake-source-read/v1' END) THEN + RAISE EXCEPTION 'Settlement original preliminary scope schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM original.owner THEN + RAISE EXCEPTION 'Settlement original scope owner differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + FOR index_value IN 1..4 LOOP + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF index_value = 1 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.operation_id::TEXT + OR index_value = 2 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.fence_id::TEXT + OR index_value = 3 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.intake_request_id::TEXT + OR index_value = 4 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM original.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Settlement operation scope tuple differs' USING ERRCODE = '23514'; + END IF; + END LOOP; + SELECT frame_value, next_position INTO selected_bytes, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF namespace_value IS DISTINCT FROM NEW.target_namespace + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT THEN + RAISE EXCEPTION 'Settlement original selected scope differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM 'spiffe://firemud/ns/' || NEW.target_namespace || '/sa/account-service' THEN + RAISE EXCEPTION 'Settlement source scope reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_SOURCE' ELSE 'ENTITY_INTAKE_SOURCE' END) + OR source_position <> octet_length(binding_scope) + 1 THEN + RAISE EXCEPTION 'Settlement source scope purpose or trailing bytes differ' + USING ERRCODE = '23514'; + END IF; + + FOR index_value IN 1..count_value LOOP + SELECT frame_value, next_position INTO source_bytes, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + 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') IS DISTINCT FROM 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Settlement source evidence schema differs' 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); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + current_sort_key := account_publication_authorization_source_sort_key(source_key_value); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Settlement source vector is duplicated or unordered' + USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + IF NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_sources source + WHERE source.operation_id = NEW.operation_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) + OR NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_sources source + WHERE source.operation_id = NEW.operation_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Settlement source child differs from complete original vector' + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF p <> octet_length(original.binding_bytes) + 1 + OR count_value IS DISTINCT FROM (SELECT count(*) FROM account_selected_owner_intake_sources + WHERE operation_id = NEW.operation_id) + OR count_value IS DISTINCT FROM (SELECT count(*) FROM account_selected_owner_intake_source_read_sources + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Settlement source child vector is incomplete' USING ERRCODE = '23514'; + END IF; + + IF NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') + OR NEW.terminal_receipt_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_receipt_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement or Automation receipt digest differs' USING ERRCODE = '23514'; + END IF; + p := 1; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-selected-owner-intake-settlement/v1' THEN + RAISE EXCEPTION 'Settlement receipt schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Settlement receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF parsed IS DISTINCT FROM NEW.binding_bytes THEN + RAISE EXCEPTION 'Settlement receipt changed original binding bytes' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Settlement receipt changed original binding digest' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Settlement terminal request schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + BEGIN request_id_value := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Settlement terminal read correlation is malformed' USING ERRCODE = '23514'; END; + IF request_id_value = '00000000-0000-0000-0000-000000000000'::UUID + OR request_id_value::TEXT IS DISTINCT FROM ignored_text + OR request_id_value = NEW.operation_id OR request_id_value = NEW.fence_id + OR request_id_value = NEW.intake_request_id + OR request_id_value IS DISTINCT FROM NEW.terminal_read_request_id THEN + RAISE EXCEPTION 'Settlement terminal read correlation differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF namespace_value IS DISTINCT FROM NEW.target_namespace + OR marker IS DISTINCT FROM 'spiffe://firemud/ns/' || NEW.target_namespace || '/sa/account-service' THEN + RAISE EXCEPTION 'Settlement terminal reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_TERMINAL_READ' ELSE 'ENTITY_INTAKE_TERMINAL_READ' END) THEN + RAISE EXCEPTION 'Settlement terminal read purpose differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO terminal_binding, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF terminal_binding IS DISTINCT FROM NEW.binding_bytes OR marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Settlement terminal request changed original Account binding' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO owner_receipt, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF owner_receipt IS DISTINCT FROM NEW.terminal_receipt_bytes + OR marker IS DISTINCT FROM NEW.terminal_receipt_digest + OR p <> octet_length(NEW.receipt_bytes) + 1 THEN + RAISE EXCEPTION 'Settlement receipt differs from exact Automation terminal bytes' + USING ERRCODE = '23514'; + END IF; + + IF original.owner = 'AUTOMATION_SCRIPTING' THEN + -- The owner receipt has a closed canonical frame and embeds the complete same binding. + p := 1; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM 'automation-empty-selected-source-intake-receipt/v1' THEN + RAISE EXCEPTION 'Automation terminal receipt schema is not COMMITTED_EMPTY' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Automation terminal receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + FOR index_value IN 1..8 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF index_value = 1 AND marker IS DISTINCT FROM NEW.operation_id::TEXT + OR index_value = 2 AND marker IS DISTINCT FROM NEW.fence_id::TEXT + OR index_value = 3 AND marker IS DISTINCT FROM NEW.intake_request_id::TEXT + OR index_value = 4 AND marker IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR index_value = 5 AND marker IS DISTINCT FROM NEW.version_uuid::TEXT + OR index_value = 6 AND marker IS DISTINCT FROM convert_from(selected_bytes, 'UTF8')::JSONB->>'commitId' THEN + RAISE EXCEPTION 'Automation terminal identity differs from original order' + USING ERRCODE = '23514'; + END IF; + IF index_value = 7 THEN + BEGIN PERFORM marker::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation source revision identity is malformed' + USING ERRCODE = '23514'; END; + IF marker::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR marker::UUID::TEXT IS DISTINCT FROM marker THEN + RAISE EXCEPTION 'Automation source revision identity is noncanonical' + USING ERRCODE = '23514'; + END IF; + ELSIF index_value = 8 AND marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Automation source revision order is noncanonical' + USING ERRCODE = '23514'; + END IF; + END LOOP; + -- Skip source declaration and local key/request metadata, then verify the full bound receipt + -- digest and authorization bytes before consuming the independent World evidence frames. + FOR index_value IN 1..3 LOOP + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF index_value < 3 THEN + local_key_text := convert_from(parsed, 'UTF8'); + BEGIN local_key_value := local_key_text::BIGINT; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation local key is malformed' USING ERRCODE = '23514'; END; + IF local_key_value <= 0 OR local_key_value::TEXT IS DISTINCT FROM local_key_text + OR (index_value = 2 AND local_key_text IS NOT DISTINCT FROM first_local_key_text) THEN + RAISE EXCEPTION 'Automation local key is noncanonical or repeated' + USING ERRCODE = '23514'; + END IF; + IF index_value = 1 THEN first_local_key_text := local_key_text; END IF; + ELSE + request_digest_text := convert_from(parsed, 'UTF8'); + IF request_digest_text !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation caller request digest is malformed' + USING ERRCODE = '23514'; + END IF; + END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM NEW.binding_digest OR parsed IS DISTINCT FROM NEW.binding_bytes THEN + RAISE EXCEPTION 'Automation terminal receipt changed full original binding' + USING ERRCODE = '23514'; + END IF; + IF namespace_value IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Automation terminal namespace differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN owner_world_request_id := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation World read correlation is malformed' USING ERRCODE = '23514'; END; + IF owner_world_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR owner_world_request_id::TEXT IS DISTINCT FROM ignored_text THEN + RAISE EXCEPTION 'Automation World read correlation is noncanonical' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation World request digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_request_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_request_bytes) NOT BETWEEN 1 AND 33554432 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_request_bytes), 'hex') THEN + RAISE EXCEPTION 'Automation World request bytes or digest differ' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation World inventory digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_inventory_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_inventory_bytes) NOT BETWEEN 1 AND 8388608 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_inventory_bytes), 'hex') THEN + RAISE EXCEPTION 'Automation World inventory bytes or digest differ' USING ERRCODE = '23514'; + END IF; + -- COMMITTED_EMPTY is represented only by a complete all-zero three-family census. + FOR index_value IN 1..12 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF count_text !~ '^(0|[1-9][0-9]*)$' OR count_text::BIGINT <> 0 THEN + RAISE EXCEPTION 'Automation COMMITTED_EMPTY receipt contains a nonempty census' + USING ERRCODE = '23514'; + END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF ignored_text !~ '^(?:[0-9]{4}|-[0-9]{4}|-[1-9][0-9]{4,8}|[+][1-9][0-9]{4,8})-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:[.](?:[0-9]{3}|[0-9]{6}|[0-9]{9}))?)?Z$' + OR ignored_text ~ '^-0000-' + OR ignored_text ~ 'T(?:[01][0-9]|2[0-3]):[0-5][0-9]:00Z$' + OR ignored_text ~ '[.]000Z$' + OR ignored_text ~ '[.][0-9]{3}000Z$' + OR ignored_text ~ '[.][0-9]{6}000Z$' + OR p <> octet_length(owner_receipt) + 1 THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp or trailing bytes are invalid' + USING ERRCODE = '23514'; + END IF; + BEGIN retained_timestamp := ignored_text::TIMESTAMPTZ; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp is malformed' + USING ERRCODE = '23514'; END; + IF retained_timestamp IS NULL THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp is absent' + USING ERRCODE = '23514'; + END IF; + + ELSE + -- Entity terminal bytes are a distinct closed owner receipt. Provider-row existence is + -- established by the authenticated Entity terminal reader, never inferred by Account. + p := 1; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM 'entity-selected-empty-source-catalogue/v1' THEN + RAISE EXCEPTION 'Entity terminal receipt schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Entity terminal receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO schema_digest_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + FOREACH ignored_text IN ARRAY (ARRAY[ + 'entity-selected-empty-source-catalogue-schema/v1', + 'entity-selected-empty-source-catalogue/v1', + '1', + 'encoding=ADR-0047-byte-length-frames;strings=UTF-8;counts=canonical-decimal', + 'targetNamespace:utf8', + 'authorizationBindingBytes:canonical-original-account-binding', + 'authorizationBindingDigest:sha256', + 'selectedSourceBytes:canonical-game-design-source-content', + 'selectedSourceDigest:sha256', + 'selectedSourceRevisionBindingBytes:canonical-game-design-source-operation-binding', + 'selectedSourceRevisionBindingDigest:sha256', + 'worldReadRequestBytes:canonical-recipient-qualified-world-request', + 'worldReadRequestDigest:sha256', + 'worldClosureBytes:canonical-public-world-inventory', + 'worldClosureDigest:sha256', + 'localTenantKey:positive-canonical-decimal', + 'localVersionKey:positive-canonical-decimal', + 'familyStates:count-then-23-lexical-family-records-with-provider-kind', + 'genesisId:canonical-uuid', + 'requestDigest:sha256', + 'worldReadRequestId:canonical-uuid', + 'retainedAt:canonical-utc-offset-date-time', + 'familyRecordFields=count-then-family,state,evidenceKind,rowCount,unqualifiedRowCount,retainedRowCount,selectedScopeRowCount,referenceCount', + 'family:utf8', + 'state=EMPTY', + 'evidenceKind=V1_SOURCE_CENSUS|EMPTY_ONLY_OWNER_PROVIDER', + 'rowCount:canonical-nonnegative-decimal', + 'unqualifiedRowCount:canonical-nonnegative-decimal', + 'retainedRowCount:canonical-nonnegative-decimal', + 'selectedScopeRowCount:canonical-nonnegative-decimal', + 'referenceCount:canonical-nonnegative-decimal', + '23' + ] || entity_families) LOOP + parsed := convert_to(ignored_text, 'UTF8'); + schema_bytes := schema_bytes || int4send(octet_length(parsed)) || parsed; + END LOOP; + IF schema_digest_text IS DISTINCT FROM 'sha256:' || encode(sha256(schema_bytes), 'hex') THEN + RAISE EXCEPTION 'Entity terminal schema digest differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Entity terminal namespace differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF parsed IS DISTINCT FROM NEW.binding_bytes OR marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Entity terminal changed original authorization' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF parsed IS DISTINCT FROM content_bytes + OR marker IS DISTINCT FROM original.content_digest THEN + RAISE EXCEPTION 'Entity terminal changed original selected source' USING ERRCODE = '23514'; + END IF; + IF template_snapshot->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v2' + OR jsonb_typeof(template_snapshot->'ownerSourceInventoryDeclarations') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_array_elements(template_snapshot->'ownerSourceInventoryDeclarations') declaration + WHERE declaration->>'owner' = 'ENTITY_MANAGEMENT') <> 1 THEN + RAISE EXCEPTION 'Entity original typed source declaration is unavailable' USING ERRCODE = '23514'; + END IF; + SELECT declaration INTO STRICT entity_declaration + FROM jsonb_array_elements(template_snapshot->'ownerSourceInventoryDeclarations') declaration + WHERE declaration->>'owner' = 'ENTITY_MANAGEMENT'; + SELECT frame_value, next_position INTO revision_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(revision_bytes) NOT BETWEEN 1 AND 4194304 + OR revision_bytes IS DISTINCT FROM convert_to(entity_declaration->>'sourceBindingJson', 'UTF8') + OR marker IS DISTINCT FROM entity_declaration->>'sourceBindingDigest' + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(revision_bytes), 'hex') THEN + RAISE EXCEPTION 'Entity terminal changed original source revision binding' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_request_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_request_bytes) NOT BETWEEN 1 AND 33554432 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_request_bytes), 'hex') THEN + RAISE EXCEPTION 'Entity World request bytes or digest differ' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_inventory_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_inventory_bytes) NOT BETWEEN 1 AND 8388608 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_inventory_bytes), 'hex') THEN + RAISE EXCEPTION 'Entity World closure bytes or digest differ' USING ERRCODE = '23514'; + END IF; + FOR index_value IN 1..2 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO local_key_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN local_key_value := local_key_text::BIGINT; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Entity local key is malformed' USING ERRCODE = '23514'; END; + IF local_key_value <= 0 OR local_key_value::TEXT IS DISTINCT FROM local_key_text + OR (index_value = 2 AND local_key_text IS NOT DISTINCT FROM first_local_key_text) THEN + RAISE EXCEPTION 'Entity local key is noncanonical or repeated' USING ERRCODE = '23514'; + END IF; + IF index_value = 1 THEN first_local_key_text := local_key_text; END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '23' THEN + RAISE EXCEPTION 'Entity terminal requires all 23 families' USING ERRCODE = '23514'; + END IF; + FOREACH expected_family IN ARRAY entity_families LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM expected_family THEN + RAISE EXCEPTION 'Entity terminal family order differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM 'EMPTY' THEN + RAISE EXCEPTION 'Entity terminal family is not EMPTY' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM (CASE WHEN expected_family IN ( + 'ITEM_TEMPLATE_ROOTS', 'NPC_TEMPLATE_ROOTS', 'CRAFTING_RECIPE_ROOTS', + 'CRAFTING_RECIPE_RESULT_BINDINGS', 'CRAFTING_INGREDIENT_BINDINGS', + 'EQUIPMENT_SLOT_ROOTS', 'EQUIPMENT_SLOT_GROUPS', 'BODY_LAYOUT_ROOTS', + 'BODY_LAYOUT_MEMBERSHIPS') THEN 'V1_SOURCE_CENSUS' ELSE 'EMPTY_ONLY_OWNER_PROVIDER' END) THEN + RAISE EXCEPTION 'Entity terminal family evidence kind differs' USING ERRCODE = '23514'; + END IF; + FOR index_value IN 1..5 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '0' THEN + RAISE EXCEPTION 'Entity EMPTY family contains nonzero or noncanonical counts' + USING ERRCODE = '23514'; + END IF; + END LOOP; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN request_id_value := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Entity genesis identity is malformed' USING ERRCODE = '23514'; END; + IF request_id_value = '00000000-0000-0000-0000-000000000000'::UUID + OR request_id_value::TEXT IS DISTINCT FROM ignored_text THEN + RAISE EXCEPTION 'Entity genesis identity is noncanonical' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Entity original request digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN request_id_value := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Entity World read identity is malformed' USING ERRCODE = '23514'; END; + IF request_id_value = '00000000-0000-0000-0000-000000000000'::UUID + OR request_id_value::TEXT IS DISTINCT FROM ignored_text THEN + RAISE EXCEPTION 'Entity World read identity is noncanonical' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF ignored_text !~ '^(?:[0-9]{4}|-[0-9]{4}|-[1-9][0-9]{4,8}|[+][1-9][0-9]{4,8})-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:[.](?:[0-9]{3}|[0-9]{6}|[0-9]{9}))?)?Z$' + OR ignored_text ~ '^-0000-' + OR ignored_text ~ 'T(?:[01][0-9]|2[0-3]):[0-5][0-9]:00Z$' + OR ignored_text ~ '[.]000Z$' + OR ignored_text ~ '[.][0-9]{3}000Z$' + OR ignored_text ~ '[.][0-9]{6}000Z$' + OR p <> octet_length(owner_receipt) + 1 THEN + RAISE EXCEPTION 'Entity terminal timestamp or trailing bytes are invalid' USING ERRCODE = '23514'; + END IF; + BEGIN retained_timestamp := ignored_text::TIMESTAMPTZ; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Entity terminal timestamp is malformed' USING ERRCODE = '23514'; END; + IF retained_timestamp IS NULL THEN + RAISE EXCEPTION 'Entity terminal timestamp is absent' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java new file mode 100644 index 0000000000..3f612b8225 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,2207 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedOwnerIntakeSourceReservationRepository.State; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +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.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt.FamilyCensus; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt.FamilyState; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account creator/currentness, PostgreSQL finalization, immutable source participation and + * pending source guards. Six-family content and the Game Design caller are stipulated test inputs; + * the settlement case supplies explicitly synthetic upstream Automation terminal evidence (with no + * authentication proof) and proves real Account storage only, not producer transport or peer + * authentication, activation, or runtime behavior. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("intake-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", + "intake-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var expectedSources = + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment()).sources()); + + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var finalized = new ArrayList(); + var scopes = new ArrayList(); + + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + UUID requestId = UUID.randomUUID(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), requestId, owner, selected, issued.environment())); + var content = content(scope, "stipulated-original"); + var authorization = + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + + assertThat(authorization.owner()).isEqualTo(owner); + assertThat(authorization.content().canonicalBytes()).isEqualTo(content.canonicalBytes()); + assertThat(authorization.sources()).hasSize(expectedSources.size()); + for (int index = 0; index < expectedSources.size(); index++) { + assertThat(authorization.sources().get(index).key()) + .isEqualTo(expectedSources.get(index).key()); + assertThat(authorization.sources().get(index).canonicalBytes()) + .isEqualTo(expectedSources.get(index).canonicalBytes()); + } + assertThat(f.tx(() -> repository.recoverSourceRead(scope)).state()) + .isEqualTo(State.FINALIZED); + var readback = f.tx(() -> repository.findFinalAuthorization(scope)).orElseThrow(); + assertThat(readback.canonicalBytes()).isEqualTo(authorization.canonicalBytes()); + assertThat(readback.digest()).isEqualTo(authorization.digest()); + var exactRetry = + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> { + throw new AssertionError( + "Exact finalization retry must not re-admit"); + }))); + assertThat(exactRetry.canonicalBytes()).isEqualTo(authorization.canonicalBytes()); + f.tx( + () -> { + repository.readFinalAuthorization(authorization); + return null; + }); + assertThatThrownBy(() -> f.tx(() -> repository.sourceReadCurrentness(scope))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("preliminary source read"); + assertThatThrownBy(() -> f.tx(() -> repository.abortSourceRead(scope))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot be preliminarily aborted"); + + var changedContent = content(scope, "stipulated-changed"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, changedContent, current, () -> {})))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts with original selected content"); + + scopes.add(scope); + finalized.add(authorization); + } + + UUID abortedRequest = UUID.randomUUID(); + var abortedScope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + abortedRequest, + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); + assertThat(f.tx(() -> repository.abortSourceRead(abortedScope).state())) + .isEqualTo(State.ABORTED); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + abortedScope.operationId()) + .get(0, Boolean.class)) + .isFalse(); + var abortedContent = content(abortedScope, "stipulated-aborted"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + abortedScope, abortedContent, current, () -> {})))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("scope aborted"); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_authorizations WHERE operation_id = ?", + abortedScope.operationId())) + .isNull(); + + var sourceChange = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), finalized.getFirst().sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(sourceChange))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(sourceChange))).isFalse(); + assertThat(scopes).hasSize(2); + } + } + + @Test + void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var bindings = new ArrayList(); + var terminals = new ArrayList(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + UUID.randomUUID()) + .get(0, Boolean.class)) + .isTrue(); + + for (int index = 0; index < 2; index++) { + UUID requestId = UUID.randomUUID(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + requestId, + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); + var content = content(scope, "automation-settlement-" + index); + var binding = + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + bindings.add(binding); + terminals.add(terminalEvidence(binding, 9001L + index, 9002L + index)); + } + + var firstBinding = bindings.getFirst(); + var secondBinding = bindings.getLast(); + var firstTerminal = terminals.getFirst(); + assertThat(f.tx(() -> repository.findSettlement(firstBinding).isEmpty())).isTrue(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + firstBinding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + + var writerBeforeSettlement = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), firstBinding.sources(), new byte[] {3}); + assertThat(f.tx(() -> f.fences.requestSourceChange(writerBeforeSettlement))) + .isFalse(); + + var committed = f.tx(() -> repository.settleCommittedEmpty(firstTerminal)); + assertThat(committed.authorizationBinding().canonicalBytes()) + .isEqualTo(firstBinding.canonicalBytes()); + assertThat(committed.terminalEvidence().receipt().canonicalBytes()) + .isEqualTo(firstTerminal.receipt().canonicalBytes()); + var stored = + f.dsl.fetchOne( + "SELECT * FROM account_selected_owner_intake_settlements WHERE operation_id = ?", + firstBinding.operationId()); + assertThat(stored.get("receipt_bytes", byte[].class)).isEqualTo(committed.canonicalBytes()); + assertThat(stored.get("receipt_digest", String.class)).isEqualTo(committed.digest()); + assertThat(stored.get("terminal_receipt_bytes", byte[].class)) + .isEqualTo(firstTerminal.receipt().canonicalBytes()); + assertThat(stored.get("terminal_read_request_id", UUID.class)) + .isEqualTo(firstTerminal.request().readRequestId()); + + var exactReadback = f.tx(() -> repository.findSettlement(firstBinding).orElseThrow()); + assertThat(exactReadback.canonicalBytes()).isEqualTo(committed.canonicalBytes()); + f.tx( + () -> { + repository.readFinalAuthorization(firstBinding); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeldFinalAuthorization(firstBinding); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no longer held"); + + var freshRead = + new AutomationSelectedSourceIntakeTerminalReadEvidence( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + "test", firstBinding), + firstTerminal.receipt()); + assertThat(freshRead.request().readRequestId()) + .isNotEqualTo(firstTerminal.request().readRequestId()); + var retry = f.tx(() -> repository.settleCommittedEmpty(freshRead)); + assertThat(retry.canonicalBytes()).isEqualTo(committed.canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT terminal_read_request_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + firstBinding.operationId()) + .get(0, UUID.class)) + .isEqualTo(firstTerminal.request().readRequestId()); + var changedReceipt = terminalEvidence(firstBinding, 9101L, 9102L); + assertThatThrownBy(() -> f.tx(() -> repository.settleCommittedEmpty(changedReceipt))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed Automation owner terminal receipt"); + + var changedSources = new ArrayList<>(firstBinding.sources()); + var originalSource = changedSources.getFirst(); + changedSources.set( + 0, + new DraftAuthorizationFenceBinding.SourceEvidence( + originalSource.kind(), + originalSource.scopeId(), + originalSource.generation(), + originalSource.sourceVersion(), + originalSource.checkpointStream(), + originalSource.checkpointSequence(), + new byte[] {99})); + var changedBinding = + new SelectedOwnerIntakeAuthorizationBinding(firstBinding.content(), changedSources); + var changedBindingEvidence = terminalEvidence(changedBinding, 9201L, 9202L); + assertThatThrownBy(() -> f.tx(() -> repository.settleCommittedEmpty(changedBindingEvidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Original finalized owner authorization absent or changed"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE account_selected_owner_intake_settlements " + + "SET receipt_digest = ? WHERE operation_id = ?", + DraftAuthorizationFenceBinding.digest(new byte[] {1}), + firstBinding.operationId())) + .isInstanceOf(RuntimeException.class); + assertThat( + f.dsl + .fetchSingle( + "SELECT receipt_bytes FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + firstBinding.operationId()) + .get(0, byte[].class)) + .isEqualTo(committed.canonicalBytes()); + + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + firstBinding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + secondBinding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + var writerWhileOtherOperationHeld = writerBeforeSettlement; + assertThat(f.tx(() -> f.fences.requestSourceChange(writerWhileOtherOperationHeld))) + .isFalse(); + + var settlementInserted = new CountDownLatch(1); + var allowSettlementCommit = new CountDownLatch(1); + var writerStarted = new CountDownLatch(1); + var writerBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var settling = + executor.submit( + () -> + f.transactions.execute( + ignored -> { + var result = repository.settleCommittedEmpty(terminals.getLast()); + settlementInserted.countDown(); + awaitLatch(allowSettlementCommit); + return result; + })); + assertThat(settlementInserted.await(10, TimeUnit.SECONDS)).isTrue(); + + var waitingWriter = + executor.submit( + () -> + f.transactions.execute( + ignored -> { + writerBackendPid.set( + f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + writerStarted.countDown(); + return f.fences.requestSourceChange(writerWhileOtherOperationHeld); + })); + assertThat(writerStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(writerBackendPid.get()).isPositive(); + awaitSourceLockWait(f.dsl, writerBackendPid.get()); + assertThat(waitingWriter.isDone()).isFalse(); + + allowSettlementCommit.countDown(); + assertThat(settling.get(10, TimeUnit.SECONDS).authorizationBinding().canonicalBytes()) + .isEqualTo(secondBinding.canonicalBytes()); + assertThat(waitingWriter.get(10, TimeUnit.SECONDS)).isTrue(); + } finally { + allowSettlementCommit.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + secondBinding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + f.tx(() -> f.fences.sourceMutationPermitted(writerWhileOtherOperationHeld))) + .isTrue(); + + String settlementGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('account_selected_owner_intake_settlement_guard()'::regprocedure)") + .get(0, String.class); + assertThat(settlementGuard) + .contains( + "ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key)", + "FOR UPDATE OF lock_row"); + } + } + + @Test + void commitsExactEntityEmptySettlementAndReleasesOnlyThatOperation() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var bindings = new ArrayList(); + var terminals = new ArrayList(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + UUID.randomUUID()) + .get(0, Boolean.class)) + .isTrue(); + + for (int index = 0; index < 2; index++) { + UUID requestId = UUID.randomUUID(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + requestId, + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); + var content = content(scope, "automation-settlement-" + index); + var binding = + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + bindings.add(binding); + terminals.add(entityTerminalEvidence(binding, 9001L + index, 9002L + index)); + } + + var firstBinding = bindings.getFirst(); + var secondBinding = bindings.getLast(); + var firstTerminal = terminals.getFirst(); + assertThat(f.tx(() -> repository.findSettlement(firstBinding).isEmpty())).isTrue(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + firstBinding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + + var writerBeforeSettlement = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), firstBinding.sources(), new byte[] {3}); + assertThat(f.tx(() -> f.fences.requestSourceChange(writerBeforeSettlement))) + .isFalse(); + + var committed = f.tx(() -> repository.settleEntityCommittedEmpty(firstTerminal)); + assertThat(committed.authorizationBinding().canonicalBytes()) + .isEqualTo(firstBinding.canonicalBytes()); + assertThat(committed.entityTerminalEvidence().receipt().canonicalBytes()) + .isEqualTo(firstTerminal.receipt().canonicalBytes()); + var stored = + f.dsl.fetchOne( + "SELECT * FROM account_selected_owner_intake_settlements WHERE operation_id = ?", + firstBinding.operationId()); + assertThat(stored.get("receipt_bytes", byte[].class)).isEqualTo(committed.canonicalBytes()); + assertThat(stored.get("receipt_digest", String.class)).isEqualTo(committed.digest()); + assertThat(stored.get("terminal_receipt_bytes", byte[].class)) + .isEqualTo(firstTerminal.receipt().canonicalBytes()); + assertThat(stored.get("terminal_read_request_id", UUID.class)) + .isEqualTo(firstTerminal.request().readRequestId()); + + var exactReadback = f.tx(() -> repository.findSettlement(firstBinding).orElseThrow()); + assertThat(exactReadback.canonicalBytes()).isEqualTo(committed.canonicalBytes()); + f.tx( + () -> { + repository.readFinalAuthorization(firstBinding); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeldFinalAuthorization(firstBinding); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no longer held"); + + var freshRead = + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create("test", firstBinding), + firstTerminal.receipt()); + assertThat(freshRead.request().readRequestId()) + .isNotEqualTo(firstTerminal.request().readRequestId()); + var retry = f.tx(() -> repository.settleEntityCommittedEmpty(freshRead)); + assertThat(retry.canonicalBytes()).isEqualTo(committed.canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT terminal_read_request_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + firstBinding.operationId()) + .get(0, UUID.class)) + .isEqualTo(firstTerminal.request().readRequestId()); + var changedReceipt = entityTerminalEvidence(firstBinding, 9101L, 9102L); + assertThatThrownBy(() -> f.tx(() -> repository.settleEntityCommittedEmpty(changedReceipt))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed Entity owner terminal receipt"); + + var changedSources = new ArrayList<>(firstBinding.sources()); + var originalSource = changedSources.getFirst(); + changedSources.set( + 0, + new DraftAuthorizationFenceBinding.SourceEvidence( + originalSource.kind(), + originalSource.scopeId(), + originalSource.generation(), + originalSource.sourceVersion(), + originalSource.checkpointStream(), + originalSource.checkpointSequence(), + new byte[] {99})); + var changedBinding = + new SelectedOwnerIntakeAuthorizationBinding(firstBinding.content(), changedSources); + var changedBindingEvidence = entityTerminalEvidence(changedBinding, 9201L, 9202L); + assertThatThrownBy( + () -> f.tx(() -> repository.settleEntityCommittedEmpty(changedBindingEvidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Original finalized owner authorization absent or changed"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE account_selected_owner_intake_settlements " + + "SET receipt_digest = ? WHERE operation_id = ?", + DraftAuthorizationFenceBinding.digest(new byte[] {1}), + firstBinding.operationId())) + .isInstanceOf(RuntimeException.class); + assertThat( + f.dsl + .fetchSingle( + "SELECT receipt_bytes FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + firstBinding.operationId()) + .get(0, byte[].class)) + .isEqualTo(committed.canonicalBytes()); + + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + firstBinding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + secondBinding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + var writerWhileOtherOperationHeld = writerBeforeSettlement; + assertThat(f.tx(() -> f.fences.requestSourceChange(writerWhileOtherOperationHeld))) + .isFalse(); + + var settlementInserted = new CountDownLatch(1); + var allowSettlementCommit = new CountDownLatch(1); + var writerStarted = new CountDownLatch(1); + var writerBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var settling = + executor.submit( + () -> + f.transactions.execute( + ignored -> { + var result = repository.settleEntityCommittedEmpty(terminals.getLast()); + settlementInserted.countDown(); + awaitLatch(allowSettlementCommit); + return result; + })); + assertThat(settlementInserted.await(10, TimeUnit.SECONDS)).isTrue(); + + var waitingWriter = + executor.submit( + () -> + f.transactions.execute( + ignored -> { + writerBackendPid.set( + f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + writerStarted.countDown(); + return f.fences.requestSourceChange(writerWhileOtherOperationHeld); + })); + assertThat(writerStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(writerBackendPid.get()).isPositive(); + awaitSourceLockWait(f.dsl, writerBackendPid.get()); + assertThat(waitingWriter.isDone()).isFalse(); + + allowSettlementCommit.countDown(); + assertThat(settling.get(10, TimeUnit.SECONDS).authorizationBinding().canonicalBytes()) + .isEqualTo(secondBinding.canonicalBytes()); + assertThat(waitingWriter.get(10, TimeUnit.SECONDS)).isTrue(); + } finally { + allowSettlementCommit.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + secondBinding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + f.tx(() -> f.fences.sourceMutationPermitted(writerWhileOtherOperationHeld))) + .isTrue(); + + String settlementGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('account_selected_owner_intake_settlement_guard()'::regprocedure)") + .get(0, String.class); + assertThat(settlementGuard) + .contains( + "ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key)", + "FOR UPDATE OF lock_row"); + } + } + + @Test + void migratesRetainedV1008AutomationBytesWithoutReleasingPendingEntity() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + Clock.systemUTC(), + "1008")) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var automation = + finalizeAutomationBinding(issued, reservations, repository, selected, "retained-v1008"); + var original = + f.tx(() -> repository.settleCommittedEmpty(terminalEvidence(automation, 8801, 8802))); + var entity = + finalizeEntityBinding(issued, reservations, repository, selected, "pending-v1008-entity"); + var terminal = entityTerminalEvidence(entity, 8901, 8902); + byte[] retainedAuthorization = + f.dsl + .fetchSingle( + "SELECT binding_bytes FROM account_selected_owner_intake_authorizations WHERE operation_id = ?", + automation.operationId()) + .get(0, byte[].class); + byte[] retainedTerminal = original.ownerReceiptBytes(); + String pendingDefinition = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('account_selected_owner_intake_source_read_is_pending(uuid)'::regprocedure)") + .get(0, String.class); + assertRejectedSettlementByPostgres( + issued, + entity, + terminal, + terminal.receipt().canonicalBytes(), + "active Automation authorization"); + + String historyQuery = "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1009' ORDER BY installed_rank"; + var retainedHistory = f.dsl.fetch(historyQuery).getValues(0, String.class); + Map> retainedRows = retainedSelectedOwnerRows(f.dsl); + + String schema = f.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + Path current = Path.of("").toAbsolutePath(); + while (current != null + && !java.nio.file.Files.isDirectory( + current.resolve("services/account-service/src/main/resources/db/migration"))) { + current = current.getParent(); + } + Path migrations = + Objects.requireNonNull(current, "Account migrations must be available") + .resolve("services/account-service/src/main/resources/db/migration"); + Flyway.configure() + .dataSource(Objects.requireNonNull(f.manager.getDataSource())) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + migrations, + "filesystem:" + Objects.requireNonNull(current) + .resolve("services/common-saga/src/main/resources/db/migration/saga")) + .target("1009") + .load() + .migrate(); + + assertThat(f.dsl.fetch(historyQuery).getValues(0, String.class)).isEqualTo(retainedHistory); + assertThat(retainedSelectedOwnerRows(f.dsl)).isEqualTo(retainedRows); + + var recovered = f.tx(() -> repository.findSettlement(automation).orElseThrow()); + assertThat(recovered.canonicalBytes()).isEqualTo(original.canonicalBytes()); + assertThat(recovered.digest()).isEqualTo(original.digest()); + assertThat(recovered.ownerReceiptBytes()).isEqualTo(retainedTerminal); + assertThat(recovered.terminalReadRequestId()).isEqualTo(original.terminalReadRequestId()); + assertThat( + f.dsl + .fetchSingle( + "SELECT binding_bytes FROM account_selected_owner_intake_authorizations WHERE operation_id = ?", + automation.operationId()) + .get(0, byte[].class)) + .isEqualTo(retainedAuthorization); + assertThat( + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('account_selected_owner_intake_source_read_is_pending(uuid)'::regprocedure)") + .get(0, String.class)) + .isEqualTo(pendingDefinition); + assertThat(f.tx(() -> repository.findSettlement(entity))).isEmpty(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + entity.operationId()) + .get(0, Boolean.class)) + .isTrue(); + var writer = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), entity.sources(), new byte[] {7}); + assertThat(f.tx(() -> f.fences.requestSourceChange(writer))).isFalse(); + var settledEntity = f.tx(() -> repository.settleEntityCommittedEmpty(terminal)); + assertThat(settledEntity.ownerReceiptBytes()).isEqualTo(terminal.receipt().canonicalBytes()); + assertThatThrownBy(() -> f.tx(() -> repository.abortSourceRead(entity.content().scope()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot be preliminarily aborted"); + assertThatThrownBy( + () -> + f.dsl.execute( + "DELETE FROM account_selected_owner_intake_settlements WHERE operation_id = ?", + automation.operationId())) + .isInstanceOf(RuntimeException.class); + assertThat(f.tx(() -> repository.findSettlement(automation).orElseThrow()).canonicalBytes()) + .isEqualTo(original.canonicalBytes()); + } + } + + @Test + void postgresRejectsMalformedEntityFramesWithoutReleasingItsParticipation() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var binding = + finalizeEntityBinding(issued, reservations, repository, selected, "entity-malformed"); + var terminal = entityTerminalEvidence(binding, 8701, 8702); + byte[] bytes = terminal.receipt().canonicalBytes(); + for (var invalid : + Map.of( + 2, "sha256:" + "0".repeat(64), + 7, "sha256:" + "0".repeat(64), + 16, "22", + 17, "UNKNOWN_ENTITY_FAMILY", + 18, "UNKNOWN", + 19, "V1_SOURCE_CENSUS", + 20, "1", + 201, "00000000-0000-0000-0000-000000000000", + 203, "not-a-uuid", + 204, "2026-10-10T00:00:00.000Z") + .entrySet()) { + assertRejectedSettlementByPostgres( + issued, + binding, + terminal, + replaceFrame( + bytes, invalid.getKey(), invalid.getValue().getBytes(StandardCharsets.UTF_8)), + "Entity"); + } + assertRejectedSettlementByPostgres( + issued, + binding, + terminal, + replaceFrame(bytes, 4, new byte[] {1}), + "Entity terminal changed original authorization"); + assertRejectedSettlementByPostgres( + issued, + binding, + terminal, + replaceFrame(bytes, 8, "{}".getBytes(StandardCharsets.UTF_8)), + "Entity terminal changed original source revision binding"); + assertRejectedSettlementByPostgres( + issued, + binding, + terminal, + replaceLastFrame(bytes, null, true), + "Entity terminal timestamp or trailing bytes are invalid"); + var writer = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), binding.sources(), new byte[] {8}); + assertThat(f.tx(() -> f.fences.requestSourceChange(writer))).isFalse(); + var settled = f.tx(() -> repository.settleEntityCommittedEmpty(terminal)); + assertThat( + AccountSelectedOwnerIntakeSettlementReceipt.fromStored(settled.canonicalBytes()) + .canonicalBytes()) + .isEqualTo(settled.canonicalBytes()); + assertThat(f.tx(() -> repository.findSettlement(binding).orElseThrow()).ownerReceiptBytes()) + .isEqualTo(bytes); + } + } + + private static byte[] replaceFrame(byte[] bytes, int selectedFrame, byte[] replacement) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + var out = new ByteArrayOutputStream(); + int index = 0; + while (reader.remaining() > 0) { + byte[] original = reader.bytes(); + DraftAuthorizationFenceBinding.frame(out, index++ == selectedFrame ? replacement : original); + } + reader.requireEnd(); + return out.toByteArray(); + } + + @Test + void postgresPreservesCanonicalAutomationTimestampBytesAndRejectsNoncanonicalFrames() + throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + + var rejectedBinding = + finalizeAutomationBinding( + issued, reservationService, repository, selected, "timestamp-invalid"); + var validBase = + terminalEvidence( + rejectedBinding, 9301L, 9302L, OffsetDateTime.parse("2026-10-10T00:00Z")); + var validOwnerBytes = validBase.receipt().canonicalBytes(); + assertThat(lastFrame(validOwnerBytes)).isEqualTo("2026-10-10T00:00Z"); + + for (String noncanonicalTimestamp : + List.of( + "2026-10-10T24:00Z", + "2026-10-10T00:00:60Z", + "2026-10-10T00:00:00Z", + "2026-10-10T00:00:00.000Z", + "2026-10-10T00:00:00.123450000Z", + "2026-10-10T00:00:00.12Z", + "2026-10-10T00:00:00.120000Z", + "2026-10-10T00:00:00+01:00")) { + assertRejectedSettlementByPostgres( + issued, + rejectedBinding, + validBase, + replaceLastFrame(validOwnerBytes, noncanonicalTimestamp, false), + "Automation terminal receipt timestamp or trailing bytes are invalid"); + } + assertRejectedSettlementByPostgres( + issued, + rejectedBinding, + validBase, + replaceLastFrame(validOwnerBytes, null, true), + "Automation terminal receipt timestamp or trailing bytes are invalid"); + + var canonicalTimestamps = + List.of( + "2026-10-10T00:00Z", + "2026-10-10T00:00:01Z", + "2026-10-10T00:00:00.120Z", + "2026-10-10T00:00:00.123450Z", + "2026-10-10T00:00:00.123456780Z"); + for (int index = 0; index < canonicalTimestamps.size(); index++) { + String timestamp = canonicalTimestamps.get(index); + var binding = + index == 0 + ? rejectedBinding + : finalizeAutomationBinding( + issued, + reservationService, + repository, + selected, + "timestamp-canonical-" + index); + var terminal = + index == 0 + ? validBase + : terminalEvidence( + binding, 9401L + index, 9402L + index, OffsetDateTime.parse(timestamp)); + assertThat(lastFrame(terminal.receipt().canonicalBytes())).isEqualTo(timestamp); + + var committed = f.tx(() -> repository.settleCommittedEmpty(terminal)); + assertThat(committed.terminalEvidence().receipt().canonicalBytes()) + .isEqualTo(terminal.receipt().canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT terminal_receipt_bytes FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + binding.operationId()) + .get(0, byte[].class)) + .isEqualTo(terminal.receipt().canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + binding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + } + } + } + + @Test + void postgresRejectsChangedNamespaceUnknownFamilyAndSelectedScopeEvidence() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var scopes = new ArrayList(); + for (int index = 0; index < 3; index++) { + scopes.add( + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment()))); + } + + var original = scopes.get(0); + var changedNamespace = + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + "different-namespace", + original.operationId(), + original.fenceId(), + original.intakeRequestId(), + original.actorAccountId(), + original.selected()); + var namespaceContent = content(changedNamespace, "stipulated-namespace-mismatch"); + var namespaceBinding = + new SelectedOwnerIntakeAuthorizationBinding( + namespaceContent, + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment()).sources())); + assertRejectedByPostgres( + issued, + original, + namespaceContent.canonicalBytes(), + namespaceBinding.canonicalBytes(), + "Selected content scope differs from original reservation"); + + var familyScope = scopes.get(1); + var familyContent = content(familyScope, "stipulated-family-mismatch"); + byte[] unknownFamilyContent = replaceFirstFamily(familyContent.canonicalBytes(), "UNKNOWN"); + var familySources = + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment()).sources()); + assertRejectedByPostgres( + issued, + familyScope, + unknownFamilyContent, + authorizationBytes(familyScope, unknownFamilyContent, familySources), + "Selected owner content family is missing, unknown, or changed"); + + var selectedScope = scopes.get(2); + var changedSelectedScope = + new SelectedOwnerIntakeSourceReadScope( + selectedScope.owner(), + selectedScope.targetNamespace(), + selectedScope.operationId(), + selectedScope.fenceId(), + selectedScope.intakeRequestId(), + selectedScope.actorAccountId(), + selected(f.tenant)); + var changedSelectedContent = content(changedSelectedScope, "stipulated-scope-mismatch"); + var changedSelectedBinding = + new SelectedOwnerIntakeAuthorizationBinding( + changedSelectedContent, + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment()).sources())); + assertRejectedByPostgres( + issued, + selectedScope, + changedSelectedContent.canonicalBytes(), + changedSelectedBinding.canonicalBytes(), + "Selected content scope differs from original reservation"); + } + } + + private static void assertRejectedByPostgres( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + SelectedOwnerIntakeSourceReadScope reservationScope, + byte[] contentBytes, + byte[] bindingBytes, + String expectedDiagnostic) { + var f = issued.sources(); + assertThatThrownBy( + () -> + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + insertRawAuthorization( + f.dsl, reservationScope, contentBytes, bindingBytes, current); + return null; + }))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_authorizations " + + "WHERE operation_id = ?", + reservationScope.operationId())) + .isNull(); + } + + private static void insertRawAuthorization( + org.jooq.DSLContext dsl, + SelectedOwnerIntakeSourceReadScope reservationScope, + byte[] contentBytes, + byte[] bindingBytes, + AccountControlUiActorService.Current current) { + dsl.execute( + "INSERT INTO account_selected_owner_intake_authorizations " + + "(operation_id, fence_id, intake_request_id, owner, target_namespace, " + + "actor_account_uuid, tenant_uuid, version_uuid, content_bytes, content_digest, " + + "binding_bytes, binding_digest, issuance_operation_id, issuance_fence, source_payload, " + + "issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + reservationScope.operationId(), + reservationScope.fenceId(), + reservationScope.intakeRequestId(), + reservationScope.owner().name(), + reservationScope.targetNamespace(), + reservationScope.actorAccountId(), + reservationScope.selected().target().canonicalTenantId(), + reservationScope.selected().target().canonicalVersionId(), + contentBytes, + DraftAuthorizationFenceBinding.digest(contentBytes), + bindingBytes, + DraftAuthorizationFenceBinding.digest(bindingBytes), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + AccountControlUiAuthority.canonical(current.source().outboxCheckpoints())); + var sources = + current.source().sources().stream() + .sorted(Comparator.comparing(DraftAuthorizationFenceBinding.SourceEvidence::key)) + .toList(); + for (var source : sources) { + dsl.execute( + "INSERT INTO account_selected_owner_intake_sources " + + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + reservationScope.operationId(), + source.key(), + source.canonicalBytes()); + } + } + + private static byte[] authorizationBytes( + SelectedOwnerIntakeSourceReadScope scope, + byte[] contentBytes, + List sources) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, authorizationSchema(scope.owner())); + DraftAuthorizationFenceBinding.frame(out, contentBytes); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(contentBytes)); + DraftAuthorizationFenceBinding.frame( + out, + scope.owner() == Owner.ENTITY_MANAGEMENT + ? "spiffe://firemud/ns/" + scope.targetNamespace() + "/sa/entity-management-service" + : "spiffe://firemud/ns/" + + scope.targetNamespace() + + "/sa/automation-scripting-service"); + DraftAuthorizationFenceBinding.frame( + out, + scope.owner() == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_RETENTION" + : "AUTOMATION_INTAKE_RETENTION"); + var sorted = + sources.stream() + .sorted(Comparator.comparing(DraftAuthorizationFenceBinding.SourceEvidence::key)) + .toList(); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sorted.size())); + for (var source : sorted) DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + return out.toByteArray(); + } + + private static String authorizationSchema(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "account-entity-intake-authorization/v1" + : "account-automation-intake-authorization/v1"; + } + + private static byte[] replaceFirstFamily(byte[] contentBytes, String replacement) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(contentBytes); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, reader.text()); + DraftAuthorizationFenceBinding.frame(out, reader.bytes()); + DraftAuthorizationFenceBinding.frame(out, reader.text()); + for (int index = 0; index < 6; index++) { + String family = reader.text(); + DraftAuthorizationFenceBinding.frame(out, index == 0 ? replacement : family); + DraftAuthorizationFenceBinding.frame(out, reader.bytes()); + DraftAuthorizationFenceBinding.frame(out, reader.text()); + } + reader.requireEnd(); + return out.toByteArray(); + } + + private static void settleOriginal( + 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 SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, String marker) { + var selected = scope.selected(); + UUID genesis = UUID.nameUUIDFromBytes(marker.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String markerEpoch = Integer.toUnsignedString(marker.hashCode()); + 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 = templateSnapshot(scope.owner(), selected, genesis); + var snapshots = + Map.of( + "COMMAND", + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest( + marker.getBytes(java.nio.charset.StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(), + "REALM_POLICY", + new RealmPolicySnapshot(selected, markerEpoch, List.of()).canonicalBytes(), + "ASSET", + new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(), + "BRANDING", + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes()); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> snapshots.get(family); + }; + DraftAuthorizationFenceBinding.frame(out, family); + DraftAuthorizationFenceBinding.frame(out, snapshot); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + Owner owner, DraftCommitBinding selected, UUID genesis) { + String payload; + if (owner == Owner.ENTITY_MANAGEMENT) { + payload = TemplateConfigSourceValues.ownerInventoryPayload(owner, emptyEntityDeclaration()); + } else { + var inventory = + AutomationAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + payload = TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory); + } + DraftCommitBinding authored = + DraftCommitBinding.create( + selected.target(), + UUID.randomUUID(), + UUID.randomUUID(), + "synthetic-template-config-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + selected.target().canonicalVersionId().toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + TemplateConfigOwnerSourceInventoryDeclaration declaration = + TemplateConfigSourceValues.mutations(authored).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .findFirst() + .orElseThrow(); + return new TemplateConfigSourceSnapshot( + selected, "0", null, genesis, List.of(), List.of(declaration)); + } + + private static SelectedOwnerIntakeAuthorizationBinding finalizeAutomationBinding( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + AccountSelectedOwnerIntakeSourceReservationService reservationService, + AccountSelectedOwnerIntakeSourceReservationRepository repository, + DraftCommitBinding selected, + String marker) { + var f = issued.sources(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); + var selectedContent = content(scope, marker); + return asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + selectedContent, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + } + + private static SelectedOwnerIntakeAuthorizationBinding finalizeEntityBinding( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + AccountSelectedOwnerIntakeSourceReservationService reservationService, + AccountSelectedOwnerIntakeSourceReservationRepository repository, + DraftCommitBinding selected, + String marker) { + var f = issued.sources(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); + var selectedContent = content(scope, marker); + return asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + selectedContent, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + } + + private static void assertRejectedSettlementByPostgres( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + SelectedOwnerIntakeAuthorizationBinding binding, + AutomationSelectedSourceIntakeTerminalReadEvidence validEvidence, + byte[] changedOwnerReceiptBytes, + String expectedDiagnostic) { + var f = issued.sources(); + assertThatThrownBy( + () -> + f.tx( + () -> { + insertRawSettlement(f.dsl, binding, validEvidence, changedOwnerReceiptBytes); + return null; + })) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + binding.operationId())) + .isNull(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + binding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + } + + private static void insertRawSettlement( + org.jooq.DSLContext dsl, + SelectedOwnerIntakeAuthorizationBinding binding, + AutomationSelectedSourceIntakeTerminalReadEvidence evidence, + byte[] ownerReceiptBytes) { + String ownerReceiptDigest = DraftAuthorizationFenceBinding.digest(ownerReceiptBytes); + byte[] receiptBytes = + settlementReceiptBytes(binding, evidence, ownerReceiptBytes, ownerReceiptDigest); + dsl.execute( + "INSERT INTO account_selected_owner_intake_settlements " + + "(operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " + + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.owner().name(), + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + binding.canonicalBytes(), + binding.digest(), + evidence.request().readRequestId(), + ownerReceiptBytes, + ownerReceiptDigest, + receiptBytes, + DraftAuthorizationFenceBinding.digest(receiptBytes)); + } + + private static byte[] settlementReceiptBytes( + SelectedOwnerIntakeAuthorizationBinding binding, + AutomationSelectedSourceIntakeTerminalReadEvidence evidence, + byte[] ownerReceiptBytes, + String ownerReceiptDigest) { + var request = evidence.request(); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, AccountSelectedOwnerIntakeSettlementReceipt.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, "1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, binding.digest()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(request.schemaVersion())); + DraftAuthorizationFenceBinding.frame(out, request.targetNamespace()); + DraftAuthorizationFenceBinding.frame(out, request.readRequestId().toString()); + DraftAuthorizationFenceBinding.frame(out, request.intendedReader()); + DraftAuthorizationFenceBinding.frame(out, request.terminalReadPurpose()); + DraftAuthorizationFenceBinding.frame(out, request.binding().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, request.binding().digest()); + DraftAuthorizationFenceBinding.frame(out, ownerReceiptBytes); + DraftAuthorizationFenceBinding.frame(out, ownerReceiptDigest); + return out.toByteArray(); + } + + private static void assertRejectedSettlementByPostgres( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + SelectedOwnerIntakeAuthorizationBinding binding, + EntitySelectedSourceIntakeTerminalReadEvidence validEvidence, + byte[] changedOwnerReceiptBytes, + String expectedDiagnostic) { + var f = issued.sources(); + assertThatThrownBy( + () -> + f.tx( + () -> { + insertRawSettlement(f.dsl, binding, validEvidence, changedOwnerReceiptBytes); + return null; + })) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + binding.operationId())) + .isNull(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + binding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + } + + private static void insertRawSettlement( + org.jooq.DSLContext dsl, + SelectedOwnerIntakeAuthorizationBinding binding, + EntitySelectedSourceIntakeTerminalReadEvidence evidence, + byte[] ownerReceiptBytes) { + String ownerReceiptDigest = DraftAuthorizationFenceBinding.digest(ownerReceiptBytes); + byte[] receiptBytes = + settlementReceiptBytes(binding, evidence, ownerReceiptBytes, ownerReceiptDigest); + dsl.execute( + "INSERT INTO account_selected_owner_intake_settlements " + + "(operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " + + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.owner().name(), + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + binding.canonicalBytes(), + binding.digest(), + evidence.request().readRequestId(), + ownerReceiptBytes, + ownerReceiptDigest, + receiptBytes, + DraftAuthorizationFenceBinding.digest(receiptBytes)); + } + + private static byte[] settlementReceiptBytes( + SelectedOwnerIntakeAuthorizationBinding binding, + EntitySelectedSourceIntakeTerminalReadEvidence evidence, + byte[] ownerReceiptBytes, + String ownerReceiptDigest) { + var request = evidence.request(); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, AccountSelectedOwnerIntakeSettlementReceipt.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, "1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, binding.digest()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(request.schemaVersion())); + DraftAuthorizationFenceBinding.frame(out, request.targetNamespace()); + DraftAuthorizationFenceBinding.frame(out, request.readRequestId().toString()); + DraftAuthorizationFenceBinding.frame(out, request.intendedReader()); + DraftAuthorizationFenceBinding.frame(out, request.terminalReadPurpose()); + DraftAuthorizationFenceBinding.frame(out, request.binding().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, request.binding().digest()); + DraftAuthorizationFenceBinding.frame(out, ownerReceiptBytes); + DraftAuthorizationFenceBinding.frame(out, ownerReceiptDigest); + return out.toByteArray(); + } + + private static byte[] replaceLastFrame( + byte[] canonicalBytes, String replacement, boolean appendTrailingByte) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(canonicalBytes); + var frames = new ArrayList(); + while (reader.remaining() > 0) frames.add(reader.bytes()); + reader.requireEnd(); + if (replacement != null) { + frames.set(frames.size() - 1, replacement.getBytes(StandardCharsets.UTF_8)); + } + var out = new ByteArrayOutputStream(); + for (byte[] frame : frames) DraftAuthorizationFenceBinding.frame(out, frame); + if (appendTrailingByte) out.write(0x5a); + return out.toByteArray(); + } + + private static String lastFrame(byte[] canonicalBytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(canonicalBytes); + byte[] last = null; + while (reader.remaining() > 0) last = reader.bytes(); + reader.requireEnd(); + byte[] timestampFrame = + Objects.requireNonNull(last, "Complete Automation receipt must contain a timestamp frame"); + return new String(timestampFrame, StandardCharsets.UTF_8); + } + + private static final List ENTITY_FAMILIES = + List.of( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS", + "BODY_LAYOUT_ROOTS", + "CRAFTING_INGREDIENT_BINDINGS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_RECIPE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "EQUIPMENT_SLOT_GROUPS", + "EQUIPMENT_SLOT_ROOTS", + "INBOUND_LOOT_BINDINGS", + "ITEM_TEMPLATE_ROOTS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS"); + private static final java.util.Set ENTITY_V1_FAMILIES = + java.util.Set.of( + "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS"); + + private static EntityAuthoredSourceInventoryDeclaration emptyEntityDeclaration() { + String families = + ENTITY_FAMILIES.stream() + .map(name -> "\"" + name + "\":[]") + .collect(java.util.stream.Collectors.joining(",")); + return EntityAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + families + + "}}"); + } + + private static EntitySelectedSourceIntakeTerminalReadEvidence entityTerminalEvidence( + SelectedOwnerIntakeAuthorizationBinding binding, long localTenantKey, long localVersionKey) { + var freeze = freezeEvidence(binding); + var request = + SelectedOwnerWorldInventoryReadEvidence.create(binding.targetNamespace(), binding, freeze); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var inputs = + new SelectedOwnerEmptySourceInputs( + binding, new SelectedOwnerWorldInventoryReadEvidence(request, inventory)); + var states = + ENTITY_FAMILIES.stream() + .map( + family -> + new FamilyCensus( + family, + FamilyState.EMPTY, + ENTITY_V1_FAMILIES.contains(family) + ? FamilyEvidenceKind.V1_SOURCE_CENSUS + : FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER, + 0, + 0, + 0, + 0, + 0)) + .toList(); + var receipt = + EntityEmptySelectedSourceIntakeReceipt.create( + inputs, + UUID.randomUUID(), + localTenantKey, + localVersionKey, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + binding.targetNamespace(), binding, freeze), + states, + OffsetDateTime.parse("2026-10-10T00:00:00.120Z")); + return new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + binding.targetNamespace(), binding), + receipt); + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence( + SelectedOwnerIntakeAuthorizationBinding binding, long localTenantKey, long localVersionKey) { + return terminalEvidence( + binding, localTenantKey, localVersionKey, OffsetDateTime.parse("2026-10-10T00:00:00Z")); + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence( + SelectedOwnerIntakeAuthorizationBinding binding, + long localTenantKey, + long localVersionKey, + OffsetDateTime retainedAt) { + var freeze = freezeEvidence(binding); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(binding.targetNamespace(), binding, freeze); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + var inputs = new SelectedOwnerEmptySourceInputs(binding, worldEvidence); + var receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + inputs, + localTenantKey, + localVersionKey, + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + binding.targetNamespace(), binding, freeze), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + retainedAt); + return new AutomationSelectedSourceIntakeTerminalReadEvidence( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + binding.targetNamespace(), binding), + receipt); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + SelectedOwnerIntakeAuthorizationBinding binding) { + var selected = binding.selected(); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + binding.tenantId(), + binding.versionId(), + "settlement-publication-request", + "9", + "synthetic selected-owner settlement fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + binding.actorAccountId(), selection), + List.of(accountSource(binding.actorAccountId()))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + UUID.randomUUID(), + 9, + UUID.randomUUID(), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var closure = + new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(UUID.randomUUID(), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + closure); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + UUID.randomUUID(), + acknowledgement.intakeRequestId(), + UUID.randomUUID(), + "sha256:" + "1".repeat(64), + UUID.randomUUID(), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + UUID.randomUUID(), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static SourceEvidence accountSource(UUID accountId) { + return new SourceEvidence( + SourceKind.ACCOUNT, + accountId.toString(), + null, + "1", + null, + null, + "synthetic-account-publication".getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected(UUID tenant) { + var target = + new DraftCommitBinding.TargetProof( + tenant, UUID.randomUUID(), 17, "private", 11, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("synthetic-fixture-command"))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static DraftCommitBinding selectedForSettlement(UUID tenant) { + var target = + new DraftCommitBinding.TargetProof( + tenant, UUID.randomUUID(), 17, "private", 11, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Expected concurrent settlement boundary"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted concurrent settlement boundary", interrupted); + } + } + + private static void awaitSourceLockWait(DSLContext dsl, int writerBackendPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + do { + if (Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity" + + " WHERE pid = ? AND datname = current_database()" + + " AND wait_event_type = 'Lock'" + + " AND query LIKE '%account_draft_authorization_source_locks%')", + writerBackendPid) + .get(0, Boolean.class))) { + return; + } + Thread.sleep(10); + } while (System.nanoTime() < deadline); + throw new AssertionError("Source writer did not block on settlement-held source locks"); + } + + private static Map> retainedSelectedOwnerRows(DSLContext dsl) { + Map> rows = new LinkedHashMap<>(); + for (String table : List.of("account_selected_owner_intake_source_read_reservations", + "account_selected_owner_intake_source_read_sources", "account_selected_owner_intake_source_read_aborts", + "account_selected_owner_intake_authorizations", "account_selected_owner_intake_sources", + "account_selected_owner_intake_settlements")) { + rows.put(table, dsl.fetch("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + + table + " t ORDER BY to_jsonb(t)::TEXT").getValues(0, String.class)); + } + return rows; + } + + private static T asGameDesign(java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java new file mode 100644 index 0000000000..4666b4da76 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerProtoCodec; +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.support.TransactionSynchronizationManager; + +/** + * Receiver boundary tests; the mocked owner does not establish durable retry or retention proof. + */ +class AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String CREDENTIAL = "original.creator.credential"; + + private final AccountSelectedOwnerIntakeAuthorizationService owner = + mock(AccountSelectedOwnerIntakeAuthorizationService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountSelectedOwnerIntakeAuthorizationProducerGrpcService receiver = + new AccountSelectedOwnerIntakeAuthorizationProducerGrpcService(owner, terms, NAMESPACE); + + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsWrongPeerNamespaceAndEndUserBeforeCredentialOrRequestDecoding() { + assertThat(invokeAuthorize(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer(NAMESPACE, "world-management-service", () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("42", List.of(), java.util.Map.of()); + assertThat(peer(NAMESPACE, "game-design-service", () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorChecksPeerAndMethodBeforeProtectedMetadata() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers, null)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer(NAMESPACE, "world-management-service", () -> boundCode(headers, null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers, null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("42", List.of(), java.util.Map.of()); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(headers, null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + SessionContext.clear(); + + var empty = new io.grpc.Metadata(); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(empty, null))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + var duplicate = new io.grpc.Metadata(); + duplicate.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(CREDENTIAL)); + duplicate.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(CREDENTIAL)); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(duplicate, null))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(empty, "OtherMethod"))) + .isEqualTo(Status.Code.UNIMPLEMENTED); + verifyNoInteractions(owner, terms); + } + + @Test + void rejectsMalformedRequestAndRequestNamespaceBeforeOwnerAccess() { + assertThat(authorized(() -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + var valid = request(Owner.ENTITY_MANAGEMENT); + assertThat( + authorized(() -> invokeAuthorize(valid.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner, terms); + } + + @Test + void delegatesExactRequestAndEnvironmentCaptureAndPassesThroughOwnerBindingOnRetry() { + var wire = request(Owner.AUTOMATION_SCRIPTING); + var decoded = SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromRequest(wire); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + byte[] authorizationBytes = {1, 2, 3, 4}; + String digest = "a".repeat(64); + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.owner()).thenReturn(decoded.owner()); + when(binding.targetNamespace()).thenReturn(NAMESPACE); + when(binding.intakeRequestId()).thenReturn(decoded.intakeRequestId()); + when(binding.selected()).thenReturn(decoded.selected()); + when(binding.intendedReader()) + .thenReturn("spiffe://firemud/ns/" + NAMESPACE + "/sa/automation-scripting-service"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.digest()).thenReturn(digest); + when(binding.canonicalBytes()).thenReturn(authorizationBytes); + when(owner.authorizeWithEnvironmentCapture( + eq(CREDENTIAL), + eq(decoded.intakeRequestId()), + eq(decoded.owner()), + eq(decoded.selected()), + any())) + .thenAnswer( + call -> { + Supplier capture = call.getArgument(4); + assertThat(capture.get()).isSameAs(captured); + return binding; + }); + + var first = authorized(() -> invokeAuthorize(wire)); + var retry = authorized(() -> invokeAuthorize(wire)); + assertThat(first.error()).isNull(); + assertThat(retry.error()).isNull(); + for (var result : List.of(first, retry)) { + assertThat(result.response().getRequest()).isEqualTo(wire); + assertThat(result.response().getIntakeAuthorizationBinding().toByteArray()) + .containsExactly(authorizationBytes); + assertThat(result.response().getIntakeAuthorizationDigest()).isEqualTo(digest); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + } + verify(owner, times(2)) + .authorizeWithEnvironmentCapture( + eq(CREDENTIAL), + eq(decoded.intakeRequestId()), + eq(decoded.owner()), + eq(decoded.selected()), + any()); + assertThat(wire.toString()).doesNotContain(CREDENTIAL); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeCallingOwner() { + var wire = request(Owner.ENTITY_MANAGEMENT); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThat(authorized(() -> invokeAuthorize(wire)).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThat(authorized(() -> invokeAuthorize(wire)).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(owner, terms); + } + + @Test + void sanitizesOwnerFailures() { + when(owner.authorizeWithEnvironmentCapture(any(), any(), any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()); + var denied = authorized(() -> invokeAuthorize(request(Owner.ENTITY_MANAGEMENT))); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private record Result( + SelectedOwnerIntakeAuthorizationProducerResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invokeAuthorize(SelectedOwnerIntakeAuthorizationProducerRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + var observer = + new io.grpc.stub.StreamObserver() { + @Override + public void onNext(SelectedOwnerIntakeAuthorizationProducerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }; + receiver.authorizeSelectedOwnerIntake(request, observer); + return new Result(response.get(), error.get()); + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers, String replacementMethodName) { + var method = + (io.grpc.ServerMethodDefinition< + SelectedOwnerIntakeAuthorizationProducerRequest, + SelectedOwnerIntakeAuthorizationProducerResponse>) + receiver.bindService().getMethods().stream().findFirst().orElseThrow(); + io.grpc.ServerCall< + SelectedOwnerIntakeAuthorizationProducerRequest, + SelectedOwnerIntakeAuthorizationProducerResponse> + call = mock(io.grpc.ServerCall.class); + var descriptor = method.getMethodDescriptor(); + if (replacementMethodName != null) { + descriptor = + MethodDescriptor + . + newBuilder() + .setType(descriptor.getType()) + .setFullMethodName( + AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc.SERVICE_NAME + + "/" + + replacementMethodName) + .setRequestMarshaller(descriptor.getRequestMarshaller()) + .setResponseMarshaller(descriptor.getResponseMarshaller()) + .build(); + } + when(call.getMethodDescriptor()).thenReturn(descriptor); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + private static T authorized(Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(CREDENTIAL)); + var previous = context.attach(); + try { + return peer(NAMESPACE, "game-design-service", action); + } finally { + context.detach(previous); + } + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static SelectedOwnerIntakeAuthorizationProducerRequest request(Owner owner) { + var safe = + SelectedOwnerIntakeAuthorizationProducerEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), owner, selected()); + return SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(safe); + } + + private static DraftCommitBinding selected() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java new file mode 100644 index 0000000000..9603c2eaf1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java @@ -0,0 +1,232 @@ +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.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +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.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadGrpcCodec; +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; + +/** Synthetic handler tests only; they do not establish mTLS or PostgreSQL owner proof. */ +class AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest { + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void authenticatesOwnerAndRejectsEndUserBeforeParsingOrOwnerAccess() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + var malformed = + ReadHeldSelectedOwnerIntakeAuthorizationRequest.newBuilder() + .setTargetNamespace("test") + .setSchemaVersion(-1) + .build(); + + var noPeer = new Collector(); + service.readHeldSelectedOwnerIntakeAuthorization(malformed, noPeer); + assertThat(noPeer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + + for (String workload : + List.of( + "account-service", + "game-design-service", + "game-logic-service", + "world-management-service")) { + var denied = new Collector(); + peer("test", workload) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(malformed, denied)); + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var otherNamespace = new Collector(); + peer("other", "entity-management-service") + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(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", "entity-management-service") + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(malformed, endUser)); + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + + var allowedPeerMalformed = new Collector(); + peer("test", "entity-management-service") + .run( + () -> + service.readHeldSelectedOwnerIntakeAuthorization(malformed, allowedPeerMalformed)); + assertThat(allowedPeerMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void returnsExactEchoOnlyForMatchingEntityAndAutomationReader() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + + for (Owner domain : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(domain); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + var wire = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest(request); + var result = new Collector(); + peerFromUri(binding.intendedReader()) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(wire, result)); + + assertThat(result.error).isNull(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getRequest()).isEqualTo(wire); + assertThat(result.response.getHeld()).isTrue(); + } + verify(owner, times(2)).requireHeld(any()); + } + + @Test + void entityCannotReadAutomationAndAutomationCannotReadEntity() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + + for (Owner bindingOwner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(bindingOwner); + var request = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding)); + String wrongReader = + bindingOwner == Owner.ENTITY_MANAGEMENT + ? "automation-scripting-service" + : "entity-management-service"; + var result = new Collector(); + peer("test", wrongReader) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(request, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(result.response).isNull(); + } + verifyNoInteractions(owner); + } + + @Test + void rejectsWrongNamespaceClosedFieldsDigestUnknownFieldsAndMalformedSizes() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var valid = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding)); + + var wrongNamespace = new Collector(); + peer("test", "entity-management-service") + .run( + () -> + service.readHeldSelectedOwnerIntakeAuthorization( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + var changedReader = + valid.toBuilder().setIntendedReader("spiffe://firemud/ns/test/sa/account-service").build(); + var changedPurpose = valid.toBuilder().setRetentionPurpose("ENTITY_INTAKE_SOURCE").build(); + var changedDigest = + valid.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var malformedBinding = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversizedBinding = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + for (var malformed : + List.of( + changedReader, + changedPurpose, + changedDigest, + unknown, + malformedBinding, + oversizedBinding)) { + var result = new Collector(); + peerFromUri(binding.intendedReader()) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + verifyNoInteractions(owner); + } + + @Test + void mapsOwnerReadFailureToNoHeldResponse() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + org.mockito.Mockito.doThrow(Status.FAILED_PRECONDITION.asRuntimeException()) + .when(owner) + .requireHeld(any()); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var wire = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding)); + var result = new Collector(); + + peerFromUri(binding.intendedReader()) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(wire, result)); + + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.response).isNull(); + } + + private static Context peer(String namespace, String workload) { + return peerFromUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload); + } + + private static Context peerFromUri(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + private ReadHeldSelectedOwnerIntakeAuthorizationResponse response; + private Status.Code error; + + @Override + public void onNext(ReadHeldSelectedOwnerIntakeAuthorizationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..bd9dbc2025 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.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.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +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.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +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.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic Account read tests; they do not establish PostgreSQL or owner-terminal proof. */ +class AccountSelectedOwnerIntakeAuthorizationReadServiceTest { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + + @AfterEach + void clearCallerAndTransactionContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactEntityAndAutomationBindingsInIndependentReadCommittedTransactions() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + var service = newService(); + + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = binding(owner); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + asReader(binding, () -> service.requireHeld(request)); + verify(repository).readHeldFinalAuthorization(binding); + } + + var definitions = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions, times(2)).getTransaction(definitions.capture()); + assertThat(definitions.getAllValues()) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + } + + @Test + void rejectsMissingWrongOwnerAndEndUserContextsBeforeRepositoryAccess() { + var service = newService(); + var entity = binding(Owner.ENTITY_MANAGEMENT); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", entity); + + assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + asPeer( + "test", + "automation-scripting-service", + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + asReader( + entity, + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void rejectsAmbientSqlBeforeStartingOwnerRead() { + var service = newService(); + var binding = binding(Owner.ENTITY_MANAGEMENT); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + asReader( + binding, + () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void distinguishesAbsentOrChangedAuthorizationFromUnavailableStorage() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + var service = newService(); + var binding = binding(Owner.AUTOMATION_SCRIPTING); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + + org.mockito.Mockito.doThrow(new IllegalArgumentException("not available")) + .when(repository) + .readHeldFinalAuthorization(binding); + asReader( + binding, + () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); + + org.mockito.Mockito.doThrow(new IllegalStateException("storage unavailable")) + .when(repository) + .readHeldFinalAuthorization(binding); + asReader( + binding, () -> assertCode(Status.Code.UNAVAILABLE, () -> service.requireHeld(request))); + } + + private AccountSelectedOwnerIntakeAuthorizationReadService newService() { + return new AccountSelectedOwnerIntakeAuthorizationReadService(repository, transactions, "test"); + } + + static SelectedOwnerIntakeAuthorizationBinding binding(Owner owner) { + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + UUID operation = id("55555555-5555-4555-8555-555555555555"); + UUID fence = id("66666666-6666-4666-8666-666666666666"); + UUID intake = id("77777777-7777-4777-8777-777777777777"); + var selected = selected(tenant); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, "test", operation, fence, intake, actor, selected); + return new SelectedOwnerIntakeAuthorizationBinding(content(scope), sources(actor, tenant)); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = snapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] snapshot(String family, DraftCommitBinding selected) { + UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + return switch (family) { + case "COMMAND" -> + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest( + "synthetic-read-fixture".getBytes(StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + 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()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "TEMPLATE_CONFIG" -> + new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); + }; + } + + private static List sources(UUID actor, UUID tenant) { + return List.of( + evidence(SourceKind.TENANT, tenant.toString(), "tenant"), + evidence(SourceKind.ACCOUNT, actor.toString(), "account"), + evidence(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership")); + } + + private static SourceEvidence evidence(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected(UUID tenant) { + UUID version = id("22222222-2222-4222-8222-222222222222"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("synthetic-fixture-command"))), + 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 static void asReader(SelectedOwnerIntakeAuthorizationBinding binding, Runnable action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(binding.intendedReader()).orElseThrow()); + peer.run(action); + } + + 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()); + peer.run(action); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(error -> assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationRepositoryTest.java new file mode 100644 index 0000000000..8db02479e7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationRepositoryTest.java @@ -0,0 +1,29 @@ +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 repository boundary proof; PostgreSQL finalization is covered separately. */ +class AccountSelectedOwnerIntakeAuthorizationRepositoryTest { + @Test + void finalizationAndExactReadsRequireWritableOwnerTransactions() { + var dsl = mock(DSLContext.class); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl); + + assertThatThrownBy(() -> repository.finalizeSourceRead(null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.findFinalAuthorization(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.readFinalAuthorization(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/AccountSelectedOwnerIntakeAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java new file mode 100644 index 0000000000..b1f8d51584 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java @@ -0,0 +1,692 @@ +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.argThat; +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.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.ByteArrayOutputStream; +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.concurrent.atomic.AtomicInteger; +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.SelectedOwnerIntakeAuthorizationBinding; +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.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceClient; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +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 Account composition tests; they do not establish physical or cross-owner proof. */ +class AccountSelectedOwnerIntakeAuthorizationServiceTest { + private static final String TOKEN = "header.payload.signature"; + private static final UUID ACTOR = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TENANT = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID VERSION = UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final UUID OPERATION = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); + + private final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + private final DraftAuthorizationFenceRepository fences = + mock(DraftAuthorizationFenceRepository.class); + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final SelectedOwnerIntakeSourceClient sources = + mock(SelectedOwnerIntakeSourceClient.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountSelectedOwnerIntakeAuthorizationService service = + new AccountSelectedOwnerIntakeAuthorizationService( + actors, fences, repository, sources, transactions, "test"); + + @AfterEach + void clearContextAndTransaction() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void freshAuthorizationReadsOutsideSqlThenRevalidatesAndReadsBackExactOriginalIdentity() { + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var content = content(scope, "original"); + var current = current(ACTOR, TENANT); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, current.source().sources()); + var firstEnvironment = mock(CapturedEnvironmentBoundary.class); + var finalEnvironment = mock(CapturedEnvironmentBoundary.class); + var captures = new AtomicInteger(); + var request = + org.mockito.ArgumentCaptor.forClass(SelectedOwnerIntakeSourceReadEvidence.Request.class); + stubTransactions(); + when(repository.findSourceReadScope( + selected.requestId(), Owner.ENTITY_MANAGEMENT, selected, "test", tokenHash(TOKEN))) + .thenReturn(Optional.empty()); + when(repository.reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class))) + .thenAnswer( + invocation -> { + invocation.getArgument(5).run(); + return scope; + }); + when(repository.recoverSourceRead(scope)) + .thenReturn( + recovery(scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); + when(repository.finalizeSourceRead( + eq(scope), + argThat(candidate -> sameContent(candidate, content)), + eq(current), + any(Runnable.class))) + .thenAnswer( + invocation -> { + invocation.getArgument(3).run(); + return binding; + }); + doAnswer( + invocation -> { + Function action = invocation.getArgument(3); + return action.apply(current); + }) + .when(actors) + .withCurrent( + eq(TOKEN), eq(TENANT), any(CapturedEnvironmentBoundary.class), any(Function.class)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return content; + }) + .when(sources) + .read(request.capture()); + + var result = + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> captures.incrementAndGet() == 1 ? firstEnvironment : finalEnvironment)); + + assertThat(result.canonicalBytes()).isEqualTo(binding.canonicalBytes()); + assertThat(captures.get()).isEqualTo(2); + assertThat(request.getValue().scope()).isEqualTo(scope); + assertThat(result.operationId()).isEqualTo(scope.operationId()); + assertThat(result.fenceId()).isEqualTo(scope.fenceId()); + assertThat(result.intakeRequestId()).isEqualTo(selected.requestId()); + verify(repository).readFinalAuthorization(binding); + verify(fences, org.mockito.Mockito.times(2)) + .requireSelectedOwnerIntakeAdmission(current.source().sources(), selected); + InOrder order = inOrder(actors, repository, sources); + order + .verify(repository) + .findSourceReadScope( + selected.requestId(), Owner.ENTITY_MANAGEMENT, selected, "test", tokenHash(TOKEN)); + order.verify(actors).withCurrent(eq(TOKEN), eq(TENANT), eq(firstEnvironment), any()); + order + .verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class)); + order.verify(repository).recoverSourceRead(scope); + order.verify(sources).read(request.getValue()); + order.verify(actors).withCurrent(eq(TOKEN), eq(TENANT), eq(finalEnvironment), any()); + order + .verify(repository) + .finalizeSourceRead( + eq(scope), + argThat(candidate -> sameContent(candidate, content)), + eq(current), + any(Runnable.class)); + order.verify(repository).readFinalAuthorization(binding); + } + + @Test + void exactFinalRetryUsesOriginalBindingBeforeEnvironmentOrRemoteSourceRead() { + var selected = selected(); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, OPERATION, FENCE); + var content = content(scope, "retained"); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, sources(ACTOR)); + stubTransactions(); + when(repository.findSourceReadScope( + selected.requestId(), Owner.AUTOMATION_SCRIPTING, selected, "test", tokenHash(TOKEN))) + .thenReturn(Optional.of(scope)); + when(repository.recoverSourceRead(scope)) + .thenReturn( + recovery(scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED)); + when(repository.findFinalAuthorization(scope)).thenReturn(Optional.of(binding)); + AtomicInteger environmentReads = new AtomicInteger(); + + var result = + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.AUTOMATION_SCRIPTING, + selected, + () -> { + environmentReads.incrementAndGet(); + throw new AssertionError( + "exact finalized retry must not capture environment"); + })); + + assertThat(result.canonicalBytes()).isEqualTo(binding.canonicalBytes()); + assertThat(result.operationId()).isEqualTo(OPERATION); + assertThat(result.fenceId()).isEqualTo(FENCE); + assertThat(result.intakeRequestId()).isEqualTo(selected.requestId()); + assertThat(environmentReads.get()).isZero(); + verify(repository).readFinalAuthorization(binding); + verifyNoInteractions(actors, fences, sources); + } + + @Test + void substitutedSelectedContentDeniesWithoutReleasingThePreliminaryReservation() { + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var substitutedScope = + scope( + Owner.ENTITY_MANAGEMENT, + selected, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + FENCE); + var current = current(ACTOR, TENANT); + var captures = new AtomicInteger(); + var environment = mock(CapturedEnvironmentBoundary.class); + stubFreshReservation(selected, scope, current); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenReturn(content(substitutedScope, "substituted")); + + assertThatThrownBy( + () -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> { + captures.incrementAndGet(); + return environment; + }))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(captures.get()).isEqualTo(1); + verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class)); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + verify(repository, never()).abortSourceRead(any()); + } + + @Test + void changedCurrentCreatorDuringPostReadCaptureCannotFinalize() { + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var content = content(scope, "source"); + var current = current(ACTOR, TENANT); + var environment = mock(CapturedEnvironmentBoundary.class); + var actorCalls = new AtomicInteger(); + stubFreshReservation(selected, scope, current); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenReturn(content); + doAnswer( + invocation -> { + if (actorCalls.incrementAndGet() == 1) { + Function action = + invocation.getArgument(3); + return action.apply(current); + } + throw Status.PERMISSION_DENIED + .withDescription("creator source changed after remote read") + .asRuntimeException(); + }) + .when(actors) + .withCurrent( + eq(TOKEN), eq(TENANT), any(CapturedEnvironmentBoundary.class), any(Function.class)); + + assertThatThrownBy( + () -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> environment))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(actorCalls.get()).isEqualTo(2); + verify(sources).read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class)); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + verify(repository, never()).abortSourceRead(any()); + } + + @Test + void lostFinalizationAcknowledgementRecoversOnlyTheCommittedSameBinding() { + var selected = selected(); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, OPERATION, FENCE); + var content = content(scope, "exact source"); + var current = current(ACTOR, TENANT); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, current.source().sources()); + var environment = mock(CapturedEnvironmentBoundary.class); + stubFreshReservation(selected, scope, current); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenReturn(content); + when(repository.finalizeSourceRead( + eq(scope), + argThat(candidate -> sameContent(candidate, content)), + eq(current), + any(Runnable.class))) + .thenAnswer( + invocation -> { + invocation.getArgument(3).run(); + throw new IllegalStateException("final commit acknowledgement lost"); + }); + when(repository.findFinalAuthorization(scope)).thenReturn(Optional.of(binding)); + + var result = + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.AUTOMATION_SCRIPTING, + selected, + () -> environment)); + + assertThat(result.canonicalBytes()).isEqualTo(binding.canonicalBytes()); + verify(repository).findFinalAuthorization(scope); + verify(repository).readFinalAuthorization(binding); + // The fresh attempt reserves once before finalization; lost-ACK recovery must not reserve + // again. + verify(repository) + .reserveSourceRead(eq(selected.requestId()), any(), any(), any(), any(), any()); + InOrder order = inOrder(repository); + order + .verify(repository) + .finalizeSourceRead( + eq(scope), argThat(candidate -> sameContent(candidate, content)), eq(current), any()); + order.verify(repository).findFinalAuthorization(scope); + order.verify(repository).readFinalAuthorization(binding); + } + + @Test + void unavailableRemoteResponseLeavesTheOriginalPreliminaryReservationHeld() { + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var current = current(ACTOR, TENANT); + var environment = mock(CapturedEnvironmentBoundary.class); + stubFreshReservation(selected, scope, current); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenThrow( + Status.UNAVAILABLE.withDescription("source read outcome unknown").asRuntimeException()); + + assertThatThrownBy( + () -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> environment))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + + verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class)); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + verify(repository, never()).abortSourceRead(any()); + } + + @Test + void exactGameDesignPeerAndNoEndUserContextAreCheckedBeforeInputOrStorage() { + assertCode( + Status.Code.UNAUTHENTICATED, + () -> service.authorizeWithEnvironmentCapture(null, null, null, null, null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "other", + "game-design-service", + () -> service.authorizeWithEnvironmentCapture(null, null, null, null, null))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", + "account-service", + () -> service.authorizeWithEnvironmentCapture(null, null, null, null, null))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", + "game-design-service", + () -> service.authorizeWithEnvironmentCapture(null, null, null, null, null))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(actors, fences, repository, sources, transactions); + } + + private void stubFreshReservation( + DraftCommitBinding selected, + SelectedOwnerIntakeSourceReadScope scope, + AccountControlUiActorService.Current current) { + stubTransactions(); + when(repository.findSourceReadScope( + selected.requestId(), scope.owner(), selected, "test", tokenHash(TOKEN))) + .thenReturn(Optional.empty()); + when(repository.reserveSourceRead( + eq(selected.requestId()), + eq(scope.owner()), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class))) + .thenAnswer( + invocation -> { + invocation.getArgument(5).run(); + return scope; + }); + when(repository.recoverSourceRead(scope)) + .thenReturn( + recovery(scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); + doAnswer( + invocation -> { + Function action = invocation.getArgument(3); + return action.apply(current); + }) + .when(actors) + .withCurrent( + eq(TOKEN), + eq(selected.target().canonicalTenantId()), + any(CapturedEnvironmentBoundary.class), + any(Function.class)); + } + + private void stubTransactions() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + } + + private static AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recovery( + SelectedOwnerIntakeSourceReadScope scope, + AccountSelectedOwnerIntakeSourceReservationRepository.State state) { + return new AccountSelectedOwnerIntakeSourceReservationRepository.Recovery(scope, state); + } + + private static AccountControlUiActorService.Current current(UUID actorId, UUID tenantId) { + Record row = mock(Record.class); + byte[] sourcePayload = AccountControlUiAuthority.canonical(Map.of("sources", List.of("AQID"))); + byte[] bundle = AccountControlUiAuthority.canonical(Map.of("issuanceFence", 17)); + when(row.get("request_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("operation_id", UUID.class)) + .thenReturn(UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd")); + 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")); + var stored = new AccountControlUiIssuanceRepository.Stored(row); + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(snapshot.sources()).thenReturn(sources(actorId)); + when(snapshot.issuanceFence()).thenReturn(17L); + when(snapshot.outboxCheckpoints()) + .thenReturn(List.of(Map.of("stream", "account", "sequence", 7))); + return new AccountControlUiActorService.Current(stored, snapshot); + } + + private static List sources(UUID actorId) { + return List.of( + evidence(SourceKind.ACCOUNT, actorId.toString(), "account"), + evidence(SourceKind.TENANT, TENANT.toString(), "tenant"), + evidence(SourceKind.MEMBERSHIP, actorId + "/" + TENANT, "membership")); + } + + private static SourceEvidence evidence(SourceKind kind, String scope, String payload) { + return new SourceEvidence( + kind, scope, null, "1", null, null, payload.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected() { + 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"), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("synthetic-fixture-command"))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + TENANT.toString(), + "0"))); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected, UUID operation, UUID fence) { + return new SelectedOwnerIntakeSourceReadScope( + owner, "test", operation, fence, selected.requestId(), ACTOR, selected); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, String marker) { + var selected = scope.selected(); + UUID markerGenesis = UUID.nameUUIDFromBytes(marker.getBytes(StandardCharsets.UTF_8)); + String markerEpoch = Integer.toUnsignedString(marker.hashCode()); + 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", markerGenesis.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, markerGenesis, List.of()); + Map snapshots = + Map.of( + "COMMAND", + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest(marker.getBytes(StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(), + "REALM_POLICY", + new RealmPolicySnapshot(selected, markerEpoch, List.of()).canonicalBytes(), + "ASSET", + new AssetSnapshot(selected, "0", null, markerGenesis, List.of()).canonicalBytes(), + "BRANDING", + new BrandingSourceSnapshot(selected, "0", null, markerGenesis, List.of()) + .canonicalBytes()); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> snapshots.get(family); + }; + DraftAuthorizationFenceBinding.frame(out, family); + DraftAuthorizationFenceBinding.frame(out, snapshot); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static String tokenHash(String value) { + return AccountControlUiIssuanceRepository.hash(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static boolean sameContent( + SelectedOwnerIntakeSourceContent candidate, SelectedOwnerIntakeSourceContent expected) { + return candidate != null + && expected != null + && candidate.scope().equals(expected.scope()) + && candidate.digest().equals(expected.digest()) + && java.util.Arrays.equals(candidate.canonicalBytes(), expected.canonicalBytes()); + } + + 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/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..8325c8a06d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java @@ -0,0 +1,235 @@ +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementResponse; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementGrpcCodec; +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.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Handler boundary tests only; mocks do not prove authenticated mTLS or physical settlement. */ +class AccountSelectedOwnerIntakeSettlementGrpcServiceTest { + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesSameNamespaceGameDesignAndRejectsEndUserBeforeDecode() { + var owner = mock(AccountSelectedOwnerIntakeSettlementService.class); + var service = new AccountSelectedOwnerIntakeSettlementGrpcService(owner, "test"); + var malformed = SelectedOwnerIntakeSettlementRequest.getDefaultInstance(); + + assertThat(invoke(service, malformed).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of( + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-logic-service", + "world-management-service")) { + assertThat(peer("test", workload, () -> invoke(service, malformed)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(service, malformed)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("44", List.of(), java.util.Map.of()); + try { + assertThat(peer("test", "game-design-service", () -> invoke(service, malformed)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + assertThat(peer("test", "game-design-service", () -> invoke(service, malformed)).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void rejectsAmbientSqlUnknownFieldsAndChangedNamespaceBeforeOwnerAccess() { + var owner = mock(AccountSelectedOwnerIntakeSettlementService.class); + var service = new AccountSelectedOwnerIntakeSettlementGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var valid = + SelectedOwnerIntakeSettlementGrpcCodec.toRequest( + SelectedOwnerIntakeSettlementEvidence.Request.create("test", binding)); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(peer("test", "game-design-service", () -> invoke(service, valid)).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(peer("test", "game-design-service", () -> invoke(service, valid)).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThat(peer("test", "game-design-service", () -> invoke(service, unknown)).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + peer( + "test", + "game-design-service", + () -> invoke(service, valid.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void returnsFullStoredReceiptAndExactEchoForNewCorrelationRetry() { + var owner = mock(AccountSelectedOwnerIntakeSettlementService.class); + var service = new AccountSelectedOwnerIntakeSettlementGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var firstRequest = SelectedOwnerIntakeSettlementEvidence.Request.create("test", binding); + var retryRequest = SelectedOwnerIntakeSettlementEvidence.Request.create("test", binding); + var receiptBytes = new byte[8192]; + for (int index = 0; index < receiptBytes.length; index++) { + receiptBytes[index] = (byte) (index * 17); + } + var receipt = receipt(binding, receiptBytes); + when(owner.settle(any())).thenReturn(receipt); + + var firstWire = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(firstRequest); + var first = peer("test", "game-design-service", () -> invoke(service, firstWire)); + assertThat(first.error()).isNull(); + assertThat(first.response().getRequest()).isEqualTo(firstWire); + assertThat(first.response().getSettlementReceipt().toByteArray()).containsExactly(receiptBytes); + assertThat(first.response().getSettlementReceiptDigest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(receiptBytes)); + + var retryWire = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(retryRequest); + var retry = peer("test", "game-design-service", () -> invoke(service, retryWire)); + assertThat(retry.error()).isNull(); + assertThat(retry.response().getRequest()).isEqualTo(retryWire); + assertThat(retry.response().getRequest()).isNotEqualTo(first.response().getRequest()); + assertThat(retry.response().getSettlementReceipt()) + .isEqualTo(first.response().getSettlementReceipt()); + var bindings = ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationBinding.class); + verify(owner, times(2)).settle(bindings.capture()); + assertThat(bindings.getAllValues()) + .allSatisfy( + retained -> + assertThat(retained.canonicalBytes()).containsExactly(binding.canonicalBytes())); + } + + @Test + void sanitizesOwnerFailureAndRejectsReceiptSubstitution() { + var owner = mock(AccountSelectedOwnerIntakeSettlementService.class); + var service = new AccountSelectedOwnerIntakeSettlementGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var wire = + SelectedOwnerIntakeSettlementGrpcCodec.toRequest( + SelectedOwnerIntakeSettlementEvidence.Request.create("test", binding)); + + doThrow( + Status.FAILED_PRECONDITION + .withDescription("private-owner-settlement-evidence") + .asRuntimeException()) + .when(owner) + .settle(any()); + var failure = peer("test", "game-design-service", () -> invoke(service, wire)); + assertThat(failure.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(failure.error().toString()).doesNotContain("private-owner-settlement-evidence"); + + var substituted = + receipt( + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT), + new byte[] {1, 2, 3}); + doReturn(substituted).when(owner).settle(any()); + var mismatch = peer("test", "game-design-service", () -> invoke(service, wire)); + assertThat(mismatch.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(mismatch.error().toString()).doesNotContain("authorization"); + } + + private static AccountSelectedOwnerIntakeSettlementReceipt receipt( + SelectedOwnerIntakeAuthorizationBinding binding, byte[] bytes) { + var receipt = mock(AccountSelectedOwnerIntakeSettlementReceipt.class); + when(receipt.authorizationBinding()).thenReturn(binding); + when(receipt.targetNamespace()).thenReturn(binding.targetNamespace()); + when(receipt.canonicalBytes()).thenReturn(bytes.clone()); + when(receipt.digest()).thenReturn(DraftAuthorizationFenceBinding.digest(bytes)); + return receipt; + } + + private record Result(SelectedOwnerIntakeSettlementResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private static Result invoke( + AccountSelectedOwnerIntakeSettlementGrpcService service, + SelectedOwnerIntakeSettlementRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + service.settleSelectedOwnerIntake( + request, + new StreamObserver<>() { + @Override + public void onNext(SelectedOwnerIntakeSettlementResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable value) { + error.set(value); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java new file mode 100644 index 0000000000..43f0ea7d0d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java @@ -0,0 +1,650 @@ +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.doAnswer; +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 java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +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.Mockito; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked Account transaction and owner-read ordering only; not genuine producer or SQL proof. */ +class AccountSelectedOwnerIntakeSettlementServiceTest { + private static final String NAMESPACE = "test"; + private static final SelectedOwnerIntakeAuthorizationBinding ORIGINAL = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void readsAutomationOutsideSqlThenCommitsAndReadsBackInIndependentTransactions() { + Harness harness = new Harness(NAMESPACE); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = ownerReceipt(ORIGINAL, "winner"); + AtomicReference stored = new AtomicReference<>(); + AtomicInteger settlementReads = new AtomicInteger(); + + doAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + harness.steps.add("validate-original-authorization"); + return null; + }) + .when(harness.repository) + .readFinalAuthorization(ORIGINAL); + when(harness.repository.findSettlement(ORIGINAL)) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + int read = settlementReads.incrementAndGet(); + harness.steps.add(read == 1 ? "prior-settlement-lookup" : "post-commit-readback"); + return read == 1 ? Optional.empty() : Optional.of(stored.get()); + }); + when(harness.automationClient.read(any())) + .thenAnswer( + invocation -> { + assertNoSql(); + harness.steps.add("remote-automation-terminal-read"); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + assertThat(request.binding().canonicalBytes()) + .containsExactly(ORIGINAL.canonicalBytes()); + assertThat(request.readRequestId()) + .isNotIn(ORIGINAL.operationId(), ORIGINAL.fenceId(), ORIGINAL.intakeRequestId()); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); + }); + when(harness.repository.settleCommittedEmpty(any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + harness.steps.add("commit-exact-terminal-settlement"); + AutomationSelectedSourceIntakeTerminalReadEvidence evidence = + invocation.getArgument(0); + assertThat(evidence.request().binding().canonicalBytes()) + .containsExactly(ORIGINAL.canonicalBytes()); + AccountSelectedOwnerIntakeSettlementReceipt receipt = + AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + stored.set(receipt); + return receipt; + }); + + AccountSelectedOwnerIntakeSettlementReceipt actual = + asGameDesign(() -> harness.service.settle(ORIGINAL)); + + assertThat(actual).isSameAs(stored.get()); + assertThat(actual.authorizationBinding().canonicalBytes()) + .containsExactly(ORIGINAL.canonicalBytes()); + assertThat(actual.terminalEvidence().receipt().canonicalBytes()) + .containsExactly(ownerReceipt.canonicalBytes()); + assertThat(harness.steps) + .containsExactly( + "validate-original-authorization", + "prior-settlement-lookup", + "remote-automation-terminal-read", + "commit-exact-terminal-settlement", + "post-commit-readback"); + assertThat(harness.transactions.begins).isEqualTo(3); + assertThat(harness.transactions.commits).isEqualTo(3); + verify(harness.automationClient).read(any()); + verify(harness.repository).settleCommittedEmpty(any()); + assertNoSql(); + } + + @Test + void priorExactSettlementIsReturnedWithoutAutomationContactOrSecondCommit() { + Harness harness = new Harness(NAMESPACE); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, ORIGINAL); + AccountSelectedOwnerIntakeSettlementReceipt prior = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence( + request, ownerReceipt(ORIGINAL, "retained"))); + when(harness.repository.findSettlement(ORIGINAL)).thenReturn(Optional.of(prior)); + + AccountSelectedOwnerIntakeSettlementReceipt recovered = + asGameDesign(() -> harness.service.settle(ORIGINAL)); + + assertThat(recovered).isSameAs(prior); + assertThat(harness.transactions.begins).isEqualTo(1); + assertThat(harness.transactions.commits).isEqualTo(1); + verify(harness.repository).readFinalAuthorization(ORIGINAL); + verify(harness.repository).findSettlement(ORIGINAL); + verifyNoInteractions(harness.automationClient); + verify(harness.repository, never()).settleCommittedEmpty(any()); + } + + @Test + void freshReadCorrelationKeepsAnAlreadyCommittedImmutableOwnerReceiptWinner() { + Harness harness = new Harness(NAMESPACE); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = ownerReceipt(ORIGINAL, "same-owner"); + AtomicInteger settlementReads = new AtomicInteger(); + AtomicReference remoteRequest = + new AtomicReference<>(); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request winnerRequest = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, ORIGINAL); + AccountSelectedOwnerIntakeSettlementReceipt winner = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence(winnerRequest, ownerReceipt)); + when(harness.repository.findSettlement(ORIGINAL)) + .thenAnswer( + ignored -> + settlementReads.incrementAndGet() == 1 ? Optional.empty() : Optional.of(winner)); + when(harness.automationClient.read(any())) + .thenAnswer( + invocation -> { + assertNoSql(); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + remoteRequest.set(request); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); + }); + when(harness.repository.settleCommittedEmpty(any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + AutomationSelectedSourceIntakeTerminalReadEvidence evidence = + invocation.getArgument(0); + assertThat(evidence.request().readRequestId()) + .isEqualTo(remoteRequest.get().readRequestId()); + return winner; + }); + + AccountSelectedOwnerIntakeSettlementReceipt recovered = + asGameDesign(() -> harness.service.settle(ORIGINAL)); + + assertThat(remoteRequest.get().readRequestId()).isNotEqualTo(winnerRequest.readRequestId()); + assertThat(recovered).isSameAs(winner); + assertThat(recovered.terminalEvidence().request().readRequestId()) + .isEqualTo(winnerRequest.readRequestId()); + assertThat(recovered.terminalEvidence().receipt().canonicalBytes()) + .containsExactly(ownerReceipt.canonicalBytes()); + assertThat(harness.transactions.begins).isEqualTo(3); + } + + @Test + void unavailableNullAndChangedOwnerTerminalEvidenceNeverReachesAccountSettlement() { + Harness unavailable = preparedHarness(); + when(unavailable.automationClient.read(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertStatus( + Status.Code.UNAVAILABLE, () -> asGameDesign(() -> unavailable.service.settle(ORIGINAL))); + verify(unavailable.repository, never()).settleCommittedEmpty(any()); + + Harness missing = preparedHarness(); + when(missing.automationClient.read(any())).thenReturn(null); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> missing.service.settle(ORIGINAL))); + verify(missing.repository, never()).settleCommittedEmpty(any()); + + Harness changedEcho = preparedHarness(); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = + ownerReceipt(ORIGINAL, "changed-echo"); + when(changedEcho.automationClient.read(any())) + .thenAnswer( + invocation -> { + var request = + (AutomationSelectedSourceIntakeTerminalReadEvidence.Request) + invocation.getArgument(0); + var changed = + new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + UUID.randomUUID(), + request.binding()); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(changed, ownerReceipt); + }); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> changedEcho.service.settle(ORIGINAL))); + verify(changedEcho.repository, never()).settleCommittedEmpty(any()); + + Harness corruptReceipt = preparedHarness(); + AutomationEmptySelectedSourceIntakeReceipt badReceipt = + ownerReceipt(ORIGINAL, "corrupt-digest"); + when(badReceipt.receiptDigest()).thenReturn("sha256:" + "f".repeat(64)); + when(corruptReceipt.automationClient.read(any())) + .thenAnswer( + invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), badReceipt)); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> corruptReceipt.service.settle(ORIGINAL))); + verify(corruptReceipt.repository, never()).settleCommittedEmpty(any()); + + assertThat(unavailable.transactions.begins).isEqualTo(1); + assertThat(missing.transactions.begins).isEqualTo(1); + assertThat(changedEcho.transactions.begins).isEqualTo(1); + assertThat(corruptReceipt.transactions.begins).isEqualTo(1); + } + + @Test + void failedSettlementCommitDoesNotPretendToHaveReadBackTheUnknownOutcome() { + Harness harness = preparedHarness(); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = + ownerReceipt(ORIGINAL, "commit-failure"); + when(harness.automationClient.read(any())) + .thenAnswer( + invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); + when(harness.repository.settleCommittedEmpty(any())) + .thenAnswer( + invocation -> + AccountSelectedOwnerIntakeSettlementReceipt.create( + (AutomationSelectedSourceIntakeTerminalReadEvidence) + invocation.getArgument(0))); + harness.transactions.failCommitAt = 2; + + assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(ORIGINAL))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic unknown commit"); + + verify(harness.repository).findSettlement(ORIGINAL); + verify(harness.repository, times(1)).findSettlement(ORIGINAL); + verify(harness.repository).settleCommittedEmpty(any()); + assertThat(harness.transactions.begins).isEqualTo(2); + assertThat(harness.transactions.commits).isEqualTo(2); + } + + @Test + void missingOrDifferentLookupOnlyReadbackRemainsUnresolved() { + Harness missing = preparedHarness(); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = ownerReceipt(ORIGINAL, "readback"); + AccountSelectedOwnerIntakeSettlementReceipt committed = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, ORIGINAL), + ownerReceipt)); + when(missing.automationClient.read(any())) + .thenAnswer( + invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); + when(missing.repository.settleCommittedEmpty(any())).thenReturn(committed); + when(missing.repository.findSettlement(ORIGINAL)) + .thenReturn(Optional.empty(), Optional.empty()); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> missing.service.settle(ORIGINAL))); + assertThat(missing.transactions.begins).isEqualTo(3); + + Harness changed = preparedHarness(); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request remoteRequest = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, ORIGINAL); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request otherRequest = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, ORIGINAL); + AccountSelectedOwnerIntakeSettlementReceipt exactCommit = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence(remoteRequest, ownerReceipt)); + AccountSelectedOwnerIntakeSettlementReceipt substitutedReadback = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence(otherRequest, ownerReceipt)); + when(changed.automationClient.read(any())) + .thenAnswer( + invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); + when(changed.repository.settleCommittedEmpty(any())).thenReturn(exactCommit); + when(changed.repository.findSettlement(ORIGINAL)) + .thenReturn(Optional.empty(), Optional.of(substitutedReadback)); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> changed.service.settle(ORIGINAL))); + assertThat(changed.transactions.begins).isEqualTo(3); + } + + @Test + void wrongPeerEndUserAmbientSqlAndNonAutomationScopeAreRejectedBeforeRepositoryAccess() { + Harness harness = new Harness(NAMESPACE); + assertStatus(Status.Code.UNAUTHENTICATED, () -> harness.service.settle(ORIGINAL)); + + asPeer( + peer("test", "entity-management-service"), + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(ORIGINAL))); + asPeer( + peer("other", "game-design-service"), + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(ORIGINAL))); + + SessionContext.setContext("123", List.of(), Map.of()); + asGameDesign( + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(ORIGINAL))); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + asGameDesign( + () -> + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(ORIGINAL))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + asGameDesign( + () -> + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(ORIGINAL))); + TransactionSynchronizationManager.clear(); + + SelectedOwnerIntakeAuthorizationBinding entityBinding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + asGameDesign( + () -> + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(entityBinding))); + + Harness wrongBindingNamespace = new Harness("other-runtime"); + asPeer( + peer("other-runtime", "game-design-service"), + () -> + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> wrongBindingNamespace.service.settle(ORIGINAL))); + + verifyNoInteractions(harness.repository, harness.automationClient); + verifyNoInteractions(wrongBindingNamespace.repository, wrongBindingNamespace.automationClient); + assertThat(harness.transactions.begins).isZero(); + assertThat(wrongBindingNamespace.transactions.begins).isZero(); + } + + @Test + void entityLostLookupOnlyReadbackRecoversExactPriorWithoutAnotherRemoteReadOrWrite() { + // Synthetic receipt decoder and repository stand-ins prove transaction/call ordering only. + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + Harness harness = new Harness(NAMESPACE, true); + var owner = entityReceipt(binding); + var stored = new AtomicReference(); + when(harness.repository.findSettlement(binding)) + .thenAnswer(ignored -> Optional.ofNullable(stored.get())); + when(harness.entityClient.read(any())) + .thenAnswer( + invocation -> { + assertNoSql(); + EntitySelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + return new EntitySelectedSourceIntakeTerminalReadEvidence(request, owner); + }); + when(harness.repository.settleEntityCommittedEmpty(any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + EntitySelectedSourceIntakeTerminalReadEvidence evidence = invocation.getArgument(0); + var receipt = AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + stored.set(receipt); + return receipt; + }); + // The first post-commit lookup is absent even though the immutable writer committed. + AtomicInteger reads = new AtomicInteger(); + when(harness.repository.findSettlement(binding)) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + return reads.incrementAndGet() <= 2 ? Optional.empty() : Optional.of(stored.get()); + }); + try (var decoder = Mockito.mockStatic(EntityEmptySelectedSourceIntakeReceipt.class)) { + decoder + .when(() -> EntityEmptySelectedSourceIntakeReceipt.fromStored(owner.canonicalBytes())) + .thenReturn(owner); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> harness.service.settle(binding))); + var recovered = asGameDesign(() -> harness.service.settle(binding)); + assertThat(recovered.canonicalBytes()).isEqualTo(stored.get().canonicalBytes()); + assertThat(recovered.entityTerminalEvidence().receipt()).isSameAs(owner); + assertThat(harness.transactions.begins).isEqualTo(4); + verify(harness.entityClient, times(1)).read(any()); + verify(harness.repository, times(1)).settleEntityCommittedEmpty(any()); + verifyNoInteractions(harness.automationClient); + } + } + + @Test + void entityCallerNamespaceEndUserAndAmbientSqlGatesPrecedeRepositoryAndRemoteAccess() { + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + Harness harness = new Harness(NAMESPACE, true); + assertStatus(Status.Code.UNAUTHENTICATED, () -> harness.service.settle(binding)); + asPeer( + peer("test", "automation-scripting-service"), + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(binding))); + asPeer( + peer("other", "game-design-service"), + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(binding))); + SessionContext.setContext("123", List.of(), Map.of()); + asGameDesign( + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(binding))); + SessionContext.clear(); + TransactionSynchronizationManager.initSynchronization(); + asGameDesign( + () -> assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(binding))); + TransactionSynchronizationManager.clear(); + var other = new Harness("other", true); + asPeer( + peer("other", "game-design-service"), + () -> assertStatus(Status.Code.FAILED_PRECONDITION, () -> other.service.settle(binding))); + verifyNoInteractions(harness.repository, harness.entityClient, harness.automationClient); + verifyNoInteractions(other.repository, other.entityClient, other.automationClient); + } + + @Test + void unavailableOrChangedEntityReadNeverCreatesAccountSettlement() { + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + Harness missing = new Harness(NAMESPACE, true); + when(missing.repository.findSettlement(binding)).thenReturn(Optional.empty()); + when(missing.entityClient.read(any())).thenReturn(null); + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> missing.service.settle(binding))); + verify(missing.repository, never()).settleEntityCommittedEmpty(any()); + Harness changed = new Harness(NAMESPACE, true); + when(changed.repository.findSettlement(binding)).thenReturn(Optional.empty()); + when(changed.entityClient.read(any())) + .thenAnswer( + invocation -> + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, binding), + entityReceipt(binding))); + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> changed.service.settle(binding))); + verify(changed.repository, never()).settleEntityCommittedEmpty(any()); + Harness unavailable = new Harness(NAMESPACE, true); + when(unavailable.repository.findSettlement(binding)).thenReturn(Optional.empty()); + when(unavailable.entityClient.read(any())).thenThrow(Status.UNAVAILABLE.asRuntimeException()); + assertStatus( + Status.Code.UNAVAILABLE, () -> asGameDesign(() -> unavailable.service.settle(binding))); + verify(unavailable.repository, never()).settleEntityCommittedEmpty(any()); + } + + private static EntityEmptySelectedSourceIntakeReceipt entityReceipt( + SelectedOwnerIntakeAuthorizationBinding binding) { + var receipt = Mockito.mock(EntityEmptySelectedSourceIntakeReceipt.class); + byte[] bytes = "synthetic Entity committed receipt".getBytes(StandardCharsets.UTF_8); + when(receipt.targetNamespace()).thenReturn(binding.targetNamespace()); + when(receipt.operationId()).thenReturn(binding.operationId()); + when(receipt.fenceId()).thenReturn(binding.fenceId()); + when(receipt.intakeRequestId()).thenReturn(binding.intakeRequestId()); + when(receipt.canonicalTenantId()).thenReturn(binding.tenantId()); + when(receipt.canonicalVersionId()).thenReturn(binding.versionId()); + when(receipt.selectedCommitId()).thenReturn(binding.selected().commitId()); + when(receipt.authorizationBindingBytes()).thenReturn(binding.canonicalBytes()); + when(receipt.authorizationBindingDigest()).thenReturn(binding.digest()); + when(receipt.canonicalBytes()).thenReturn(bytes); + when(receipt.receiptDigest()).thenReturn(DraftAuthorizationFenceBinding.digest(bytes)); + when(receipt.outcome()).thenReturn("COMMITTED_EMPTY"); + return receipt; + } + + private static Harness preparedHarness() { + Harness harness = new Harness(NAMESPACE); + when(harness.repository.findSettlement(ORIGINAL)).thenReturn(Optional.empty()); + return harness; + } + + private static AutomationEmptySelectedSourceIntakeReceipt ownerReceipt( + SelectedOwnerIntakeAuthorizationBinding binding, String marker) { + AutomationEmptySelectedSourceIntakeReceipt receipt = + Mockito.mock(AutomationEmptySelectedSourceIntakeReceipt.class); + byte[] bytes = + ("synthetic canonical COMMITTED_EMPTY receipt " + marker).getBytes(StandardCharsets.UTF_8); + when(receipt.targetNamespace()).thenReturn(binding.targetNamespace()); + when(receipt.operationId()).thenReturn(binding.operationId()); + when(receipt.fenceId()).thenReturn(binding.fenceId()); + when(receipt.intakeRequestId()).thenReturn(binding.intakeRequestId()); + when(receipt.canonicalTenantId()).thenReturn(binding.tenantId()); + when(receipt.canonicalVersionId()).thenReturn(binding.versionId()); + when(receipt.selectedCommitId()).thenReturn(binding.selected().commitId()); + when(receipt.authorizationBindingBytes()).thenReturn(binding.canonicalBytes()); + when(receipt.authorizationBindingDigest()).thenReturn(binding.digest()); + when(receipt.canonicalBytes()).thenReturn(bytes); + when(receipt.receiptDigest()).thenReturn(DraftAuthorizationFenceBinding.digest(bytes)); + when(receipt.outcome()).thenReturn("COMMITTED_EMPTY"); + return receipt; + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_READ_COMMITTED); + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertStatus(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asGameDesign(Runnable action) { + asPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T asGameDesign(java.util.function.Supplier action) { + return asPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static void asPeer(GrpcPeerIdentity peer, Runnable action) { + asPeer( + peer, + () -> { + action.run(); + return null; + }); + } + + private static T asPeer(GrpcPeerIdentity peer, java.util.function.Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/" + service; + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static final class Harness { + final AccountSelectedOwnerIntakeSourceReservationRepository repository = + Mockito.mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + final AutomationSelectedSourceIntakeTerminalReadClient automationClient = + Mockito.mock(AutomationSelectedSourceIntakeTerminalReadClient.class); + final EntitySelectedSourceIntakeTerminalReadClient entityClient = + Mockito.mock(EntitySelectedSourceIntakeTerminalReadClient.class); + final OwnerTransactions transactions = new OwnerTransactions(); + final List steps = new ArrayList<>(); + final AccountSelectedOwnerIntakeSettlementService service; + + Harness(String namespace) { + this(namespace, false); + } + + Harness(String namespace, boolean entityEnabled) { + service = + new AccountSelectedOwnerIntakeSettlementService( + repository, + automationClient, + entityEnabled ? entityClient : null, + transactions, + namespace); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int failCommitAt = -1; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertNoSql(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + if (commits == failCommitAt) { + throw new IllegalStateException("synthetic unknown commit"); + } + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} 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 index 5a3901a2ab..194de5fc55 100644 --- 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 @@ -33,6 +33,19 @@ void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction() assertThatThrownBy(() -> repository.readSourceScope(null, null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.readFinalAuthorization(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.readHeldFinalAuthorization(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.findSettlement(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.settleCommittedEmpty(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/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java new file mode 100644 index 0000000000..7f031371b8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java @@ -0,0 +1,222 @@ +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.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +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.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec; +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; + +/** Synthetic handler tests only; they do not establish mTLS or PostgreSQL owner proof. */ +class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest { + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void authenticatesWorldAndRejectsEndUserBeforeParsingOrOwnerAccess() { + var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); + var service = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + var malformed = + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest.newBuilder() + .setTargetNamespace("test") + .setSchemaVersion(-1) + .build(); + + var noPeer = new Collector(); + service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, noPeer); + assertThat(noPeer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + + for (String workload : + List.of( + "account-service", + "game-design-service", + "game-logic-service", + "entity-management-service", + "automation-scripting-service")) { + var denied = new Collector(); + peer("test", workload) + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, denied)); + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var otherNamespace = new Collector(); + peer("other", "world-management-service") + .run( + () -> + service.readHeldSelectedOwnerWorldClosureAuthorization(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", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, endUser)); + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + + var allowedPeerMalformed = new Collector(); + peer("test", "world-management-service") + .run( + () -> + service.readHeldSelectedOwnerWorldClosureAuthorization( + malformed, allowedPeerMalformed)); + assertThat(allowedPeerMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void returnsExactEchoForEntityAndAutomationButRejectsSubstitutedPurposeOrReader() { + var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); + var service = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + + for (Owner domain : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(domain); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + var wire = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest(request); + var result = new Collector(); + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(wire, result)); + + assertThat(result.error).isNull(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getRequest()).isEqualTo(wire); + assertThat(result.response.getHeld()).isTrue(); + + for (var changed : + List.of( + wire.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build(), + wire.toBuilder().setClosureReadPurpose("ENTITY_INTAKE_RETENTION").build())) { + var denied = new Collector(); + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(changed, denied)); + assertThat(denied.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(denied.response).isNull(); + } + } + verify(owner, times(2)).requireHeld(any()); + } + + @Test + void rejectsWrongNamespaceClosedFieldsDigestUnknownFieldsAndMalformedSizes() { + var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); + var service = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var valid = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + "test", binding)); + + var wrongNamespace = new Collector(); + peer("test", "world-management-service") + .run( + () -> + service.readHeldSelectedOwnerWorldClosureAuthorization( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + var changedDigest = + valid.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var malformedBinding = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversizedBinding = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + for (var malformed : List.of(changedDigest, unknown, malformedBinding, oversizedBinding)) { + var result = new Collector(); + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + verifyNoInteractions(owner); + } + + @Test + void mapsOwnerReadFailureToNoHeldResponse() { + var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); + org.mockito.Mockito.doThrow(Status.FAILED_PRECONDITION.asRuntimeException()) + .when(owner) + .requireHeld(any()); + var service = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var wire = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + "test", binding)); + var result = new Collector(); + + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(wire, result)); + + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.response).isNull(); + } + + 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 { + private ReadHeldSelectedOwnerWorldClosureAuthorizationResponse response; + private Status.Code error; + + @Override + public void onNext(ReadHeldSelectedOwnerWorldClosureAuthorizationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..ee268a7717 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.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 net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +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.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic Account read tests; they do not establish PostgreSQL or owner-terminal proof. */ +class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + + @AfterEach + void clearCallerAndTransactionContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactEntityAndAutomationBindingsInIndependentReadCommittedTransactions() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + var service = newService(); + + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(owner); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + asWorldReader(() -> service.requireHeld(request)); + verify(repository).readHeldFinalAuthorization(binding); + } + + var definitions = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions, times(2)).getTransaction(definitions.capture()); + assertThat(definitions.getAllValues()) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + } + + @Test + void independentlyRejectsWrongWorkloadNamespaceAndEndUserBeforeRepositoryAccess() { + var service = newService(); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + + assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + asPeer( + "test", + "entity-management-service", + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + asPeer( + "other", + "world-management-service", + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + asWorldReader( + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void rejectsAmbientSqlBeforeStartingOwnerRead() { + var service = newService(); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + asWorldReader( + () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void distinguishesAbsentOrChangedAuthorizationFromUnavailableStorage() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + var service = newService(); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + + org.mockito.Mockito.doThrow(new IllegalArgumentException("not available")) + .when(repository) + .readHeldFinalAuthorization(binding); + asWorldReader( + () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); + + org.mockito.Mockito.doThrow(new IllegalStateException("storage unavailable")) + .when(repository) + .readHeldFinalAuthorization(binding); + asWorldReader(() -> assertCode(Status.Code.UNAVAILABLE, () -> service.requireHeld(request))); + } + + private AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService newService() { + return new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService( + repository, transactions, "test"); + } + + private static void asWorldReader(Runnable action) { + asPeer("test", "world-management-service", action); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()) + .run(action); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(error -> assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected)); + } +} 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..791d65e020 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) && !"1008".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 preliminary source-read, or 1008 selected-owner predecessor is supported"); } this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java new file mode 100644 index 0000000000..3d042ce3b6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java @@ -0,0 +1,157 @@ +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.AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc; +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; + +/** File-backed mTLS client for Account's distinct selected-owner HELD read. */ +public final class AccountSelectedOwnerIntakeAuthorizationGrpcClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationReadServiceBlockingStub> + implements SelectedOwnerIntakeAuthorizationReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedOwnerIntakeAuthorizationGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountSelectedOwnerIntakeAuthorizationGrpcClient.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 authorization client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account selected-owner authorization stub unavailable"); + initialized = true; + } + + /** Returns only Account's exact echoed HELD result, outside ambient SQL and synchronization. */ + @Override + public SelectedOwnerIntakeAuthorizationReadEvidence read( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account selected-owner authorization read must run outside SQL"); + } + Objects.requireNonNull(request, "authorization-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException( + "Account selected-owner authorization read must use the configured namespace"); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHeldSelectedOwnerIntakeAuthorization( + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest(request)); + try { + return SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid selected-owner HELD authorization evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(SelectedOwnerIntakeAuthorizationReadGrpcCodec.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 AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) + throw new IllegalStateException( + "Account selected-owner authorization 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 authorization 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 authorization read requires file-backed certificate, key, and CA material"); + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) + throw new IllegalArgumentException( + "Account selected-owner authorization 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 authorization read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Account selected-owner authorization read " + + label + + " must be an existing readable file"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java new file mode 100644 index 0000000000..32343ed7a5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java @@ -0,0 +1,319 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +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.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; + +/** Immutable Account record of one exact closed owner {@code COMMITTED_EMPTY} terminal read. */ +public final class AccountSelectedOwnerIntakeSettlementReceipt { + public static final String DOMAIN = "account-selected-owner-intake-settlement/v1"; + public static final int AUTOMATION_MAX_BYTES = + 2 * SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + + 64 * 1024; + public static final int ENTITY_MAX_BYTES = + 2 * SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + + 64 * 1024; + public static final int MAX_BYTES = Math.max(AUTOMATION_MAX_BYTES, ENTITY_MAX_BYTES); + + private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; + private final AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence; + private final EntitySelectedSourceIntakeTerminalReadEvidence entityTerminalEvidence; + private final byte[] canonicalBytes; + private final String digest; + + private AccountSelectedOwnerIntakeSettlementReceipt( + SelectedOwnerIntakeAuthorizationBinding authorizationBinding, + AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence) { + this.authorizationBinding = Objects.requireNonNull(authorizationBinding); + this.terminalEvidence = Objects.requireNonNull(terminalEvidence); + this.entityTerminalEvidence = null; + if (!Arrays.equals( + authorizationBinding.canonicalBytes(), + terminalEvidence.request().binding().canonicalBytes()) + || !Arrays.equals( + authorizationBinding.canonicalBytes(), + terminalEvidence.receipt().authorizationBindingBytes()) + || !authorizationBinding + .digest() + .equals(terminalEvidence.receipt().authorizationBindingDigest()) + || !"COMMITTED_EMPTY".equals(terminalEvidence.receipt().outcome())) { + throw new IllegalArgumentException( + "Automation terminal differs from the complete original Account authorization"); + } + this.canonicalBytes = encode(); + if (canonicalBytes.length > AUTOMATION_MAX_BYTES) { + throw new IllegalArgumentException( + "Account selected-owner settlement exceeds its size limit"); + } + this.digest = DraftAuthorizationFenceBinding.digest(canonicalBytes); + } + + public static AccountSelectedOwnerIntakeSettlementReceipt create( + AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence) { + Objects.requireNonNull(terminalEvidence, "Automation terminal evidence is required"); + return new AccountSelectedOwnerIntakeSettlementReceipt( + terminalEvidence.request().binding(), terminalEvidence); + } + + private AccountSelectedOwnerIntakeSettlementReceipt( + EntitySelectedSourceIntakeTerminalReadEvidence evidence) { + this.entityTerminalEvidence = Objects.requireNonNull(evidence); + this.terminalEvidence = null; + this.authorizationBinding = evidence.request().binding(); + if (!Arrays.equals( + authorizationBinding.canonicalBytes(), evidence.receipt().authorizationBindingBytes()) + || !authorizationBinding.digest().equals(evidence.receipt().authorizationBindingDigest()) + || !"COMMITTED_EMPTY".equals(evidence.receipt().outcome())) { + throw new IllegalArgumentException( + "Entity terminal differs from the complete original Account authorization"); + } + this.canonicalBytes = encode(); + if (canonicalBytes.length > ENTITY_MAX_BYTES) { + throw new IllegalArgumentException("Account Entity settlement exceeds its size limit"); + } + this.digest = DraftAuthorizationFenceBinding.digest(canonicalBytes); + } + + public static AccountSelectedOwnerIntakeSettlementReceipt create( + EntitySelectedSourceIntakeTerminalReadEvidence evidence) { + return new AccountSelectedOwnerIntakeSettlementReceipt(evidence); + } + + public static int maxBytes(Owner owner) { + return switch (owner) { + case AUTOMATION_SCRIPTING -> AUTOMATION_MAX_BYTES; + case ENTITY_MANAGEMENT -> ENTITY_MAX_BYTES; + default -> throw new IllegalArgumentException("Unsupported selected-owner settlement"); + }; + } + + /** Strictly decodes the complete immutable Account binding and its closed owner terminal. */ + public static AccountSelectedOwnerIntakeSettlementReceipt fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { + throw new IllegalArgumentException( + "Stored Account selected-owner settlement size is invalid"); + } + byte[] stored = bytes.clone(); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(DOMAIN); + if (!"1".equals(reader.text())) { + throw new IllegalArgumentException("Unsupported Account selected-owner settlement schema"); + } + byte[] bindingBytes = + bounded(reader.bytes(), SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES); + String bindingDigest = reader.text(); + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(bindingDigest)) { + throw new IllegalArgumentException("Retained Account authorization digest differs"); + } + + int terminalSchemaVersion = parseSchemaVersion(reader.text()); + String namespace = reader.text(); + String readRequestIdText = reader.text(); + DraftAuthorizationFenceBinding.canonicalUuid(readRequestIdText); + UUID readRequestId = UUID.fromString(readRequestIdText); + String intendedReader = reader.text(); + String purpose = reader.text(); + byte[] terminalBindingBytes = + bounded(reader.bytes(), SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES); + String terminalBindingDigest = reader.text(); + var terminalBinding = SelectedOwnerIntakeAuthorizationBinding.fromStored(terminalBindingBytes); + if (!binding.digest().equals(terminalBindingDigest) + || !Arrays.equals(bindingBytes, terminalBindingBytes)) { + throw new IllegalArgumentException("Owner terminal request changed the Account binding"); + } + if (binding.owner() == Owner.ENTITY_MANAGEMENT) { + if (stored.length > ENTITY_MAX_BYTES) { + throw new IllegalArgumentException("Stored Entity settlement exceeds its size limit"); + } + var entityRequest = + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + terminalSchemaVersion, namespace, readRequestId, terminalBinding); + if (!intendedReader.equals(entityRequest.intendedReader()) + || !purpose.equals(entityRequest.terminalReadPurpose())) { + throw new IllegalArgumentException("Entity terminal reader or purpose differs"); + } + byte[] ownerBytes = bounded(reader.bytes(), EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES); + String ownerDigest = reader.text(); + reader.requireEnd(); + var owner = EntityEmptySelectedSourceIntakeReceipt.fromStored(ownerBytes); + if (!owner.receiptDigest().equals(ownerDigest)) { + throw new IllegalArgumentException("Entity terminal receipt digest differs"); + } + var result = create(new EntitySelectedSourceIntakeTerminalReadEvidence(entityRequest, owner)); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical Account Entity settlement"); + } + return result; + } + if (binding.owner() != Owner.AUTOMATION_SCRIPTING || stored.length > AUTOMATION_MAX_BYTES) { + throw new IllegalArgumentException("Stored Automation settlement size or owner differs"); + } + var request = + new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( + terminalSchemaVersion, namespace, readRequestId, terminalBinding); + if (!intendedReader.equals(request.intendedReader()) + || !purpose.equals(request.terminalReadPurpose())) { + throw new IllegalArgumentException("Automation terminal reader or purpose differs"); + } + + byte[] ownerReceiptBytes = + bounded(reader.bytes(), AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES); + String ownerReceiptDigest = reader.text(); + reader.requireEnd(); + var ownerReceipt = AutomationEmptySelectedSourceIntakeReceipt.fromStored(ownerReceiptBytes); + if (!ownerReceipt.receiptDigest().equals(ownerReceiptDigest)) { + throw new IllegalArgumentException("Automation terminal receipt digest differs"); + } + var evidence = new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); + var result = new AccountSelectedOwnerIntakeSettlementReceipt(binding, evidence); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical Account selected-owner settlement"); + } + return result; + } + + public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + return authorizationBinding; + } + + public AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence() { + if (terminalEvidence == null) throw new IllegalStateException("Settlement is not Automation"); + return terminalEvidence; + } + + public EntitySelectedSourceIntakeTerminalReadEvidence entityTerminalEvidence() { + if (entityTerminalEvidence == null) throw new IllegalStateException("Settlement is not Entity"); + return entityTerminalEvidence; + } + + public UUID terminalReadRequestId() { + return entityTerminalEvidence == null + ? terminalEvidence.request().readRequestId() + : entityTerminalEvidence.request().readRequestId(); + } + + public UUID operationId() { + return authorizationBinding.operationId(); + } + + public String targetNamespace() { + return authorizationBinding.targetNamespace(); + } + + public byte[] ownerReceiptBytes() { + return entityTerminalEvidence == null + ? terminalEvidence.receipt().canonicalBytes() + : entityTerminalEvidence.receipt().canonicalBytes(); + } + + public String ownerReceiptDigest() { + return entityTerminalEvidence == null + ? terminalEvidence.receipt().receiptDigest() + : entityTerminalEvidence.receipt().receiptDigest(); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + /** Correlation is retained on first settlement, but is not part of owner receipt identity. */ + public boolean sameImmutableOwnerReceipt( + AutomationSelectedSourceIntakeTerminalReadEvidence requested) { + return terminalEvidence != null + && requested != null + && Arrays.equals( + authorizationBinding.canonicalBytes(), requested.request().binding().canonicalBytes()) + && Arrays.equals( + terminalEvidence.receipt().canonicalBytes(), requested.receipt().canonicalBytes()) + && terminalEvidence.receipt().receiptDigest().equals(requested.receipt().receiptDigest()); + } + + public boolean sameImmutableOwnerReceipt( + EntitySelectedSourceIntakeTerminalReadEvidence requested) { + return entityTerminalEvidence != null + && requested != null + && Arrays.equals( + authorizationBinding.canonicalBytes(), requested.request().binding().canonicalBytes()) + && Arrays.equals(ownerReceiptBytes(), requested.receipt().canonicalBytes()) + && ownerReceiptDigest().equals(requested.receipt().receiptDigest()); + } + + @Override + public boolean equals(Object value) { + return value instanceof AccountSelectedOwnerIntakeSettlementReceipt other + && Arrays.equals(canonicalBytes, other.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private byte[] encode() { + var out = new ByteArrayOutputStream(); + frame(out, DOMAIN); + frame(out, "1"); + frame(out, authorizationBinding.canonicalBytes()); + frame(out, authorizationBinding.digest()); + if (entityTerminalEvidence != null) { + var entityRequest = entityTerminalEvidence.request(); + frame(out, Integer.toString(entityRequest.schemaVersion())); + frame(out, entityRequest.targetNamespace()); + frame(out, entityRequest.readRequestId().toString()); + frame(out, entityRequest.intendedReader()); + frame(out, entityRequest.terminalReadPurpose()); + frame(out, entityRequest.binding().canonicalBytes()); + frame(out, entityRequest.binding().digest()); + frame(out, entityTerminalEvidence.receipt().canonicalBytes()); + frame(out, entityTerminalEvidence.receipt().receiptDigest()); + return out.toByteArray(); + } + var request = terminalEvidence.request(); + frame(out, Integer.toString(request.schemaVersion())); + frame(out, request.targetNamespace()); + frame(out, request.readRequestId().toString()); + frame(out, request.intendedReader()); + frame(out, request.terminalReadPurpose()); + frame(out, request.binding().canonicalBytes()); + frame(out, request.binding().digest()); + frame(out, terminalEvidence.receipt().canonicalBytes()); + frame(out, terminalEvidence.receipt().receiptDigest()); + return out.toByteArray(); + } + + private static int parseSchemaVersion(String value) { + if (!"1".equals(value)) { + throw new IllegalArgumentException("Unsupported Automation terminal-read schema"); + } + return 1; + } + + private static byte[] bounded(byte[] value, int max) { + if (value == null || value.length == 0 || value.length > max) { + throw new IllegalArgumentException("Selected-owner settlement evidence size is invalid"); + } + return value; + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java new file mode 100644 index 0000000000..59c7eedd4f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java @@ -0,0 +1,160 @@ +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.AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc; +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; + +/** File-backed mTLS client for Account's distinct World closure HELD read. */ +public final class AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceBlockingStub> + implements SelectedOwnerIntakeWorldClosureAuthorizationReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.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 World closure authorization client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account World closure authorization stub unavailable"); + initialized = true; + } + + /** Returns only Account's exact echoed HELD result, outside ambient SQL and synchronization. */ + @Override + public SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence readHeld( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account World closure authorization read must run outside SQL"); + } + Objects.requireNonNull(request, "World closure authorization-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException( + "Account World closure authorization read must use the configured namespace"); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHeldSelectedOwnerWorldClosureAuthorization( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest(request)); + try { + return SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid selected-owner World closure HELD evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc.newBlockingStub( + channel) + .withMaxInboundMessageSize( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.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 AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) + throw new IllegalStateException( + "Account World closure authorization client is not initialized and available"); + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException( + "Account World closure authorization 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 World closure authorization read requires file-backed certificate, key, and CA material"); + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) + throw new IllegalArgumentException( + "Account World closure authorization read requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account World closure authorization read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Account World closure authorization read " + + label + + " must be an existing readable file"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java new file mode 100644 index 0000000000..d90e70a218 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; + +/** + * Exact local inputs for composing an approved fresh empty Entity or Automation intake. + * + *

This value binds the supplied original Account owner authorization to the exact World + * inventory response and the matching typed authored declaration. It is integrity/input binding + * only: its inputs do not authenticate either producer, establish current or through-commit Account + * protection, census the complete owner database, or produce an owner receipt. + */ +public final class SelectedOwnerEmptySourceInputs { + private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; + private final SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence; + private final SelectedOwnerIntakeSourceContent sourceContent; + private final TemplateConfigOwnerSourceInventoryDeclaration ownerSourceInventoryDeclaration; + + public SelectedOwnerEmptySourceInputs( + SelectedOwnerIntakeAuthorizationBinding authorizationBinding, + SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence) { + this.authorizationBinding = + Objects.requireNonNull(authorizationBinding, "authorizationBinding"); + this.worldInventoryReadEvidence = + Objects.requireNonNull(worldInventoryReadEvidence, "worldInventoryReadEvidence"); + this.sourceContent = authorizationBinding.content(); + requireExactWorldBinding(authorizationBinding, worldInventoryReadEvidence); + requireSupportedWorldClosure(authorizationBinding.owner(), worldInventoryReadEvidence); + this.ownerSourceInventoryDeclaration = + requireOwnerDeclaration(authorizationBinding.owner(), sourceContent.templateConfigSource()); + requireNoOwnerTemplateReferences( + authorizationBinding.owner(), sourceContent.templateConfigSource()); + } + + /** Returns the exact supplied original Account owner authorization binding. */ + public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + return authorizationBinding; + } + + /** Returns the exact supplied World response, including its original read request echo. */ + public SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence() { + return worldInventoryReadEvidence; + } + + /** Returns the immutable source content carried by the original authorization binding. */ + public SelectedOwnerIntakeSourceContent sourceContent() { + return sourceContent; + } + + /** Returns the original typed owner declaration and its unchanged source revision provenance. */ + public TemplateConfigOwnerSourceInventoryDeclaration ownerSourceInventoryDeclaration() { + return ownerSourceInventoryDeclaration; + } + + private static void requireExactWorldBinding( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerWorldInventoryReadEvidence worldEvidence) { + var request = worldEvidence.request(); + var echoedAuthorization = request.authorizationBinding(); + if (!Arrays.equals(authorization.canonicalBytes(), echoedAuthorization.canonicalBytes()) + || !authorization.digest().equals(echoedAuthorization.digest())) { + throw new IllegalArgumentException( + "World inventory read does not echo the exact original owner authorization"); + } + + var scope = authorization.content().scope(); + var freeze = request.freezeEvidence().request(); + var selected = authorization.selected(); + var echoedSelected = freeze.accountBinding().input().selection().selectedCommit(); + var publicInventory = worldEvidence.inventory().publicEvidence(); + var publicOwner = publicInventory.ownerScope(); + if (!authorization.targetNamespace().equals(request.targetNamespace()) + || !scope.targetNamespace().equals(request.targetNamespace()) + || !request.targetNamespace().equals(freeze.targetNamespace()) + || !request.targetNamespace().equals(publicOwner.targetNamespace()) + || !selected.target().canonicalTenantId().equals(freeze.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(freeze.canonicalVersionId()) + || !selected.target().canonicalTenantId().equals(publicOwner.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(publicOwner.canonicalVersionId()) + || !Arrays.equals(selected.canonicalBytes(), echoedSelected.canonicalBytes()) + || !selected.digest().equals(echoedSelected.digest()) + || !Arrays.equals( + selected.canonicalBytes(), request.authorizationBinding().selected().canonicalBytes()) + || !selected.digest().equals(request.authorizationBinding().selected().digest()) + || !selected + .commitId() + .toString() + .equals(publicInventory.selectedApplication().appliedCommitId()) + || !selected.digest().equals(publicInventory.selectedApplication().bindingDigest())) { + throw new IllegalArgumentException( + "World inventory read differs from the exact selected owner scope or commit"); + } + } + + private static void requireSupportedWorldClosure( + Owner owner, SelectedOwnerWorldInventoryReadEvidence worldEvidence) { + WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence inventory = + worldEvidence.inventory().publicEvidence(); + var sourceModel = inventory.sourceModel(); + if (!WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA.equals( + inventory.schema()) + || inventory.schemaVersion() + != WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION + || !WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL.equals( + sourceModel.modelId()) + || sourceModel.graphSchemaVersion() + != WorldSelectedPublicationArtifactInventoryEvidence + .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + || sourceModel.inboundSourceClosure() == null) { + throw new IllegalArgumentException( + "Selected World inventory requires the supported complete v2 inbound closure"); + } + if (owner == Owner.ENTITY_MANAGEMENT && sourceModel.spawnBindingCount() != 0) { + throw new IllegalArgumentException( + "Entity empty-source intake cannot bind a nonempty World spawn inventory"); + } + } + + private static TemplateConfigOwnerSourceInventoryDeclaration requireOwnerDeclaration( + Owner owner, TemplateConfigSourceSnapshot snapshot) { + if (snapshot.ownerSourceInventoryDeclarations().isEmpty()) { + throw new IllegalArgumentException( + "Selected template config requires its original v2 owner inventory declaration"); + } + return snapshot.ownerSourceInventoryDeclarations().stream() + .filter(declaration -> declaration.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new IllegalArgumentException( + "Selected template config has no declaration for the authorized owner")); + } + + private static void requireNoOwnerTemplateReferences( + Owner owner, TemplateConfigSourceSnapshot snapshot) { + for (var entry : snapshot.entries()) { + boolean conflict = + switch (owner) { + case ENTITY_MANAGEMENT -> entry.config().hasEntityReferences(); + case AUTOMATION_SCRIPTING -> entry.config().hasAutomationReferences(); + default -> throw new IllegalArgumentException("Unsupported selected source owner"); + }; + if (conflict) { + throw new IllegalArgumentException( + "Selected template config contains a reference owned by the intake recipient"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java new file mode 100644 index 0000000000..a70bc98e1c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java @@ -0,0 +1,257 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Comparator; +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.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; + +/** + * Integrity input for Account's distinct selected-owner source-retention authorization. Decoding + * proves only the canonical relationship among the supplied content and source evidence; it does + * not authenticate Account, establish HELD/current authority, prove a complete source census, or + * create an owner receipt. + */ +public record SelectedOwnerIntakeAuthorizationBinding( + SelectedOwnerIntakeSourceContent content, List sources) { + public static final int MAX_BYTES = 16 * 1024 * 1024; + + public SelectedOwnerIntakeAuthorizationBinding { + Objects.requireNonNull(content, "content"); + SelectedOwnerIntakeSourceReadScope scope = content.scope(); + schemaFor(scope.owner()); + sources = + List.copyOf(Objects.requireNonNull(sources, "sources")).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Complete distinct Account sources required"); + } + for (SourceEvidence source : sources) requireActorTenantScope(source, scope); + canonicalBytes( + content, + sources, + intendedReader(scope.owner(), scope.targetNamespace()), + purposeFor(scope.owner())); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public Owner owner() { + return content.scope().owner(); + } + + public String targetNamespace() { + return content.scope().targetNamespace(); + } + + public UUID operationId() { + return content.scope().operationId(); + } + + public UUID fenceId() { + return content.scope().fenceId(); + } + + public UUID intakeRequestId() { + return content.scope().intakeRequestId(); + } + + public UUID actorAccountId() { + return content.scope().actorAccountId(); + } + + public DraftCommitBinding selected() { + return content.scope().selected(); + } + + public UUID tenantId() { + return selected().target().canonicalTenantId(); + } + + public UUID versionId() { + return selected().target().canonicalVersionId(); + } + + public String schema() { + return schemaFor(owner()); + } + + public String purpose() { + return purposeFor(owner()); + } + + public String intendedReader() { + return intendedReader(owner(), targetNamespace()); + } + + public byte[] canonicalBytes() { + return canonicalBytes(content, sources, intendedReader(), purpose()); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + /** + * Decodes a self-contained integrity envelope by revalidating its embedded exact source scope, + * complete six-family content and all Account source-evidence frames. + */ + public static SelectedOwnerIntakeAuthorizationBinding fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Selected owner intake authorization size is invalid"); + } + byte[] stored = bytes.clone(); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + String schema = reader.text(); + Owner owner = ownerForSchema(schema); + byte[] contentBytes = reader.bytes(); + String contentDigest = reader.text(); + if (!DraftAuthorizationFenceBinding.digest(contentBytes).equals(contentDigest)) { + throw new IllegalArgumentException("Selected owner intake content digest differs"); + } + + SelectedOwnerIntakeSourceReadScope embeddedScope = embeddedScope(contentBytes); + if (embeddedScope.owner() != owner) { + throw new IllegalArgumentException("Selected owner intake schema differs from content owner"); + } + SelectedOwnerIntakeSourceContent content = + SelectedOwnerIntakeSourceContent.fromStored(contentBytes, embeddedScope, contentDigest); + String recipientReader = reader.text(); + String purpose = reader.text(); + String expectedReader = intendedReader(owner, embeddedScope.targetNamespace()); + String expectedPurpose = purposeFor(owner); + if (!expectedReader.equals(recipientReader) || !expectedPurpose.equals(purpose)) { + throw new IllegalArgumentException("Selected owner intake recipient or purpose differs"); + } + + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + int count = Integer.parseInt(countText); + if (count > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete selected owner intake source vector"); + } + var sources = new java.util.ArrayList(); + for (int i = 0; i < count; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + reader.requireEnd(); + + var result = new SelectedOwnerIntakeAuthorizationBinding(content, sources); + if (!schema.equals(result.schema()) + || !recipientReader.equals(result.intendedReader()) + || !purpose.equals(result.purpose()) + || !Arrays.equals(stored, result.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical selected owner intake authorization"); + } + return result; + } + + private static SelectedOwnerIntakeSourceReadScope embeddedScope(byte[] contentBytes) { + if (contentBytes == null + || contentBytes.length == 0 + || contentBytes.length > SelectedOwnerIntakeSourceContent.MAX_BYTES) { + throw new IllegalArgumentException("Selected owner intake content size is invalid"); + } + var contentReader = new DraftAuthorizationFenceBinding.FrameReader(contentBytes); + contentReader.expect(SelectedOwnerIntakeSourceContent.DOMAIN); + byte[] scopeBytes = contentReader.bytes(); + String scopeDigest = contentReader.text(); + if (!DraftAuthorizationFenceBinding.digest(scopeBytes).equals(scopeDigest)) { + throw new IllegalArgumentException("Selected owner intake scope digest differs"); + } + return SelectedOwnerIntakeSourceReadScope.fromStored(scopeBytes); + } + + private static byte[] canonicalBytes( + SelectedOwnerIntakeSourceContent content, + List sources, + String intendedReader, + String purpose) { + var out = new ByteArrayOutputStream(); + frameBounded(out, schemaFor(content.scope().owner())); + byte[] contentBytes = content.canonicalBytes(); + frameBounded(out, contentBytes); + frameBounded(out, content.digest()); + frameBounded(out, intendedReader); + frameBounded(out, purpose); + frameBounded(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + frameBounded(out, source.canonicalBytes()); + } + return out.toByteArray(); + } + + private static void frameBounded(ByteArrayOutputStream out, String value) { + byte[] utf8 = value.getBytes(StandardCharsets.UTF_8); + requireFrameCapacity(out, utf8.length); + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frameBounded(ByteArrayOutputStream out, byte[] value) { + requireFrameCapacity(out, value.length); + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void requireFrameCapacity(ByteArrayOutputStream out, int frameBytes) { + if ((long) out.size() + Integer.BYTES + frameBytes > MAX_BYTES) { + throw new IllegalArgumentException("Selected owner intake authorization exceeds 16 MiB"); + } + } + + private static void requireActorTenantScope( + SourceEvidence source, SelectedOwnerIntakeSourceReadScope scope) { + String expected = + switch (source.kind()) { + case ACCOUNT, GLOBAL_ROLES -> scope.actorAccountId().toString(); + case TENANT -> scope.selected().target().canonicalTenantId().toString(); + case MEMBERSHIP -> + scope.actorAccountId() + "/" + scope.selected().target().canonicalTenantId(); + default -> null; + }; + if (expected != null && !expected.equals(source.scopeId())) { + throw new IllegalArgumentException("Intake source differs from actor/tenant"); + } + } + + private static String schemaFor(Owner owner) { + if (owner == Owner.ENTITY_MANAGEMENT) return "account-entity-intake-authorization/v1"; + if (owner == Owner.AUTOMATION_SCRIPTING) return "account-automation-intake-authorization/v1"; + throw new IllegalArgumentException("Unsupported selected source intake owner"); + } + + private static Owner ownerForSchema(String schema) { + if ("account-entity-intake-authorization/v1".equals(schema)) return Owner.ENTITY_MANAGEMENT; + if ("account-automation-intake-authorization/v1".equals(schema)) + return Owner.AUTOMATION_SCRIPTING; + throw new IllegalArgumentException("Unsupported selected owner intake authorization schema"); + } + + private static String purposeFor(Owner owner) { + schemaFor(owner); + return owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_RETENTION" + : "AUTOMATION_INTAKE_RETENTION"; + } + + private static String intendedReader(Owner owner, String namespace) { + String workload = + switch (owner) { + case ENTITY_MANAGEMENT -> "entity-management-service"; + case AUTOMATION_SCRIPTING -> "automation-scripting-service"; + default -> throw new IllegalArgumentException("Unsupported selected source intake owner"); + }; + return "spiffe://firemud/ns/" + namespace + "/sa/" + workload; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentials.java new file mode 100644 index 0000000000..119ec8f098 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentials.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.util.Iterator; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; + +/** Method-scoped protected metadata for the unchanged selected-owner creator credential. */ +public final class SelectedOwnerIntakeAuthorizationProducerCredentials { + public static final int MAX_CREDENTIAL_CHARS = 16384; + public static final Context.Key CONTEXT_KEY = + Context.key("selected-owner-intake-authorization-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "x-firemud-selected-owner-intake-creator", + new Metadata.AsciiMarshaller<>() { + @Override + public String toAsciiString(Credential value) { + return value.value(); + } + + // Credential validation is deferred until after the receiving peer is authenticated. + @Override + public Credential parseAsciiString(String serialized) { + return new Credential(serialized); + } + }); + + private SelectedOwnerIntakeAuthorizationProducerCredentials() {} + + public static final class Credential { + private final String credential; + + private Credential(String credential) { + this.credential = credential; + } + + public static Credential of(String value) { + if (!validCredential(value)) throw invalid(); + return new Credential(value); + } + + public String value() { + if (!validCredential(credential)) throw invalid(); + return credential; + } + + @Override + public String toString() { + return "SelectedOwnerIntakeAuthorizationCredential[redacted]"; + } + } + + /** Call only after authenticating the exact same-namespace Game Design workload. */ + public static Credential readAuthenticated(Metadata headers, String methodName) { + if (!allowedMethod(methodName) || headers == null) throw invalid(); + Iterable values = headers.getAll(HEADER); + if (values == null) throw invalid(); + Iterator iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forAuthorize(String value) { + Credential credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || info.getMethodDescriptor() == null + || !AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .getAuthorizeSelectedOwnerIntakeMethod() + .getFullMethodName() + .equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected selected-owner intake producer transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "SelectedOwnerIntakeAuthorizationCallCredentials[redacted]"; + } + }; + } + + public static boolean allowedMethod(String methodName) { + return AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .getAuthorizeSelectedOwnerIntakeMethod() + .getFullMethodName() + .equals(methodName); + } + + private static boolean validCredential(String credential) { + return credential != null + && !credential.isEmpty() + && credential.length() <= MAX_CREDENTIAL_CHARS + && credential.chars().allMatch(value -> value > 32 && value < 127); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-owner intake creator metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerEvidence.java new file mode 100644 index 0000000000..6e15f0de5f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerEvidence.java @@ -0,0 +1,220 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +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; + +/** Immutable evidence for the distinct selected-owner Account authorization producer transport. */ +public final class SelectedOwnerIntakeAuthorizationProducerEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_SELECTION_BYTES = SelectedOwnerIntakeSourceReadScope.MAX_BYTES; + + private SelectedOwnerIntakeAuthorizationProducerEvidence() {} + + /** Closed producer request. The selected Draft bytes are retained and returned exactly. */ + public static final class Request { + private final int schemaVersion; + private final String targetNamespace; + private final UUID transportRequestId; + private final UUID intakeRequestId; + private final Owner owner; + private final byte[] selectedDraftBinding; + + public Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + UUID intakeRequestId, + Owner owner, + byte[] selectedDraftBinding) { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !isSupportedOwner(owner)) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + if (transportRequestId.equals(intakeRequestId)) throw invalid(); + if (selectedDraftBinding == null + || selectedDraftBinding.length == 0 + || selectedDraftBinding.length > MAX_SELECTION_BYTES) { + throw invalid(); + } + this.schemaVersion = schemaVersion; + this.targetNamespace = targetNamespace; + this.transportRequestId = transportRequestId; + this.intakeRequestId = intakeRequestId; + this.owner = owner; + this.selectedDraftBinding = selectedDraftBinding.clone(); + DraftCommitBinding selected = decodeSelection(this.selectedDraftBinding); + if (transportRequestId.equals(selected.requestId()) + || transportRequestId.equals(selected.commitId())) { + throw invalid(); + } + } + + public static Request create( + String namespace, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { + Objects.requireNonNull(selected, "selected Draft binding is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (correlation.equals(intakeRequestId) + || correlation.equals(selected.requestId()) + || correlation.equals(selected.commitId())); + return new Request( + SCHEMA_VERSION, + namespace, + correlation, + intakeRequestId, + owner, + selected.canonicalBytes()); + } + + public int schemaVersion() { + return schemaVersion; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID transportRequestId() { + return transportRequestId; + } + + public UUID intakeRequestId() { + return intakeRequestId; + } + + public Owner owner() { + return owner; + } + + public byte[] selectedDraftBinding() { + return selectedDraftBinding.clone(); + } + + public DraftCommitBinding selected() { + return decodeSelection(selectedDraftBinding); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof Request request)) return false; + return schemaVersion == request.schemaVersion + && targetNamespace.equals(request.targetNamespace) + && transportRequestId.equals(request.transportRequestId) + && intakeRequestId.equals(request.intakeRequestId) + && owner == request.owner + && Arrays.equals(selectedDraftBinding, request.selectedDraftBinding); + } + + @Override + public int hashCode() { + int result = + Objects.hash(schemaVersion, targetNamespace, transportRequestId, intakeRequestId, owner); + return 31 * result + Arrays.hashCode(selectedDraftBinding); + } + + @Override + public String toString() { + return "SelectedOwnerIntakeAuthorizationProducer.Request[redacted]"; + } + } + + /** Exact immutable authorization returned by Account, including its canonical digest. */ + public static final class Result { + private final Request request; + private final SelectedOwnerIntakeAuthorizationBinding binding; + private final String digest; + + public Result(Request request, SelectedOwnerIntakeAuthorizationBinding binding, String digest) { + this.request = Objects.requireNonNull(request, "producer request is required"); + this.binding = Objects.requireNonNull(binding, "finalized authorization binding is required"); + this.digest = Objects.requireNonNull(digest, "authorization digest is required"); + requireBindingMatches(request, binding); + if (!binding.digest().equals(digest)) throw invalid(); + } + + public Request request() { + return request; + } + + public SelectedOwnerIntakeAuthorizationBinding binding() { + return binding; + } + + public String digest() { + return digest; + } + + public byte[] canonicalBindingBytes() { + return binding.canonicalBytes(); + } + + @Override + public String toString() { + return "SelectedOwnerIntakeAuthorizationProducer.Result[redacted]"; + } + } + + static void requireBindingMatches( + Request request, SelectedOwnerIntakeAuthorizationBinding binding) { + if (binding.owner() != request.owner() + || !binding.targetNamespace().equals(request.targetNamespace()) + || !binding.intakeRequestId().equals(request.intakeRequestId()) + || !Arrays.equals(binding.selected().canonicalBytes(), request.selectedDraftBinding()) + || !binding + .intendedReader() + .equals(intendedReader(request.owner(), request.targetNamespace())) + || !binding.purpose().equals(purpose(request.owner()))) { + throw invalid(); + } + } + + static boolean isSupportedOwner(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT || owner == Owner.AUTOMATION_SCRIPTING; + } + + static String intendedReader(Owner owner, String namespace) { + String workload = + switch (owner) { + case ENTITY_MANAGEMENT -> "entity-management-service"; + case AUTOMATION_SCRIPTING -> "automation-scripting-service"; + default -> throw invalid(); + }; + return "spiffe://firemud/ns/" + namespace + "/sa/" + workload; + } + + static String purpose(Owner owner) { + return switch (owner) { + case ENTITY_MANAGEMENT -> "ENTITY_INTAKE_RETENTION"; + case AUTOMATION_SCRIPTING -> "AUTOMATION_INTAKE_RETENTION"; + default -> throw invalid(); + }; + } + + private static DraftCommitBinding decodeSelection(byte[] bytes) { + try { + String json = new String(bytes, StandardCharsets.UTF_8); + DraftCommitBinding selected = + DraftCommitBinding.fromStored(json, DraftAuthorizationFenceBinding.digest(bytes)); + if (!Arrays.equals(bytes, selected.canonicalBytes())) throw invalid(); + return selected; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Invalid selected-owner intake authorization producer evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodec.java new file mode 100644 index 0000000000..bc562791ed --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodec.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerOwner; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence.Request; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence.Result; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; + +/** Closed request and exact authorization response mapping for the selected-owner producer. */ +public final class SelectedOwnerIntakeAuthorizationProducerProtoCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + public static final int MAX_AUTHORIZATION_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES; + + private SelectedOwnerIntakeAuthorizationProducerProtoCodec() {} + + public static SelectedOwnerIntakeAuthorizationProducerRequest toRequest(Request request) { + Objects.requireNonNull(request, "producer request is required"); + byte[] selection = request.selectedDraftBinding(); + if (selection.length == 0 + || selection.length + > SelectedOwnerIntakeAuthorizationProducerEvidence.MAX_SELECTION_BYTES) { + throw invalid("Selected Draft binding exceeds the 4 MiB scope limit"); + } + var wire = + SelectedOwnerIntakeAuthorizationProducerRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setOwner(toWire(request.owner())) + .setSelectedDraftBinding(ByteString.copyFrom(selection)) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static Request fromRequest(SelectedOwnerIntakeAuthorizationProducerRequest wire) { + requireKnownAndWithinBudget(wire, "request"); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getTransportRequestId()); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getIntakeRequestId()); + byte[] selection = wire.getSelectedDraftBinding().toByteArray(); + if (selection.length == 0 + || selection.length + > SelectedOwnerIntakeAuthorizationProducerEvidence.MAX_SELECTION_BYTES) { + throw invalid("Selected Draft binding size is invalid"); + } + Request request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getTransportRequestId()), + UUID.fromString(wire.getIntakeRequestId()), + fromWire(wire.getOwner()), + selection); + if (!Arrays.equals(selection, request.selectedDraftBinding()) + || !toRequest(request).equals(wire)) { + throw invalid("Selected Draft binding or request is noncanonical"); + } + return request; + } + + public static SelectedOwnerIntakeAuthorizationProducerResponse toResponse(Result result) { + Objects.requireNonNull(result, "Account authorization result is required"); + byte[] binding = result.canonicalBindingBytes(); + if (binding.length == 0 || binding.length > MAX_AUTHORIZATION_BYTES) { + throw invalid("Complete authorization binding exceeds its 16 MiB limit"); + } + var response = + SelectedOwnerIntakeAuthorizationProducerResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setIntakeAuthorizationBinding(ByteString.copyFrom(binding)) + .setIntakeAuthorizationDigest(result.digest()) + .build(); + requireWithinBudget(response.getSerializedSize()); + return response; + } + + public static Result fromResponse( + Request request, SelectedOwnerIntakeAuthorizationProducerResponse response) { + Objects.requireNonNull(request, "producer request is required"); + requireKnownAndWithinBudget(response, "response"); + if (!response.hasRequest()) throw invalid("Complete request echo is required"); + requireKnownAndWithinBudget(response.getRequest(), "echoed request"); + if (!toRequest(request).equals(response.getRequest())) { + throw invalid("Account changed the selected-owner producer request"); + } + byte[] bindingBytes = response.getIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 || bindingBytes.length > MAX_AUTHORIZATION_BYTES) { + throw invalid("Complete authorization binding size is invalid"); + } + SelectedOwnerIntakeAuthorizationBinding binding; + try { + binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + } catch (RuntimeException malformed) { + throw invalid("Complete authorization binding is malformed or noncanonical"); + } + if (!Arrays.equals(bindingBytes, binding.canonicalBytes()) + || !binding.digest().equals(response.getIntakeAuthorizationDigest())) { + throw invalid("Complete authorization binding or SHA-256 digest differs"); + } + return new Result(request, binding, response.getIntakeAuthorizationDigest()); + } + + private static SelectedOwnerIntakeAuthorizationProducerOwner toWire(Owner owner) { + return switch (owner) { + case ENTITY_MANAGEMENT -> + SelectedOwnerIntakeAuthorizationProducerOwner + .SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_ENTITY_MANAGEMENT; + case AUTOMATION_SCRIPTING -> + SelectedOwnerIntakeAuthorizationProducerOwner + .SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_AUTOMATION_SCRIPTING; + default -> throw invalid("Unsupported selected-owner intake authorization owner"); + }; + } + + private static Owner fromWire(SelectedOwnerIntakeAuthorizationProducerOwner owner) { + return switch (owner) { + case SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_ENTITY_MANAGEMENT -> + Owner.ENTITY_MANAGEMENT; + case SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_AUTOMATION_SCRIPTING -> + Owner.AUTOMATION_SCRIPTING; + default -> throw invalid("Unsupported or unspecified selected-owner intake owner"); + }; + } + + private static void requireKnownAndWithinBudget(Message wire, String label) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) { + throw invalid("Missing or oversized selected-owner producer " + label); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown selected-owner producer " + label + " fields"); + } + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) { + throw invalid("Selected-owner producer message exceeds its 24 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/SelectedOwnerIntakeAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadClient.java new file mode 100644 index 0000000000..54ddf57b05 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.account.sourceintake; + +/** Account's authenticated held-retention read, separate from original Draft authorization. */ +public interface SelectedOwnerIntakeAuthorizationReadClient { + SelectedOwnerIntakeAuthorizationReadEvidence read( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidence.java new file mode 100644 index 0000000000..9c8f75066e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidence.java @@ -0,0 +1,69 @@ +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.grpc.GrpcPeerIdentity; + +/** Exact lookup identity for reading a finalized selected-owner Account authorization. */ +public record SelectedOwnerIntakeAuthorizationReadEvidence(Request request) { + public static final int SCHEMA_VERSION = 1; + + public SelectedOwnerIntakeAuthorizationReadEvidence { + Objects.requireNonNull(request, "authorization-read request is required"); + } + + /** The binding is lookup evidence only; Account authentication establishes the HELD result. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || binding == null + || !targetNamespace.equals(binding.targetNamespace())) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) { + throw invalid(); + } + // These accessors reject any owner outside the closed Entity and Automation domains. + Objects.requireNonNull(binding.intendedReader()); + Objects.requireNonNull(binding.purpose()); + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + Objects.requireNonNull(binding, "finalized selected-owner authorization is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (sameIdentity(correlation, binding)); + return new Request(SCHEMA_VERSION, namespace, correlation, binding); + } + + public String intendedReader() { + return binding.intendedReader(); + } + + public String retentionPurpose() { + return binding.purpose(); + } + + private static boolean sameIdentity( + UUID candidate, SelectedOwnerIntakeAuthorizationBinding binding) { + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-owner authorization-read evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodec.java new file mode 100644 index 0000000000..efe3a4bc91 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodec.java @@ -0,0 +1,104 @@ +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.ReadHeldSelectedOwnerIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed HELD-read wire mapping with full request-echo validation. */ +public final class SelectedOwnerIntakeAuthorizationReadGrpcCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + private SelectedOwnerIntakeAuthorizationReadGrpcCodec() {} + + public static ReadHeldSelectedOwnerIntakeAuthorizationRequest toRequest( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "authorization-read request is required"); + byte[] bindingBytes = request.binding().canonicalBytes(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Selected-owner authorization exceeds its 16 MiB limit"); + } + var wire = + ReadHeldSelectedOwnerIntakeAuthorizationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setRetentionPurpose(request.retentionPurpose()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static SelectedOwnerIntakeAuthorizationReadEvidence.Request fromRequest( + ReadHeldSelectedOwnerIntakeAuthorizationRequest wire) { + requireKnownAndWithinBudget(wire); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getReadRequestId()); + byte[] bindingBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Selected-owner authorization size is invalid"); + } + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(wire.getIntakeAuthorizationDigest())) + throw invalid("Selected-owner authorization digest differs"); + var request = + new SelectedOwnerIntakeAuthorizationReadEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getReadRequestId()), + binding); + if (!request.intendedReader().equals(wire.getIntendedReader()) + || !request.retentionPurpose().equals(wire.getRetentionPurpose()) + || !toRequest(request).equals(wire)) { + throw invalid("Selected-owner authorization reader, purpose, or request differs"); + } + return request; + } + + public static ReadHeldSelectedOwnerIntakeAuthorizationResponse toHeldResponse( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + var response = + ReadHeldSelectedOwnerIntakeAuthorizationResponse.newBuilder() + .setRequest(toRequest(request)) + .setHeld(true) + .build(); + requireWithinBudget(response.getSerializedSize()); + return response; + } + + public static SelectedOwnerIntakeAuthorizationReadEvidence fromResponse( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request, + ReadHeldSelectedOwnerIntakeAuthorizationResponse response) { + Objects.requireNonNull(request, "authorization-read request is required"); + requireKnownAndWithinBudget(response); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getHeld()) { + throw invalid("Exact held selected-owner authorization response required"); + } + return new SelectedOwnerIntakeAuthorizationReadEvidence(request); + } + + private static void requireKnownAndWithinBudget(Message wire) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Missing or oversized selected-owner authorization-read message"); + if (!wire.getUnknownFields().asMap().isEmpty()) + throw invalid("Unknown selected-owner authorization-read fields"); + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) + throw invalid("Selected-owner authorization-read message exceeds 24 MiB"); + } + + 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/SelectedOwnerIntakeSettlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java new file mode 100644 index 0000000000..a7835eb75a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.Arrays; +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; + +/** Closed transport correlation and the complete immutable Account settlement response. */ +public final class SelectedOwnerIntakeSettlementEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_REQUEST_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 64 * 1024; + public static final int MAX_RESPONSE_BYTES = + AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES + MAX_REQUEST_BYTES + 64 * 1024; + + private SelectedOwnerIntakeSettlementEvidence() {} + + /** The correlation is independent from the retained operation, fence and intake identities. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding authorizationBinding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || authorizationBinding == null + || (authorizationBinding.owner() != Owner.AUTOMATION_SCRIPTING + && authorizationBinding.owner() != Owner.ENTITY_MANAGEMENT) + || !targetNamespace.equals(authorizationBinding.targetNamespace()) + || !(authorizationBinding.owner() == Owner.AUTOMATION_SCRIPTING + ? "account-automation-intake-authorization/v1".equals(authorizationBinding.schema()) + && "AUTOMATION_INTAKE_RETENTION".equals(authorizationBinding.purpose()) + : "account-entity-intake-authorization/v1".equals(authorizationBinding.schema()) + && "ENTITY_INTAKE_RETENTION".equals(authorizationBinding.purpose()))) { + throw invalid("Canonical same-namespace selected-owner authorization required"); + } + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + if (transportRequestId.equals(authorizationBinding.operationId()) + || transportRequestId.equals(authorizationBinding.fenceId()) + || transportRequestId.equals(authorizationBinding.intakeRequestId())) { + throw invalid("Independent settlement transport correlation required"); + } + byte[] bytes = authorizationBinding.canonicalBytes(); + if (bytes.length == 0 + || bytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + || !DraftAuthorizationFenceBinding.digest(bytes).equals(authorizationBinding.digest())) { + throw invalid("Canonical original authorization is required"); + } + var decoded = SelectedOwnerIntakeAuthorizationBinding.fromStored(bytes); + if (!Arrays.equals(bytes, decoded.canonicalBytes()) + || !authorizationBinding.digest().equals(decoded.digest())) { + throw invalid("Canonical original authorization is required"); + } + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding authorizationBinding) { + Objects.requireNonNull(authorizationBinding, "Original authorization is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (correlation.equals(authorizationBinding.operationId()) + || correlation.equals(authorizationBinding.fenceId()) + || correlation.equals(authorizationBinding.intakeRequestId())); + return new Request(SCHEMA_VERSION, namespace, correlation, authorizationBinding); + } + + public byte[] authorizationBindingBytes() { + return authorizationBinding.canonicalBytes(); + } + + public String authorizationBindingDigest() { + return authorizationBinding.digest(); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && transportRequestId.equals(other.transportRequestId) + && Arrays.equals(authorizationBindingBytes(), other.authorizationBindingBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, + targetNamespace, + transportRequestId, + Arrays.hashCode(authorizationBindingBytes())); + } + } + + /** Full settlement receipt paired with the exact request that Account echoed. */ + public record Result(Request request, AccountSelectedOwnerIntakeSettlementReceipt receipt) { + public Result { + Objects.requireNonNull(request, "Settlement request is required"); + Objects.requireNonNull(receipt, "Complete Account settlement receipt is required"); + byte[] receiptBytes = receipt.canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length + > AccountSelectedOwnerIntakeSettlementReceipt.maxBytes( + request.authorizationBinding().owner()) + || !DraftAuthorizationFenceBinding.digest(receiptBytes).equals(receipt.digest()) + || !request.targetNamespace().equals(receipt.targetNamespace()) + || !Arrays.equals( + request.authorizationBindingBytes(), receipt.authorizationBinding().canonicalBytes()) + || !request + .authorizationBindingDigest() + .equals(receipt.authorizationBinding().digest())) { + throw invalid("Settlement receipt differs from the exact original authorization"); + } + } + } + + private static IllegalArgumentException invalid(String description) { + return new IllegalArgumentException(description); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java new file mode 100644 index 0000000000..5a276e3312 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence.Request; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence.Result; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Strict closed-schema mapping for the standalone selected-owner settlement command. */ +public final class SelectedOwnerIntakeSettlementGrpcCodec { + public static final int MAX_REQUEST_BYTES = + SelectedOwnerIntakeSettlementEvidence.MAX_REQUEST_BYTES; + public static final int MAX_RESPONSE_BYTES = + SelectedOwnerIntakeSettlementEvidence.MAX_RESPONSE_BYTES; + + private SelectedOwnerIntakeSettlementGrpcCodec() {} + + public static SelectedOwnerIntakeSettlementRequest toRequest(Request request) { + if (request == null) throw invalid("Settlement request is required"); + byte[] authorization = request.authorizationBindingBytes(); + if (authorization.length == 0 + || authorization.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original authorization exceeds its 16 MiB bound"); + } + var wire = + SelectedOwnerIntakeSettlementRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(authorization)) + .setIntakeAuthorizationDigest(request.authorizationBindingDigest()) + .build(); + requireWithinBudget(wire.getSerializedSize(), MAX_REQUEST_BYTES, "request"); + return wire; + } + + public static Request fromRequest(SelectedOwnerIntakeSettlementRequest wire) { + requireKnownAndWithinBudget(wire, MAX_REQUEST_BYTES, "request"); + if (wire.getOriginalIntakeAuthorizationBinding().size() + > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original authorization exceeds its 16 MiB bound"); + } + DraftAuthorizationFenceBinding.canonicalUuid(wire.getTransportRequestId()); + byte[] authorizationBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (authorizationBytes.length == 0) throw invalid("Original authorization is required"); + SelectedOwnerIntakeAuthorizationBinding authorization; + try { + authorization = SelectedOwnerIntakeAuthorizationBinding.fromStored(authorizationBytes); + } catch (RuntimeException malformed) { + throw invalid("Original authorization is malformed or noncanonical"); + } + if (!authorization.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original authorization digest differs"); + } + Request request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getTransportRequestId()), + authorization); + if (!Arrays.equals(authorizationBytes, request.authorizationBindingBytes()) + || !toRequest(request).equals(wire)) { + throw invalid("Settlement request is noncanonical"); + } + return request; + } + + public static SelectedOwnerIntakeSettlementResponse toResponse(Result result) { + if (result == null) throw invalid("Complete settlement result is required"); + byte[] receipt = result.receipt().canonicalBytes(); + if (receipt.length == 0 + || receipt.length + > AccountSelectedOwnerIntakeSettlementReceipt.maxBytes( + result.request().authorizationBinding().owner())) { + throw invalid("Complete settlement receipt exceeds its owner bound"); + } + var response = + SelectedOwnerIntakeSettlementResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setSettlementReceipt(ByteString.copyFrom(receipt)) + .setSettlementReceiptDigest(result.receipt().digest()) + .build(); + requireWithinBudget(response.getSerializedSize(), MAX_RESPONSE_BYTES, "response"); + return response; + } + + public static Result fromResponse( + Request request, SelectedOwnerIntakeSettlementResponse response) { + if (request == null) throw invalid("Original settlement request is required"); + requireKnownAndWithinBudget(response, MAX_RESPONSE_BYTES, "response"); + if (!response.hasRequest()) throw invalid("Exact settlement request echo is required"); + requireKnownAndWithinBudget(response.getRequest(), MAX_REQUEST_BYTES, "echoed request"); + if (!toRequest(request).equals(response.getRequest())) { + throw invalid("Account changed the complete settlement request"); + } + if (response.getSettlementReceipt().size() + > AccountSelectedOwnerIntakeSettlementReceipt.maxBytes( + request.authorizationBinding().owner())) { + throw invalid("Complete settlement receipt exceeds its owner bound"); + } + byte[] receiptBytes = response.getSettlementReceipt().toByteArray(); + AccountSelectedOwnerIntakeSettlementReceipt receipt; + try { + receipt = AccountSelectedOwnerIntakeSettlementReceipt.fromStored(receiptBytes); + } catch (RuntimeException malformed) { + throw invalid("Complete settlement receipt is malformed or noncanonical"); + } + if (!Arrays.equals(receiptBytes, receipt.canonicalBytes()) + || !receipt.digest().equals(response.getSettlementReceiptDigest()) + || !Arrays.equals( + request.authorizationBindingBytes(), receipt.authorizationBinding().canonicalBytes()) + || !request.authorizationBindingDigest().equals(receipt.authorizationBinding().digest())) { + throw invalid("Settlement receipt digest or original authorization differs"); + } + return new Result(request, receipt); + } + + private static void requireKnownAndWithinBudget(Message wire, int maxBytes, String label) { + if (wire == null || wire.getSerializedSize() > maxBytes) { + throw invalid("Missing or oversized selected-owner settlement " + label); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown selected-owner settlement " + label + " fields"); + } + } + + private static void requireWithinBudget(int size, int maxBytes, String label) { + if (size > maxBytes) { + throw invalid("Selected-owner settlement " + label + " exceeds its wire budget"); + } + } + + private static IllegalArgumentException invalid(String description) { + return new IllegalArgumentException(description); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadClient.java new file mode 100644 index 0000000000..01d96dce15 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.account.sourceintake; + +/** Account client for the distinct selected-owner World closure HELD read. */ +public interface SelectedOwnerIntakeWorldClosureAuthorizationReadClient { + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence readHeld( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.java new file mode 100644 index 0000000000..ba6702a1db --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.java @@ -0,0 +1,72 @@ +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.grpc.GrpcPeerIdentity; + +/** Exact lookup identity for World to read a finalized selected-owner Account authorization. */ +public record SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(Request request) { + public static final int SCHEMA_VERSION = 1; + + public SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence { + Objects.requireNonNull(request, "World closure authorization-read request is required"); + } + + /** The original binding is lookup evidence only; Account authentication establishes HELD. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || binding == null + || !targetNamespace.equals(binding.targetNamespace())) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) { + throw invalid(); + } + Objects.requireNonNull(binding.owner(), "closed Entity or Automation owner is required"); + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + Objects.requireNonNull(binding, "finalized selected-owner authorization is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (sameIdentity(correlation, binding)); + return new Request(SCHEMA_VERSION, namespace, correlation, binding); + } + + public String intendedReader() { + return "spiffe://firemud/ns/" + targetNamespace + "/sa/world-management-service"; + } + + public String closureReadPurpose() { + return switch (binding.owner()) { + case ENTITY_MANAGEMENT -> "ENTITY_INTAKE_WORLD_CLOSURE_READ"; + case AUTOMATION_SCRIPTING -> "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"; + default -> throw invalid(); + }; + } + + private static boolean sameIdentity( + UUID candidate, SelectedOwnerIntakeAuthorizationBinding binding) { + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Invalid selected-owner World closure authorization-read evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.java new file mode 100644 index 0000000000..0f8f39131d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.java @@ -0,0 +1,104 @@ +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.ReadHeldSelectedOwnerWorldClosureAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed protobuf encoding for Account's distinct World closure HELD read. */ +public final class SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + private SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec() {} + + public static ReadHeldSelectedOwnerWorldClosureAuthorizationRequest toRequest( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "World closure authorization-read request is required"); + byte[] bindingBytes = request.binding().canonicalBytes(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Selected-owner authorization exceeds its 16 MiB limit"); + } + var wire = + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setClosureReadPurpose(request.closureReadPurpose()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request fromRequest( + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest wire) { + requireKnownAndWithinBudget(wire); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getReadRequestId()); + byte[] bindingBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Selected-owner authorization size is invalid"); + } + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(wire.getIntakeAuthorizationDigest())) + throw invalid("Selected-owner authorization digest differs"); + var request = + new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getReadRequestId()), + binding); + if (!request.intendedReader().equals(wire.getIntendedReader()) + || !request.closureReadPurpose().equals(wire.getClosureReadPurpose()) + || !toRequest(request).equals(wire)) { + throw invalid("Selected-owner World reader, purpose, or request differs"); + } + return request; + } + + public static ReadHeldSelectedOwnerWorldClosureAuthorizationResponse toHeldResponse( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { + var response = + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse.newBuilder() + .setRequest(toRequest(request)) + .setHeld(true) + .build(); + requireWithinBudget(response.getSerializedSize()); + return response; + } + + public static SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence fromResponse( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request, + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse response) { + Objects.requireNonNull(request, "World closure authorization-read request is required"); + requireKnownAndWithinBudget(response); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getHeld()) { + throw invalid("Exact held selected-owner World closure authorization response required"); + } + return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(request); + } + + private static void requireKnownAndWithinBudget(Message wire) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Missing or oversized selected-owner World closure read message"); + if (!wire.getUnknownFields().asMap().isEmpty()) + throw invalid("Unknown selected-owner World closure read fields"); + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) + throw invalid("Selected-owner World closure read message exceeds 24 MiB"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java new file mode 100644 index 0000000000..e36fac3be8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java @@ -0,0 +1,717 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.ByteArrayOutputStream; +import java.time.OffsetDateTime; +import java.time.format.DateTimeParseException; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; + +/** Immutable retained outcome for one freshly founded empty Automation source scope. */ +public final class AutomationEmptySelectedSourceIntakeReceipt { + public static final String DOMAIN = "automation-empty-selected-source-intake-receipt/v1"; + public static final int MAX_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES + + SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES + + 16 * 1024; + + private final String targetNamespace; + private final UUID operationId; + private final UUID fenceId; + private final UUID intakeRequestId; + private final UUID canonicalTenantId; + private final UUID canonicalVersionId; + private final UUID selectedCommitId; + private final UUID sourceRevisionId; + private final String sourceRevisionOrder; + private final long localTenantKey; + private final long localVersionKey; + private final String requestDigest; + private final String authorizationBindingDigest; + private final byte[] authorizationBindingBytes; + private final UUID worldReadRequestId; + private final String worldReadRequestDigest; + private final byte[] worldReadRequestBytes; + private final String worldInventoryDigest; + private final byte[] worldInventoryBytes; + private final long scriptsRowCount; + private final long eventBindingsRowCount; + private final long patchBaseBindingsRowCount; + private final long unqualifiedScriptsRowCount; + private final long unqualifiedEventBindingsRowCount; + private final long unqualifiedPatchBaseBindingsRowCount; + private final long emptyAssociatedScriptsRowCount; + private final long emptyAssociatedEventBindingsRowCount; + private final long emptyAssociatedPatchBaseBindingsRowCount; + private final long selectedScopeScriptsRowCount; + private final long selectedScopeEventBindingsRowCount; + private final long selectedScopePatchBaseBindingsRowCount; + private final OffsetDateTime retainedAt; + private final byte[] canonicalBytes; + private final String receiptDigest; + private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; + private final SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence; + + private AutomationEmptySelectedSourceIntakeReceipt( + String targetNamespace, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID selectedCommitId, + UUID sourceRevisionId, + String sourceRevisionOrder, + long localTenantKey, + long localVersionKey, + String requestDigest, + String authorizationBindingDigest, + byte[] authorizationBindingBytes, + UUID worldReadRequestId, + String worldReadRequestDigest, + byte[] worldReadRequestBytes, + String worldInventoryDigest, + byte[] worldInventoryBytes, + long scriptsRowCount, + long eventBindingsRowCount, + long patchBaseBindingsRowCount, + long unqualifiedScriptsRowCount, + long unqualifiedEventBindingsRowCount, + long unqualifiedPatchBaseBindingsRowCount, + long emptyAssociatedScriptsRowCount, + long emptyAssociatedEventBindingsRowCount, + long emptyAssociatedPatchBaseBindingsRowCount, + long selectedScopeScriptsRowCount, + long selectedScopeEventBindingsRowCount, + long selectedScopePatchBaseBindingsRowCount, + OffsetDateTime retainedAt) { + this.targetNamespace = requireText(targetNamespace, "targetNamespace"); + this.operationId = requireUuid(operationId, "operationId"); + this.fenceId = requireUuid(fenceId, "fenceId"); + this.intakeRequestId = requireUuid(intakeRequestId, "intakeRequestId"); + this.canonicalTenantId = requireUuid(canonicalTenantId, "canonicalTenantId"); + this.canonicalVersionId = requireUuid(canonicalVersionId, "canonicalVersionId"); + this.selectedCommitId = requireUuid(selectedCommitId, "selectedCommitId"); + this.sourceRevisionId = requireUuid(sourceRevisionId, "sourceRevisionId"); + this.sourceRevisionOrder = requireDecimal(sourceRevisionOrder, "sourceRevisionOrder"); + if (localTenantKey <= 0L || localVersionKey <= 0L || localTenantKey == localVersionKey) { + throw new IllegalArgumentException("Distinct positive Automation local keys are required"); + } + this.localTenantKey = localTenantKey; + this.localVersionKey = localVersionKey; + this.requestDigest = requireDigest(requestDigest, "requestDigest"); + this.authorizationBindingDigest = + requireDigest(authorizationBindingDigest, "authorizationBindingDigest"); + this.authorizationBindingBytes = + boundedBytes( + authorizationBindingBytes, + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES, + "authorizationBindingBytes"); + this.worldReadRequestId = requireUuid(worldReadRequestId, "worldReadRequestId"); + this.worldReadRequestDigest = requireDigest(worldReadRequestDigest, "worldReadRequestDigest"); + this.worldReadRequestBytes = + boundedBytes( + worldReadRequestBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES, + "worldReadRequestBytes"); + this.worldInventoryDigest = requireDigest(worldInventoryDigest, "worldInventoryDigest"); + this.worldInventoryBytes = + boundedBytes( + worldInventoryBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES, + "worldInventoryBytes"); + this.scriptsRowCount = nonnegative(scriptsRowCount, "scriptsRowCount"); + this.eventBindingsRowCount = nonnegative(eventBindingsRowCount, "eventBindingsRowCount"); + this.patchBaseBindingsRowCount = + nonnegative(patchBaseBindingsRowCount, "patchBaseBindingsRowCount"); + this.unqualifiedScriptsRowCount = + nonnegative(unqualifiedScriptsRowCount, "unqualifiedScriptsRowCount"); + this.unqualifiedEventBindingsRowCount = + nonnegative(unqualifiedEventBindingsRowCount, "unqualifiedEventBindingsRowCount"); + this.unqualifiedPatchBaseBindingsRowCount = + nonnegative(unqualifiedPatchBaseBindingsRowCount, "unqualifiedPatchBaseBindingsRowCount"); + this.emptyAssociatedScriptsRowCount = + nonnegative(emptyAssociatedScriptsRowCount, "emptyAssociatedScriptsRowCount"); + this.emptyAssociatedEventBindingsRowCount = + nonnegative(emptyAssociatedEventBindingsRowCount, "emptyAssociatedEventBindingsRowCount"); + this.emptyAssociatedPatchBaseBindingsRowCount = + nonnegative( + emptyAssociatedPatchBaseBindingsRowCount, "emptyAssociatedPatchBaseBindingsRowCount"); + this.selectedScopeScriptsRowCount = + nonnegative(selectedScopeScriptsRowCount, "selectedScopeScriptsRowCount"); + this.selectedScopeEventBindingsRowCount = + nonnegative(selectedScopeEventBindingsRowCount, "selectedScopeEventBindingsRowCount"); + this.selectedScopePatchBaseBindingsRowCount = + nonnegative( + selectedScopePatchBaseBindingsRowCount, "selectedScopePatchBaseBindingsRowCount"); + if (Math.addExact(unqualifiedScriptsRowCount, emptyAssociatedScriptsRowCount) != scriptsRowCount + || Math.addExact(unqualifiedEventBindingsRowCount, emptyAssociatedEventBindingsRowCount) + != eventBindingsRowCount + || Math.addExact( + unqualifiedPatchBaseBindingsRowCount, emptyAssociatedPatchBaseBindingsRowCount) + != patchBaseBindingsRowCount) { + throw new IllegalArgumentException("Automation source census partitions do not add up"); + } + if (unqualifiedScriptsRowCount != 0L + || unqualifiedEventBindingsRowCount != 0L + || unqualifiedPatchBaseBindingsRowCount != 0L + || emptyAssociatedScriptsRowCount != 0L + || emptyAssociatedEventBindingsRowCount != 0L + || emptyAssociatedPatchBaseBindingsRowCount != 0L + || selectedScopeScriptsRowCount != 0L + || selectedScopeEventBindingsRowCount != 0L + || selectedScopePatchBaseBindingsRowCount != 0L) { + throw new IllegalArgumentException( + "Fresh empty Automation intake requires a zero unqualified and selected-scope census"); + } + this.retainedAt = Objects.requireNonNull(retainedAt, "retainedAt"); + if (retainedAt.getOffset().getTotalSeconds() != 0) { + throw new IllegalArgumentException("Receipt timestamp must use UTC"); + } + + this.authorizationBinding = + SelectedOwnerIntakeAuthorizationBinding.fromStored(this.authorizationBindingBytes); + if (!this.authorizationBinding.digest().equals(this.authorizationBindingDigest)) { + throw new IllegalArgumentException("Retained Account authorization digest differs"); + } + this.worldInventoryReadEvidence = decodeWorldEvidence(); + requireAuthorizationIdentity(); + this.canonicalBytes = encode(); + if (canonicalBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Automation source receipt exceeds its size limit"); + } + this.receiptDigest = DraftAuthorizationFenceBinding.digest(canonicalBytes); + } + + public static AutomationEmptySelectedSourceIntakeReceipt create( + SelectedOwnerEmptySourceInputs inputs, + long localTenantKey, + long localVersionKey, + String requestDigest, + long scriptsRowCount, + long eventBindingsRowCount, + long patchBaseBindingsRowCount, + long unqualifiedScriptsRowCount, + long unqualifiedEventBindingsRowCount, + long unqualifiedPatchBaseBindingsRowCount, + long emptyAssociatedScriptsRowCount, + long emptyAssociatedEventBindingsRowCount, + long emptyAssociatedPatchBaseBindingsRowCount, + long selectedScopeScriptsRowCount, + long selectedScopeEventBindingsRowCount, + long selectedScopePatchBaseBindingsRowCount, + OffsetDateTime retainedAt) { + Objects.requireNonNull(inputs, "validated empty-source inputs are required"); + var binding = inputs.authorizationBinding(); + var declaration = inputs.ownerSourceInventoryDeclaration(); + var worldEvidence = inputs.worldInventoryReadEvidence(); + var worldRequest = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(worldEvidence.request()); + byte[] accountBytes = binding.canonicalBytes(); + byte[] worldRequestBytes = worldRequest.toByteArray(); + byte[] worldInventoryBytes = worldEvidence.inventory().canonicalBytes(); + return new AutomationEmptySelectedSourceIntakeReceipt( + binding.targetNamespace(), + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.tenantId(), + binding.versionId(), + binding.selected().commitId(), + declaration.revisionId(), + declaration.revisionOrder(), + localTenantKey, + localVersionKey, + requestDigest, + binding.digest(), + accountBytes, + worldEvidence.request().readRequestId(), + DraftAuthorizationFenceBinding.digest(worldRequestBytes), + worldRequestBytes, + worldEvidence.inventory().digest(), + worldInventoryBytes, + scriptsRowCount, + eventBindingsRowCount, + patchBaseBindingsRowCount, + unqualifiedScriptsRowCount, + unqualifiedEventBindingsRowCount, + unqualifiedPatchBaseBindingsRowCount, + emptyAssociatedScriptsRowCount, + emptyAssociatedEventBindingsRowCount, + emptyAssociatedPatchBaseBindingsRowCount, + selectedScopeScriptsRowCount, + selectedScopeEventBindingsRowCount, + selectedScopePatchBaseBindingsRowCount, + retainedAt); + } + + /** Strictly decodes the complete immutable owner receipt retained by Automation. */ + public static AutomationEmptySelectedSourceIntakeReceipt fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Stored Automation source receipt size is invalid"); + } + byte[] stored = bytes.clone(); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(DOMAIN); + if (!"1".equals(reader.text())) { + throw new IllegalArgumentException("Unsupported Automation source receipt schema"); + } + var result = + new AutomationEmptySelectedSourceIntakeReceipt( + reader.text(), + parseUuid(reader.text(), "operationId"), + parseUuid(reader.text(), "fenceId"), + parseUuid(reader.text(), "intakeRequestId"), + parseUuid(reader.text(), "canonicalTenantId"), + parseUuid(reader.text(), "canonicalVersionId"), + parseUuid(reader.text(), "selectedCommitId"), + parseUuid(reader.text(), "sourceRevisionId"), + reader.text(), + parsePositiveLong(reader.text(), "localTenantKey"), + parsePositiveLong(reader.text(), "localVersionKey"), + reader.text(), + reader.text(), + reader.bytes(), + parseUuid(reader.text(), "worldReadRequestId"), + reader.text(), + reader.bytes(), + reader.text(), + reader.bytes(), + parseLong(reader.text(), "scriptsRowCount"), + parseLong(reader.text(), "eventBindingsRowCount"), + parseLong(reader.text(), "patchBaseBindingsRowCount"), + parseLong(reader.text(), "unqualifiedScriptsRowCount"), + parseLong(reader.text(), "unqualifiedEventBindingsRowCount"), + parseLong(reader.text(), "unqualifiedPatchBaseBindingsRowCount"), + parseLong(reader.text(), "emptyAssociatedScriptsRowCount"), + parseLong(reader.text(), "emptyAssociatedEventBindingsRowCount"), + parseLong(reader.text(), "emptyAssociatedPatchBaseBindingsRowCount"), + parseLong(reader.text(), "selectedScopeScriptsRowCount"), + parseLong(reader.text(), "selectedScopeEventBindingsRowCount"), + parseLong(reader.text(), "selectedScopePatchBaseBindingsRowCount"), + parseTimestamp(reader.text())); + reader.requireEnd(); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical stored Automation source receipt"); + } + return result; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID operationId() { + return operationId; + } + + public UUID fenceId() { + return fenceId; + } + + public UUID intakeRequestId() { + return intakeRequestId; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public UUID selectedCommitId() { + return selectedCommitId; + } + + public UUID sourceRevisionId() { + return sourceRevisionId; + } + + public String sourceRevisionOrder() { + return sourceRevisionOrder; + } + + public long localTenantKey() { + return localTenantKey; + } + + public long localVersionKey() { + return localVersionKey; + } + + public String requestDigest() { + return requestDigest; + } + + public String authorizationBindingDigest() { + return authorizationBindingDigest; + } + + public byte[] authorizationBindingBytes() { + return authorizationBindingBytes.clone(); + } + + public UUID worldReadRequestId() { + return worldReadRequestId; + } + + public String worldReadRequestDigest() { + return worldReadRequestDigest; + } + + public byte[] worldReadRequestBytes() { + return worldReadRequestBytes.clone(); + } + + public String worldInventoryDigest() { + return worldInventoryDigest; + } + + public byte[] worldInventoryBytes() { + return worldInventoryBytes.clone(); + } + + public long scriptsRowCount() { + return scriptsRowCount; + } + + public long eventBindingsRowCount() { + return eventBindingsRowCount; + } + + public long patchBaseBindingsRowCount() { + return patchBaseBindingsRowCount; + } + + public long unqualifiedScriptsRowCount() { + return unqualifiedScriptsRowCount; + } + + public long unqualifiedEventBindingsRowCount() { + return unqualifiedEventBindingsRowCount; + } + + public long unqualifiedPatchBaseBindingsRowCount() { + return unqualifiedPatchBaseBindingsRowCount; + } + + public long emptyAssociatedScriptsRowCount() { + return emptyAssociatedScriptsRowCount; + } + + public long emptyAssociatedEventBindingsRowCount() { + return emptyAssociatedEventBindingsRowCount; + } + + public long emptyAssociatedPatchBaseBindingsRowCount() { + return emptyAssociatedPatchBaseBindingsRowCount; + } + + public long selectedScopeScriptsRowCount() { + return selectedScopeScriptsRowCount; + } + + public long selectedScopeEventBindingsRowCount() { + return selectedScopeEventBindingsRowCount; + } + + public long selectedScopePatchBaseBindingsRowCount() { + return selectedScopePatchBaseBindingsRowCount; + } + + public OffsetDateTime retainedAt() { + return retainedAt; + } + + public String receiptDigest() { + return receiptDigest; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String outcome() { + return "COMMITTED_EMPTY"; + } + + /** This bounded slice never settles or releases Account's original source participation. */ + public String sourceParticipationDisposition() { + return "PENDING_OWNER_TERMINAL_SETTLEMENT"; + } + + public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + return authorizationBinding; + } + + public SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence() { + return worldInventoryReadEvidence; + } + + /** Checks a caller retry against the original Account binding and exact selected World freeze. */ + public void requireSameRequest( + String namespace, + SelectedOwnerIntakeAuthorizationBinding candidateBinding, + WorldSelectedDraftPublicationFreezeEvidence candidateFreeze) { + Objects.requireNonNull(candidateBinding, "candidate Account binding is required"); + Objects.requireNonNull(candidateFreeze, "candidate World freeze is required"); + String candidateDigest = requestDigest(namespace, candidateBinding, candidateFreeze); + if (!targetNamespace.equals(namespace) + || !requestDigest.equals(candidateDigest) + || !Arrays.equals(authorizationBindingBytes, candidateBinding.canonicalBytes()) + || !worldInventoryReadEvidence.request().freezeEvidence().equals(candidateFreeze)) { + throw new IllegalStateException( + "Automation source intake request identity already records different selected evidence"); + } + } + + /** Also binds a concurrent first-write race to the exact newly read World inventory content. */ + public void requireSameInputs(SelectedOwnerEmptySourceInputs candidateInputs) { + Objects.requireNonNull(candidateInputs, "validated empty-source inputs are required"); + var candidateBinding = candidateInputs.authorizationBinding(); + var candidateWorld = candidateInputs.worldInventoryReadEvidence(); + requireSameRequest( + candidateBinding.targetNamespace(), + candidateBinding, + candidateWorld.request().freezeEvidence()); + if (!Arrays.equals(worldInventoryBytes, candidateWorld.inventory().canonicalBytes()) + || !worldInventoryDigest.equals(candidateWorld.inventory().digest())) { + throw new IllegalStateException( + "Automation source intake request identity already records different World evidence"); + } + } + + /** Digest for the caller-stable request, excluding the fresh World read correlation. */ + public static String requestDigest( + String namespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + requireText(namespace, "targetNamespace"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "automation-empty-selected-source-intake-request/v1"); + DraftAuthorizationFenceBinding.frame(out, namespace); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame( + out, + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freezeEvidence.request()) + .toByteArray()); + DraftAuthorizationFenceBinding.frame( + out, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freezeEvidence.acknowledgement()) + .toByteArray()); + return DraftAuthorizationFenceBinding.digest(out.toByteArray()); + } + + private void requireAuthorizationIdentity() { + if (authorizationBinding.owner() != Owner.AUTOMATION_SCRIPTING + || !authorizationBinding.schema().equals("account-automation-intake-authorization/v1") + || !authorizationBinding.purpose().equals("AUTOMATION_INTAKE_RETENTION") + || !authorizationBinding.targetNamespace().equals(targetNamespace) + || !authorizationBinding.operationId().equals(operationId) + || !authorizationBinding.fenceId().equals(fenceId) + || !authorizationBinding.intakeRequestId().equals(intakeRequestId) + || !authorizationBinding.tenantId().equals(canonicalTenantId) + || !authorizationBinding.versionId().equals(canonicalVersionId) + || !authorizationBinding.selected().commitId().equals(selectedCommitId)) { + throw new IllegalArgumentException( + "Automation receipt differs from its original Account binding"); + } + var declaration = + new SelectedOwnerEmptySourceInputs(authorizationBinding, decodeWorldEvidence()) + .ownerSourceInventoryDeclaration(); + if (declaration.owner() != Owner.AUTOMATION_SCRIPTING + || !declaration.revisionId().equals(sourceRevisionId) + || !declaration.revisionOrder().equals(sourceRevisionOrder)) { + throw new IllegalArgumentException( + "Automation receipt differs from its original source revision"); + } + if (!requestDigest.equals( + requestDigest( + targetNamespace, + authorizationBinding, + worldInventoryReadEvidence.request().freezeEvidence()))) { + throw new IllegalArgumentException("Automation receipt request digest differs"); + } + } + + private SelectedOwnerWorldInventoryReadEvidence decodeWorldEvidence() { + if (!DraftAuthorizationFenceBinding.digest(worldReadRequestBytes) + .equals(worldReadRequestDigest)) { + throw new IllegalArgumentException("Retained World read request digest differs"); + } + final ReadSelectedOwnerWorldInventoryRequest requestMessage; + try { + requestMessage = ReadSelectedOwnerWorldInventoryRequest.parseFrom(worldReadRequestBytes); + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("Retained World read request is malformed", invalid); + } + if (!Arrays.equals(worldReadRequestBytes, requestMessage.toByteArray())) { + throw new IllegalArgumentException("Retained World read request is not canonical"); + } + var request = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(requestMessage); + if (!request.readRequestId().equals(worldReadRequestId) + || !request.targetNamespace().equals(targetNamespace) + || !Arrays.equals( + authorizationBindingBytes, request.authorizationBinding().canonicalBytes())) { + throw new IllegalArgumentException( + "Retained World request differs from the original binding"); + } + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + request.freezeEvidence(), worldInventoryBytes, worldInventoryDigest); + return new SelectedOwnerWorldInventoryReadEvidence(request, inventory); + } + + private byte[] encode() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + frame(out, DOMAIN); + frame(out, "1"); + frame(out, targetNamespace); + frame(out, operationId.toString()); + frame(out, fenceId.toString()); + frame(out, intakeRequestId.toString()); + frame(out, canonicalTenantId.toString()); + frame(out, canonicalVersionId.toString()); + frame(out, selectedCommitId.toString()); + frame(out, sourceRevisionId.toString()); + frame(out, sourceRevisionOrder); + frame(out, Long.toString(localTenantKey)); + frame(out, Long.toString(localVersionKey)); + frame(out, requestDigest); + frame(out, authorizationBindingDigest); + frame(out, authorizationBindingBytes); + frame(out, worldReadRequestId.toString()); + frame(out, worldReadRequestDigest); + frame(out, worldReadRequestBytes); + frame(out, worldInventoryDigest); + frame(out, worldInventoryBytes); + frame(out, Long.toString(scriptsRowCount)); + frame(out, Long.toString(eventBindingsRowCount)); + frame(out, Long.toString(patchBaseBindingsRowCount)); + frame(out, Long.toString(unqualifiedScriptsRowCount)); + frame(out, Long.toString(unqualifiedEventBindingsRowCount)); + frame(out, Long.toString(unqualifiedPatchBaseBindingsRowCount)); + frame(out, Long.toString(emptyAssociatedScriptsRowCount)); + frame(out, Long.toString(emptyAssociatedEventBindingsRowCount)); + frame(out, Long.toString(emptyAssociatedPatchBaseBindingsRowCount)); + frame(out, Long.toString(selectedScopeScriptsRowCount)); + frame(out, Long.toString(selectedScopeEventBindingsRowCount)); + frame(out, Long.toString(selectedScopePatchBaseBindingsRowCount)); + frame(out, retainedAt.toString()); + return out.toByteArray(); + } + + 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 byte[] boundedBytes(byte[] value, int max, String label) { + if (value == null || value.length == 0 || value.length > max) { + throw new IllegalArgumentException(label + " is absent or exceeds its limit"); + } + return value.clone(); + } + + private static String requireText(String value, String label) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException(label + " is required"); + } + for (int i = 0; i < value.length(); i++) { + char character = value.charAt(i); + if (Character.isHighSurrogate(character)) { + if (++i >= value.length() || !Character.isLowSurrogate(value.charAt(i))) { + throw new IllegalArgumentException(label + " contains an unpaired surrogate"); + } + } else if (Character.isLowSurrogate(character)) { + throw new IllegalArgumentException(label + " contains an unpaired surrogate"); + } + } + return value; + } + + private static String requireDigest(String value, String label) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + return value; + } + + private static String requireDecimal(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, true); + return value; + } + + private static long nonnegative(long value, String label) { + if (value < 0L) { + throw new IllegalArgumentException(label + " cannot be negative"); + } + return value; + } + + private static UUID requireUuid(UUID value, String label) { + try { + DraftAuthorizationFenceBinding.requireUuid(value); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + return value; + } + + private static UUID parseUuid(String value, String label) { + try { + UUID id = UUID.fromString(value); + if (!id.toString().equals(value)) { + throw new IllegalArgumentException("Noncanonical UUID"); + } + return requireUuid(id, label); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static long parsePositiveLong(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, false); + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal"); + } + return parsed; + } + + private static long parseLong(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, true); + return Long.parseLong(value); + } + + private static OffsetDateTime parseTimestamp(String value) { + final OffsetDateTime parsed; + try { + parsed = OffsetDateTime.parse(value); + } catch (DateTimeParseException malformed) { + throw new IllegalArgumentException("Receipt timestamp is malformed", malformed); + } + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Receipt timestamp is not canonical"); + } + return parsed; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java new file mode 100644 index 0000000000..0386f11faa --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java @@ -0,0 +1,160 @@ +package net.firedevops.firemud.common.automation.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.automationscripting.v1.AutomationSelectedSourceIntakeTerminalReadServiceGrpc; +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; + +/** File-backed mTLS client for Automation's exact original selected-source terminal read. */ +public final class AutomationSelectedSourceIntakeTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AutomationSelectedSourceIntakeTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AutomationSelectedSourceIntakeTerminalReadClient.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("Automation terminal-read client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Automation terminal-read stub unavailable"); + } + initialized = true; + } + + /** Returns only an exact original COMMITTED_EMPTY receipt, outside owner SQL. */ + public AutomationSelectedSourceIntakeTerminalReadEvidence read( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Automation terminal read must run outside owner SQL"); + } + Objects.requireNonNull(request, "terminal-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Automation terminal read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedSourceIntakeTerminal( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); + try { + return AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Automation returned invalid terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAutomationScriptingService(); + } + + @Override + protected String defaultTarget() { + return "automation-scripting-service:6565"; + } + + @Override + protected AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/automation-scripting-service"; + return AutomationSelectedSourceIntakeTerminalReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.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 AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Automation terminal-read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Automation terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Automation terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Automation terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Automation terminal read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Automation terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java new file mode 100644 index 0000000000..65c66ca538 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact lookup correlation and the original committed Automation receipt. */ +public record AutomationSelectedSourceIntakeTerminalReadEvidence( + Request request, AutomationEmptySelectedSourceIntakeReceipt receipt) { + public static final int SCHEMA_VERSION = 1; + public static final String TERMINAL_READ_PURPOSE = "AUTOMATION_INTAKE_TERMINAL_READ"; + + public AutomationSelectedSourceIntakeTerminalReadEvidence { + Objects.requireNonNull(request, "terminal-read request is required"); + Objects.requireNonNull(receipt, "committed Automation receipt is required"); + if (!request.targetNamespace().equals(receipt.targetNamespace()) + || !Arrays.equals(request.binding().canonicalBytes(), receipt.authorizationBindingBytes()) + || !"COMMITTED_EMPTY".equals(receipt.outcome())) { + throw new IllegalArgumentException( + "Automation receipt differs from the complete original terminal-read binding"); + } + } + + /** The correlation changes per transport read and never changes the retained operation. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || binding == null + || !targetNamespace.equals(binding.targetNamespace()) + || binding.owner() != Owner.AUTOMATION_SCRIPTING + || !"account-automation-intake-authorization/v1".equals(binding.schema()) + || !"AUTOMATION_INTAKE_RETENTION".equals(binding.purpose()) + || binding.canonicalBytes().length == 0 + || binding.canonicalBytes().length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if (collides(readRequestId, binding)) throw invalid(); + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + Objects.requireNonNull(binding, "original finalized Account binding is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (collides(correlation, binding)); + return new Request(SCHEMA_VERSION, namespace, correlation, binding); + } + + /** Account is the only intended reader of this Automation-owned terminal. */ + public String intendedReader() { + return "spiffe://firemud/ns/" + targetNamespace + "/sa/account-service"; + } + + public String terminalReadPurpose() { + return TERMINAL_READ_PURPOSE; + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && readRequestId.equals(other.readRequestId) + && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + } + + private static boolean collides( + UUID candidate, SelectedOwnerIntakeAuthorizationBinding binding) { + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Automation selected-source terminal request"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..fb636d537c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcCodec.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalResult; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed terminal mapping with an unchanged request echo and canonical receipt validation. */ +public final class AutomationSelectedSourceIntakeTerminalReadGrpcCodec { + private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024; + + /** Full receipt plus a complete echoed 16 MiB Account binding and bounded protobuf framing. */ + public static final int MAX_WIRE_BYTES = + AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + private AutomationSelectedSourceIntakeTerminalReadGrpcCodec() {} + + public static ReadSelectedSourceIntakeTerminalRequest toRequest( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "terminal-read request is required"); + byte[] bindingBytes = request.binding().canonicalBytes(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Automation authorization exceeds its 16 MiB limit"); + } + var wire = + ReadSelectedSourceIntakeTerminalRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setTerminalReadPurpose(request.terminalReadPurpose()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static AutomationSelectedSourceIntakeTerminalReadEvidence.Request fromRequest( + ReadSelectedSourceIntakeTerminalRequest wire) { + requireKnownAndWithinBudget(wire, "terminal-read request"); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getReadRequestId()); + byte[] bindingBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Automation authorization size is invalid"); + } + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original Automation authorization digest differs"); + } + var request = + new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getReadRequestId()), + binding); + if (!request.intendedReader().equals(wire.getIntendedReader()) + || !request.terminalReadPurpose().equals(wire.getTerminalReadPurpose()) + || !toRequest(request).equals(wire)) { + throw invalid("Terminal reader, purpose, or request differs"); + } + return request; + } + + public static ReadSelectedSourceIntakeTerminalResponse toResponse( + AutomationSelectedSourceIntakeTerminalReadEvidence evidence) { + Objects.requireNonNull(evidence, "committed Automation terminal evidence is required"); + byte[] receiptBytes = evidence.receipt().canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Committed Automation receipt size is invalid"); + } + var response = + ReadSelectedSourceIntakeTerminalResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setResult( + AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY) + .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes)) + .setReceiptDigest(evidence.receipt().receiptDigest()) + .build(); + requireWithinBudget(response.getSerializedSize()); + return response; + } + + public static AutomationSelectedSourceIntakeTerminalReadEvidence fromResponse( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request, + ReadSelectedSourceIntakeTerminalResponse response) { + Objects.requireNonNull(request, "terminal-read request is required"); + requireKnownAndWithinBudget(response, "terminal-read response"); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || response.getResult() + != AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY) { + throw invalid("Exact COMMITTED_EMPTY response and full request echo required"); + } + byte[] receiptBytes = response.getCommittedEmptyReceipt().toByteArray(); + if (receiptBytes.length == 0 + || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Missing or oversized committed Automation receipt"); + } + AutomationEmptySelectedSourceIntakeReceipt receipt = + AutomationEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + if (!receipt.receiptDigest().equals(response.getReceiptDigest())) { + throw invalid("Automation receipt digest differs"); + } + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt); + } + + private static void requireKnownAndWithinBudget(Message wire, String label) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) { + throw invalid("Missing or oversized Automation " + label); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown Automation " + label + " fields"); + } + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) { + throw invalid("Automation terminal-read message exceeds its derived 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/entity/sourceintake/EntityEmptySelectedSourceIntakeReceipt.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntityEmptySelectedSourceIntakeReceipt.java new file mode 100644 index 0000000000..0b3e2559ae --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntityEmptySelectedSourceIntakeReceipt.java @@ -0,0 +1,880 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.ByteArrayOutputStream; +import java.time.OffsetDateTime; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable local receipt for a freshly founded, explicitly empty Entity source catalogue. */ +public final class EntityEmptySelectedSourceIntakeReceipt { + public static final String DOMAIN = "entity-selected-empty-source-catalogue/v1"; + public static final int SCHEMA_VERSION = 1; + public static final int MAX_BYTES = 80 * 1024 * 1024; + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final String targetNamespace; + private final UUID genesisId; + private final UUID operationId; + private final UUID fenceId; + private final UUID intakeRequestId; + private final UUID canonicalTenantId; + private final UUID canonicalVersionId; + private final UUID selectedCommitId; + private final UUID sourceRevisionId; + private final String sourceRevisionOrder; + private final long localTenantKey; + private final long localVersionKey; + private final String requestDigest; + private final String schemaDigest; + private final String authorizationBindingDigest; + private final byte[] authorizationBindingBytes; + private final String selectedSourceDigest; + private final byte[] selectedSourceBytes; + private final String selectedSourceRevisionBindingDigest; + private final byte[] selectedSourceRevisionBindingBytes; + private final UUID worldReadRequestId; + private final String worldReadRequestDigest; + private final byte[] worldReadRequestBytes; + private final String worldClosureDigest; + private final byte[] worldClosureBytes; + private final List familyStates; + private final OffsetDateTime retainedAt; + private final byte[] canonicalBytes; + private final String receiptDigest; + private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; + private final SelectedOwnerEmptySourceInputs inputs; + + private EntityEmptySelectedSourceIntakeReceipt( + String targetNamespace, + UUID genesisId, + long localTenantKey, + long localVersionKey, + String requestDigest, + String schemaDigest, + byte[] authorizationBindingBytes, + String authorizationBindingDigest, + byte[] selectedSourceBytes, + String selectedSourceDigest, + byte[] selectedSourceRevisionBindingBytes, + String selectedSourceRevisionBindingDigest, + UUID worldReadRequestId, + byte[] worldReadRequestBytes, + String worldReadRequestDigest, + byte[] worldClosureBytes, + String worldClosureDigest, + List familyStates, + OffsetDateTime retainedAt) { + this.targetNamespace = requireText(targetNamespace, "targetNamespace"); + this.genesisId = requireUuid(genesisId, "genesisId"); + if (localTenantKey <= 0L || localVersionKey <= 0L || localTenantKey == localVersionKey) { + throw new IllegalArgumentException("Distinct positive Entity local keys are required"); + } + this.localTenantKey = localTenantKey; + this.localVersionKey = localVersionKey; + this.requestDigest = requireDigest(requestDigest, "requestDigest"); + this.authorizationBindingBytes = + boundedBytes( + authorizationBindingBytes, + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES, + "authorizationBindingBytes"); + this.authorizationBinding = + SelectedOwnerIntakeAuthorizationBinding.fromStored(this.authorizationBindingBytes); + this.authorizationBindingDigest = + requireDigest(authorizationBindingDigest, "authorizationBindingDigest"); + if (!this.authorizationBinding.digest().equals(this.authorizationBindingDigest)) { + throw new IllegalArgumentException("Retained Account authorization digest differs"); + } + this.selectedSourceBytes = + boundedBytes( + selectedSourceBytes, SelectedOwnerIntakeSourceContent.MAX_BYTES, "selectedSourceBytes"); + this.selectedSourceDigest = requireDigest(selectedSourceDigest, "selectedSourceDigest"); + if (!Arrays.equals( + this.selectedSourceBytes, this.authorizationBinding.content().canonicalBytes()) + || !this.selectedSourceDigest.equals(this.authorizationBinding.content().digest())) { + throw new IllegalArgumentException( + "Selected source differs from its original Account binding"); + } + this.inputs = + decodeInputs( + this.authorizationBinding, + worldReadRequestId, + worldReadRequestBytes, + worldReadRequestDigest, + worldClosureBytes, + worldClosureDigest); + this.selectedSourceRevisionBindingBytes = + boundedBytes( + selectedSourceRevisionBindingBytes, + 4 * 1024 * 1024, + "selectedSourceRevisionBindingBytes"); + this.selectedSourceRevisionBindingDigest = + requireDigest(selectedSourceRevisionBindingDigest, "selectedSourceRevisionBindingDigest"); + var sourceDeclaration = this.inputs.ownerSourceInventoryDeclaration(); + byte[] expectedRevisionBinding = sourceDeclaration.sourceBinding().canonicalBytes(); + if (!Arrays.equals(this.selectedSourceRevisionBindingBytes, expectedRevisionBinding) + || !this.selectedSourceRevisionBindingDigest.equals( + sourceDeclaration.sourceBinding().digest())) { + throw new IllegalArgumentException( + "Selected source revision binding differs from the original Game Design source"); + } + this.operationId = requireUuid(this.authorizationBinding.operationId(), "operationId"); + this.fenceId = requireUuid(this.authorizationBinding.fenceId(), "fenceId"); + this.intakeRequestId = + requireUuid(this.authorizationBinding.intakeRequestId(), "intakeRequestId"); + this.canonicalTenantId = requireUuid(this.authorizationBinding.tenantId(), "canonicalTenantId"); + this.canonicalVersionId = + requireUuid(this.authorizationBinding.versionId(), "canonicalVersionId"); + this.selectedCommitId = + requireUuid(this.authorizationBinding.selected().commitId(), "selectedCommitId"); + this.sourceRevisionId = requireUuid(sourceDeclaration.revisionId(), "sourceRevisionId"); + this.sourceRevisionOrder = + requireDecimal(sourceDeclaration.revisionOrder(), "sourceRevisionOrder"); + this.worldReadRequestId = requireUuid(worldReadRequestId, "worldReadRequestId"); + this.worldReadRequestBytes = + boundedBytes( + worldReadRequestBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES, + "worldReadRequestBytes"); + this.worldReadRequestDigest = requireDigest(worldReadRequestDigest, "worldReadRequestDigest"); + if (!DraftAuthorizationFenceBinding.digest(this.worldReadRequestBytes) + .equals(this.worldReadRequestDigest)) { + throw new IllegalArgumentException("Retained World read request digest differs"); + } + this.worldClosureBytes = + boundedBytes( + worldClosureBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES, + "worldClosureBytes"); + this.worldClosureDigest = requireDigest(worldClosureDigest, "worldClosureDigest"); + if (!this.inputs + .worldInventoryReadEvidence() + .inventory() + .digest() + .equals(this.worldClosureDigest)) { + throw new IllegalArgumentException("Retained World closure digest differs"); + } + if (!Arrays.equals( + this.inputs.worldInventoryReadEvidence().inventory().canonicalBytes(), + this.worldClosureBytes)) { + throw new IllegalArgumentException("Retained World closure bytes differ"); + } + this.familyStates = + requireAllEmptyStates( + familyStates, familyNames(sourceDeclaration.entityInventory().canonicalJson())); + this.schemaDigest = requireDigest(schemaDigest, "schemaDigest"); + if (!schemaDigest.equals( + schemaDigest(familyNames(sourceDeclaration.entityInventory().canonicalJson())))) { + throw new IllegalArgumentException("Entity source catalogue schema digest differs"); + } + requireSameNamespace(this.targetNamespace, this.authorizationBinding); + if (this.authorizationBinding.owner() != Owner.ENTITY_MANAGEMENT + || !this.authorizationBinding.schema().equals("account-entity-intake-authorization/v1") + || !this.authorizationBinding.purpose().equals("ENTITY_INTAKE_RETENTION")) { + throw new IllegalArgumentException("Exact original Entity Account authorization is required"); + } + this.retainedAt = Objects.requireNonNull(retainedAt, "retainedAt"); + if (retainedAt.getOffset().getTotalSeconds() != 0) { + throw new IllegalArgumentException("Receipt timestamp must use UTC"); + } + if (!this.requestDigest.equals( + requestDigest( + targetNamespace, + authorizationBinding, + this.inputs.worldInventoryReadEvidence().request().freezeEvidence()))) { + throw new IllegalArgumentException("Entity source intake request digest differs"); + } + this.canonicalBytes = encode(); + if (this.canonicalBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Entity source catalogue receipt exceeds its size limit"); + } + this.receiptDigest = DraftAuthorizationFenceBinding.digest(this.canonicalBytes); + } + + public static EntityEmptySelectedSourceIntakeReceipt create( + SelectedOwnerEmptySourceInputs inputs, + UUID genesisId, + long localTenantKey, + long localVersionKey, + String requestDigest, + List familyStates, + OffsetDateTime retainedAt) { + Objects.requireNonNull(inputs, "validated selected empty-source inputs are required"); + var binding = inputs.authorizationBinding(); + var worldEvidence = inputs.worldInventoryReadEvidence(); + byte[] worldReadRequest = + SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(worldEvidence.request()).toByteArray(); + byte[] sourceRevisionBinding = + inputs.ownerSourceInventoryDeclaration().sourceBinding().canonicalBytes(); + return new EntityEmptySelectedSourceIntakeReceipt( + binding.targetNamespace(), + genesisId, + localTenantKey, + localVersionKey, + requestDigest, + schemaDigest( + familyNames( + inputs.ownerSourceInventoryDeclaration().entityInventory().canonicalJson())), + binding.canonicalBytes(), + binding.digest(), + inputs.sourceContent().canonicalBytes(), + inputs.sourceContent().digest(), + sourceRevisionBinding, + inputs.ownerSourceInventoryDeclaration().sourceBinding().digest(), + worldEvidence.request().readRequestId(), + worldReadRequest, + DraftAuthorizationFenceBinding.digest(worldReadRequest), + worldEvidence.inventory().canonicalBytes(), + worldEvidence.inventory().digest(), + familyStates, + retainedAt); + } + + /** Decodes and fully revalidates the immutable canonical owner receipt. */ + public static EntityEmptySelectedSourceIntakeReceipt fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Stored Entity source catalogue receipt size is invalid"); + } + byte[] stored = bytes.clone(); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(DOMAIN); + if (!Integer.toString(SCHEMA_VERSION).equals(reader.text())) { + throw new IllegalArgumentException("Unsupported Entity source catalogue schema"); + } + String schemaDigest = reader.text(); + String namespace = reader.text(); + byte[] authorizationBindingBytes = reader.bytes(); + String authorizationBindingDigest = reader.text(); + byte[] selectedSourceBytes = reader.bytes(); + String selectedSourceDigest = reader.text(); + byte[] selectedSourceRevisionBindingBytes = reader.bytes(); + String selectedSourceRevisionBindingDigest = reader.text(); + byte[] worldReadRequestBytes = reader.bytes(); + String worldReadRequestDigest = reader.text(); + byte[] worldClosureBytes = reader.bytes(); + String worldClosureDigest = reader.text(); + long localTenantKey = parsePositiveLong(reader.text(), "localTenantKey"); + long localVersionKey = parsePositiveLong(reader.text(), "localVersionKey"); + int stateCount = parsePositiveInt(reader.text(), "familyStateCount"); + if (stateCount != 23) { + throw new IllegalArgumentException("Entity receipt must retain all 23 typed family states"); + } + var states = new ArrayList(stateCount); + for (int index = 0; index < stateCount; index++) { + states.add( + new FamilyCensus( + reader.text(), + FamilyState.valueOf(reader.text()), + FamilyEvidenceKind.valueOf(reader.text()), + parseNonnegativeLong(reader.text(), "rowCount"), + parseNonnegativeLong(reader.text(), "unqualifiedRowCount"), + parseNonnegativeLong(reader.text(), "retainedRowCount"), + parseNonnegativeLong(reader.text(), "selectedScopeRowCount"), + parseNonnegativeLong(reader.text(), "referenceCount"))); + } + UUID genesisId = parseUuid(reader.text(), "genesisId"); + String requestDigest = reader.text(); + UUID worldReadRequestId = parseUuid(reader.text(), "worldReadRequestId"); + OffsetDateTime retainedAt = parseTimestamp(reader.text()); + reader.requireEnd(); + var result = + new EntityEmptySelectedSourceIntakeReceipt( + namespace, + genesisId, + localTenantKey, + localVersionKey, + requestDigest, + schemaDigest, + authorizationBindingBytes, + authorizationBindingDigest, + selectedSourceBytes, + selectedSourceDigest, + selectedSourceRevisionBindingBytes, + selectedSourceRevisionBindingDigest, + worldReadRequestId, + worldReadRequestBytes, + worldReadRequestDigest, + worldClosureBytes, + worldClosureDigest, + states, + retainedAt); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical stored Entity source catalogue receipt"); + } + return result; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID genesisId() { + return genesisId; + } + + public UUID operationId() { + return operationId; + } + + public UUID fenceId() { + return fenceId; + } + + public UUID intakeRequestId() { + return intakeRequestId; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public UUID selectedCommitId() { + return selectedCommitId; + } + + public UUID sourceRevisionId() { + return sourceRevisionId; + } + + public String sourceRevisionOrder() { + return sourceRevisionOrder; + } + + public long localTenantKey() { + return localTenantKey; + } + + public long localVersionKey() { + return localVersionKey; + } + + public String requestDigest() { + return requestDigest; + } + + public String schemaDigest() { + return schemaDigest; + } + + public String authorizationBindingDigest() { + return authorizationBindingDigest; + } + + public byte[] authorizationBindingBytes() { + return authorizationBindingBytes.clone(); + } + + public String selectedSourceDigest() { + return selectedSourceDigest; + } + + public String selectedSourceRevisionBindingDigest() { + return selectedSourceRevisionBindingDigest; + } + + public byte[] selectedSourceBytes() { + return selectedSourceBytes.clone(); + } + + public UUID worldReadRequestId() { + return worldReadRequestId; + } + + public String worldReadRequestDigest() { + return worldReadRequestDigest; + } + + public byte[] worldReadRequestBytes() { + return worldReadRequestBytes.clone(); + } + + public String worldClosureDigest() { + return worldClosureDigest; + } + + public byte[] worldClosureBytes() { + return worldClosureBytes.clone(); + } + + /** Digest of one persisted EMPTY-only provider row, bound to this exact retained source. */ + public String providerStateDigest(String family) { + if (evidenceKindForFamily(family) != FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER) { + throw new IllegalArgumentException("Family is not backed by an EMPTY-only Entity provider"); + } + var out = new ByteArrayOutputStream(); + frame(out, "entity-empty-only-family-provider-state/v1"); + frame(out, Integer.toString(SCHEMA_VERSION)); + frame(out, targetNamespace); + frame(out, authorizationBindingBytes); + frame(out, authorizationBindingDigest); + frame(out, selectedSourceBytes); + frame(out, selectedSourceDigest); + frame(out, selectedSourceRevisionBindingBytes); + frame(out, selectedSourceRevisionBindingDigest); + frame(out, worldClosureBytes); + frame(out, worldClosureDigest); + frame(out, Long.toString(localTenantKey)); + frame(out, Long.toString(localVersionKey)); + frame(out, genesisId.toString()); + frame(out, family); + frame(out, "providerSchemaVersion=1"); + frame(out, FamilyState.EMPTY.name()); + frame(out, "rowCount=0"); + frame(out, "referenceCount=0"); + return DraftAuthorizationFenceBinding.digest(out.toByteArray()); + } + + public List familyStates() { + return List.copyOf(familyStates); + } + + public OffsetDateTime retainedAt() { + return retainedAt; + } + + public String receiptDigest() { + return receiptDigest; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String outcome() { + return "COMMITTED_EMPTY"; + } + + public String sourceParticipationDisposition() { + return "PENDING_OWNER_TERMINAL_SETTLEMENT"; + } + + public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + return authorizationBinding; + } + + public SelectedOwnerEmptySourceInputs inputs() { + return inputs; + } + + public void requireSameRequest( + String namespace, + SelectedOwnerIntakeAuthorizationBinding candidateBinding, + WorldSelectedDraftPublicationFreezeEvidence candidateFreeze) { + Objects.requireNonNull(candidateBinding, "candidate Account binding is required"); + Objects.requireNonNull(candidateFreeze, "candidate World freeze is required"); + if (!targetNamespace.equals(namespace) + || !requestDigest.equals(requestDigest(namespace, candidateBinding, candidateFreeze)) + || !Arrays.equals(authorizationBindingBytes, candidateBinding.canonicalBytes()) + || !inputs + .worldInventoryReadEvidence() + .request() + .freezeEvidence() + .equals(candidateFreeze)) { + throw new IllegalStateException( + "Entity source request identity already records different selected evidence"); + } + } + + public void requireSameInputs(SelectedOwnerEmptySourceInputs candidate) { + Objects.requireNonNull(candidate, "validated selected empty-source inputs are required"); + requireSameRequest( + candidate.authorizationBinding().targetNamespace(), + candidate.authorizationBinding(), + candidate.worldInventoryReadEvidence().request().freezeEvidence()); + if (!Arrays.equals( + worldClosureBytes, candidate.worldInventoryReadEvidence().inventory().canonicalBytes()) + || !worldClosureDigest.equals(candidate.worldInventoryReadEvidence().inventory().digest()) + || !Arrays.equals(selectedSourceBytes, candidate.sourceContent().canonicalBytes()) + || !selectedSourceDigest.equals(candidate.sourceContent().digest())) { + throw new IllegalStateException( + "Entity exact retry changed selected source or World closure"); + } + } + + /** Stable request identity; the fresh World read correlation is intentionally excluded. */ + public static String requestDigest( + String namespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + requireText(namespace, "targetNamespace"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + var out = new ByteArrayOutputStream(); + frame(out, "entity-selected-empty-source-catalogue-request/v1"); + frame(out, namespace); + frame(out, binding.canonicalBytes()); + frame( + out, + net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec + .toRequest(freezeEvidence.request()) + .toByteArray()); + frame( + out, + net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec + .toResponse(freezeEvidence.acknowledgement()) + .toByteArray()); + return DraftAuthorizationFenceBinding.digest(out.toByteArray()); + } + + public static String schemaDigest(String canonicalEntityDeclaration) { + return schemaDigest(familyNames(canonicalEntityDeclaration)); + } + + private byte[] encode() { + var out = new ByteArrayOutputStream(); + frame(out, DOMAIN); + frame(out, Integer.toString(SCHEMA_VERSION)); + frame(out, schemaDigest); + frame(out, targetNamespace); + frame(out, authorizationBindingBytes); + frame(out, authorizationBindingDigest); + frame(out, selectedSourceBytes); + frame(out, selectedSourceDigest); + frame(out, selectedSourceRevisionBindingBytes); + frame(out, selectedSourceRevisionBindingDigest); + frame(out, worldReadRequestBytes); + frame(out, worldReadRequestDigest); + frame(out, worldClosureBytes); + frame(out, worldClosureDigest); + frame(out, Long.toString(localTenantKey)); + frame(out, Long.toString(localVersionKey)); + frame(out, Integer.toString(familyStates.size())); + for (FamilyCensus state : familyStates) { + frame(out, state.family()); + frame(out, state.state().name()); + frame(out, state.evidenceKind().name()); + frame(out, Long.toString(state.rowCount())); + frame(out, Long.toString(state.unqualifiedRowCount())); + frame(out, Long.toString(state.retainedRowCount())); + frame(out, Long.toString(state.selectedScopeRowCount())); + frame(out, Long.toString(state.referenceCount())); + } + frame(out, genesisId.toString()); + frame(out, requestDigest); + frame(out, worldReadRequestId.toString()); + frame(out, retainedAt.toString()); + return out.toByteArray(); + } + + private static SelectedOwnerEmptySourceInputs decodeInputs( + SelectedOwnerIntakeAuthorizationBinding binding, + UUID readRequestId, + byte[] requestBytes, + String requestDigest, + byte[] closureBytes, + String closureDigest) { + UUID checkedRequestId = requireUuid(readRequestId, "worldReadRequestId"); + byte[] boundedRequest = + boundedBytes( + requestBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES, + "worldReadRequestBytes"); + if (!DraftAuthorizationFenceBinding.digest(boundedRequest) + .equals(requireDigest(requestDigest, "worldReadRequestDigest"))) { + throw new IllegalArgumentException("Retained World read request digest differs"); + } + final ReadSelectedOwnerWorldInventoryRequest requestMessage; + try { + requestMessage = ReadSelectedOwnerWorldInventoryRequest.parseFrom(boundedRequest); + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("Retained World read request is malformed", invalid); + } + if (!Arrays.equals(boundedRequest, requestMessage.toByteArray())) { + throw new IllegalArgumentException("Retained World read request is not canonical"); + } + var request = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(requestMessage); + if (!request.readRequestId().equals(checkedRequestId) + || !request.targetNamespace().equals(binding.targetNamespace()) + || !Arrays.equals( + binding.canonicalBytes(), request.authorizationBinding().canonicalBytes())) { + throw new IllegalArgumentException( + "Retained World request differs from original Entity binding"); + } + byte[] boundedClosure = + boundedBytes( + closureBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES, + "worldClosureBytes"); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + request.freezeEvidence(), + boundedClosure, + requireDigest(closureDigest, "worldClosureDigest")); + return new SelectedOwnerEmptySourceInputs( + binding, new SelectedOwnerWorldInventoryReadEvidence(request, inventory)); + } + + private static List requireAllEmptyStates( + List states, List expectedFamilies) { + List copy = List.copyOf(Objects.requireNonNull(states, "familyStates")); + if (expectedFamilies.size() != 23 || copy.size() != expectedFamilies.size()) { + throw new IllegalArgumentException("All 23 Entity owner family states are required"); + } + for (int index = 0; index < expectedFamilies.size(); index++) { + FamilyCensus state = copy.get(index); + if (!expectedFamilies.get(index).equals(state.family()) + || state.state() != FamilyState.EMPTY) { + throw new IllegalArgumentException( + "Entity family states must be complete, ordered, and explicitly EMPTY"); + } + } + return copy; + } + + public static List familyNames(String canonicalDeclaration) { + try { + var root = JSON.readTree(canonicalDeclaration); + var families = root.get("families"); + if (families == null || !families.isObject()) { + throw new IllegalArgumentException("Typed Entity family declaration is required"); + } + var names = new ArrayList(); + families.properties().forEach(property -> names.add(property.getKey())); + names.sort(String::compareTo); + if (names.size() != 23) { + throw new IllegalArgumentException("Typed Entity declaration must provide all 23 families"); + } + return List.copyOf(names); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Entity family order could not be derived from its typed declaration", malformed); + } + } + + private static String schemaDigest(List familyNames) { + var out = new ByteArrayOutputStream(); + frame(out, "entity-selected-empty-source-catalogue-schema/v1"); + frame(out, DOMAIN); + frame(out, Integer.toString(SCHEMA_VERSION)); + frame(out, "encoding=ADR-0047-byte-length-frames;strings=UTF-8;counts=canonical-decimal"); + for (String field : + List.of( + "targetNamespace:utf8", + "authorizationBindingBytes:canonical-original-account-binding", + "authorizationBindingDigest:sha256", + "selectedSourceBytes:canonical-game-design-source-content", + "selectedSourceDigest:sha256", + "selectedSourceRevisionBindingBytes:canonical-game-design-source-operation-binding", + "selectedSourceRevisionBindingDigest:sha256", + "worldReadRequestBytes:canonical-recipient-qualified-world-request", + "worldReadRequestDigest:sha256", + "worldClosureBytes:canonical-public-world-inventory", + "worldClosureDigest:sha256", + "localTenantKey:positive-canonical-decimal", + "localVersionKey:positive-canonical-decimal", + "familyStates:count-then-23-lexical-family-records-with-provider-kind", + "genesisId:canonical-uuid", + "requestDigest:sha256", + "worldReadRequestId:canonical-uuid", + "retainedAt:canonical-utc-offset-date-time")) { + frame(out, field); + } + frame( + out, + "familyRecordFields=count-then-family,state,evidenceKind,rowCount,unqualifiedRowCount,retainedRowCount,selectedScopeRowCount,referenceCount"); + frame(out, "family:utf8"); + frame(out, "state=EMPTY"); + frame(out, "evidenceKind=V1_SOURCE_CENSUS|EMPTY_ONLY_OWNER_PROVIDER"); + frame(out, "rowCount:canonical-nonnegative-decimal"); + frame(out, "unqualifiedRowCount:canonical-nonnegative-decimal"); + frame(out, "retainedRowCount:canonical-nonnegative-decimal"); + frame(out, "selectedScopeRowCount:canonical-nonnegative-decimal"); + frame(out, "referenceCount:canonical-nonnegative-decimal"); + frame(out, Integer.toString(familyNames.size())); + for (String family : familyNames) frame(out, family); + return DraftAuthorizationFenceBinding.digest(out.toByteArray()); + } + + private static String requireSameNamespace( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + if (!namespace.equals(binding.targetNamespace())) { + throw new IllegalArgumentException("Entity authorization namespace differs"); + } + return namespace; + } + + private static FamilyEvidenceKind evidenceKindForFamily(String family) { + return switch (family) { + case "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS" -> + FamilyEvidenceKind.V1_SOURCE_CENSUS; + case "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "INBOUND_LOOT_BINDINGS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS" -> + FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER; + default -> throw new IllegalArgumentException("Unsupported Entity family: " + family); + }; + } + + private static String requireText(String value, String label) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException(label + " is required"); + } + return value; + } + + private static String requireDigest(String value, String label) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be canonical SHA-256"); + } + return value; + } + + private static byte[] boundedBytes(byte[] value, int max, String label) { + if (value == null || value.length == 0 || value.length > max) { + throw new IllegalArgumentException(label + " is absent or exceeds its limit"); + } + return value.clone(); + } + + private static UUID requireUuid(UUID value, String label) { + DraftAuthorizationFenceBinding.requireUuid(value); + return value; + } + + private static UUID parseUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) throw new IllegalArgumentException("Noncanonical UUID"); + return requireUuid(parsed, label); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(label + " must be a canonical nonzero UUID", invalid); + } + } + + private static String requireDecimal(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, true); + return value; + } + + private static long parsePositiveLong(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, false); + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal"); + } + return parsed; + } + + private static long parseNonnegativeLong(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, true); + long parsed = Long.parseLong(value); + if (parsed < 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal"); + } + return parsed; + } + + private static int parsePositiveInt(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, false); + int parsed = Integer.parseInt(value); + if (parsed <= 0 || !Integer.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal"); + } + return parsed; + } + + private static OffsetDateTime parseTimestamp(String value) { + final OffsetDateTime parsed; + try { + parsed = OffsetDateTime.parse(value); + } catch (DateTimeParseException malformed) { + throw new IllegalArgumentException("Receipt timestamp must be canonical UTC", malformed); + } + if (parsed.getOffset().getTotalSeconds() != 0 || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Receipt timestamp must be canonical UTC"); + } + return parsed; + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + public enum FamilyState { + EMPTY + } + + /** Distinguishes source census from a newly persisted fresh-only owner state. */ + public enum FamilyEvidenceKind { + V1_SOURCE_CENSUS, + EMPTY_ONLY_OWNER_PROVIDER + } + + /** Actual owner-local census and reference counts captured under the source-table guard. */ + public record FamilyCensus( + String family, + FamilyState state, + FamilyEvidenceKind evidenceKind, + long rowCount, + long unqualifiedRowCount, + long retainedRowCount, + long selectedScopeRowCount, + long referenceCount) { + public FamilyCensus { + requireText(family, "family"); + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(evidenceKind, "evidenceKind"); + if (evidenceKindForFamily(family) != evidenceKind) { + throw new IllegalArgumentException("Entity family evidence kind differs from its provider"); + } + if (rowCount < 0L + || unqualifiedRowCount < 0L + || retainedRowCount < 0L + || selectedScopeRowCount < 0L + || referenceCount < 0L) { + throw new IllegalArgumentException("Entity family census counts must be nonnegative"); + } + if (state == FamilyState.EMPTY + && (rowCount != 0L + || unqualifiedRowCount != 0L + || retainedRowCount != 0L + || selectedScopeRowCount != 0L + || referenceCount != 0L)) { + throw new IllegalArgumentException("An EMPTY Entity family must have a zero owner census"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadClient.java new file mode 100644 index 0000000000..c6969746a6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +/** Transport boundary for reading Entity's exact original selected-source terminal. */ +public interface EntitySelectedSourceIntakeTerminalReadClient { + EntitySelectedSourceIntakeTerminalReadEvidence read( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java new file mode 100644 index 0000000000..826c228781 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact lookup correlation and the original committed Entity receipt. */ +public record EntitySelectedSourceIntakeTerminalReadEvidence( + Request request, EntityEmptySelectedSourceIntakeReceipt receipt) { + public static final int SCHEMA_VERSION = 1; + public static final String TERMINAL_READ_PURPOSE = "ENTITY_INTAKE_TERMINAL_READ"; + + public EntitySelectedSourceIntakeTerminalReadEvidence { + Objects.requireNonNull(request, "terminal-read request is required"); + Objects.requireNonNull(receipt, "committed Entity receipt is required"); + if (!request.targetNamespace().equals(receipt.targetNamespace()) + || !Arrays.equals(request.binding().canonicalBytes(), receipt.authorizationBindingBytes()) + || !"COMMITTED_EMPTY".equals(receipt.outcome())) { + throw new IllegalArgumentException( + "Entity receipt differs from the complete original terminal-read binding"); + } + } + + /** The correlation changes per transport read and never changes the retained operation. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || binding == null + || !targetNamespace.equals(binding.targetNamespace()) + || binding.owner() != Owner.ENTITY_MANAGEMENT + || !"account-entity-intake-authorization/v1".equals(binding.schema()) + || !"ENTITY_INTAKE_RETENTION".equals(binding.purpose()) + || binding.canonicalBytes().length == 0 + || binding.canonicalBytes().length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if (collides(readRequestId, binding)) throw invalid(); + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + Objects.requireNonNull(binding, "original finalized Account binding is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (collides(correlation, binding)); + return new Request(SCHEMA_VERSION, namespace, correlation, binding); + } + + /** Account is the only intended reader of this Entity-owned terminal. */ + public String intendedReader() { + return "spiffe://firemud/ns/" + targetNamespace + "/sa/account-service"; + } + + public String terminalReadPurpose() { + return TERMINAL_READ_PURPOSE; + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && readRequestId.equals(other.readRequestId) + && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + } + + private static boolean collides( + UUID candidate, SelectedOwnerIntakeAuthorizationBinding binding) { + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Entity selected-source terminal request"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..c205600c49 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodec.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +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.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalResult; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; + +/** Closed terminal mapping with an unchanged request echo and canonical receipt validation. */ +public final class EntitySelectedSourceIntakeTerminalReadGrpcCodec { + private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024; + + /** Full receipt plus the complete echoed 16 MiB Account binding and bounded protobuf framing. */ + public static final int MAX_REQUEST_WIRE_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + MAX_REQUEST_FRAMING_BYTES; + + public static final int MAX_WIRE_BYTES = + EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + MAX_REQUEST_WIRE_BYTES; + + private EntitySelectedSourceIntakeTerminalReadGrpcCodec() {} + + public static ReadSelectedSourceIntakeTerminalRequest toRequest( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "terminal-read request is required"); + byte[] bindingBytes = request.binding().canonicalBytes(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Entity authorization exceeds its 16 MiB limit"); + } + var wire = + ReadSelectedSourceIntakeTerminalRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setTerminalReadPurpose(request.terminalReadPurpose()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize(), MAX_REQUEST_WIRE_BYTES, "request"); + return wire; + } + + public static EntitySelectedSourceIntakeTerminalReadEvidence.Request fromRequest( + ReadSelectedSourceIntakeTerminalRequest wire) { + requireKnownAndWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getReadRequestId()); + byte[] bindingBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Entity authorization size is invalid"); + } + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original Entity authorization digest differs"); + } + var request = + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getReadRequestId()), + binding); + if (!request.intendedReader().equals(wire.getIntendedReader()) + || !request.terminalReadPurpose().equals(wire.getTerminalReadPurpose()) + || !toRequest(request).equals(wire)) { + throw invalid("Terminal reader, purpose, or request differs"); + } + return request; + } + + public static ReadSelectedSourceIntakeTerminalResponse toResponse( + EntitySelectedSourceIntakeTerminalReadEvidence evidence) { + Objects.requireNonNull(evidence, "committed Entity terminal evidence is required"); + byte[] receiptBytes = evidence.receipt().canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Committed Entity receipt size is invalid"); + } + var response = + ReadSelectedSourceIntakeTerminalResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setResult( + EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY) + .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes)) + .setReceiptDigest(evidence.receipt().receiptDigest()) + .build(); + requireWithinBudget(response.getSerializedSize(), MAX_WIRE_BYTES, "response"); + return response; + } + + public static EntitySelectedSourceIntakeTerminalReadEvidence fromResponse( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request, + ReadSelectedSourceIntakeTerminalResponse response) { + Objects.requireNonNull(request, "terminal-read request is required"); + requireKnownAndWithinBudget(response, MAX_WIRE_BYTES, "response"); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || response.getResult() + != EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY) { + throw invalid("Exact COMMITTED_EMPTY response and full request echo required"); + } + byte[] receiptBytes = response.getCommittedEmptyReceipt().toByteArray(); + if (receiptBytes.length == 0 + || receiptBytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Missing or oversized committed Entity receipt"); + } + EntityEmptySelectedSourceIntakeReceipt receipt = + EntityEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + if (!receipt.receiptDigest().equals(response.getReceiptDigest())) { + throw invalid("Entity receipt digest differs"); + } + return new EntitySelectedSourceIntakeTerminalReadEvidence(request, receipt); + } + + private static void requireKnownAndWithinBudget(Message wire, int maxBytes, String label) { + if (wire == null || wire.getSerializedSize() > maxBytes) { + throw invalid("Missing or oversized Entity terminal-read " + label); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown Entity terminal-read " + label + " fields"); + } + } + + private static void requireWithinBudget(int size, int maxBytes, String label) { + if (size > maxBytes) { + throw invalid("Entity terminal-read " + label + " exceeds its derived 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/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java new file mode 100644 index 0000000000..ddaa70d439 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java @@ -0,0 +1,162 @@ +package net.firedevops.firemud.common.entity.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.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; +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; + +/** File-backed mTLS client for Entity's exact original selected-source terminal read. */ +public final class GrpcEntitySelectedSourceIntakeTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceBlockingStub> + implements EntitySelectedSourceIntakeTerminalReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcEntitySelectedSourceIntakeTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcEntitySelectedSourceIntakeTerminalReadClient.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("Entity terminal-read client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Entity terminal-read stub unavailable"); + } + initialized = true; + } + + /** Returns only an exact original COMMITTED_EMPTY receipt, outside owner SQL. */ + @Override + public EntitySelectedSourceIntakeTerminalReadEvidence read( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Entity terminal read must run outside owner SQL"); + } + Objects.requireNonNull(request, "terminal-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Entity terminal read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedSourceIntakeTerminal( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); + try { + return EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Entity returned invalid terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service"; + return EntitySelectedSourceIntakeTerminalReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.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 EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Entity terminal-read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Entity terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Entity terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Entity terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Entity terminal read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Entity terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadClient.java new file mode 100644 index 0000000000..f164ab8e1f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.publication; + +/** Authenticated read of the exact retained World inventory for selected owner intake. */ +public interface SelectedOwnerWorldInventoryReadClient { + SelectedOwnerWorldInventoryReadEvidence read( + SelectedOwnerWorldInventoryReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadEvidence.java new file mode 100644 index 0000000000..15a38719d8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadEvidence.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.common.publication; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact read correlation and public inventory for an Entity or Automation intake. */ +public record SelectedOwnerWorldInventoryReadEvidence( + Request request, WorldSelectedPublicationArtifactInventoryEvidence inventory) { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_INTAKE_AUTHORIZATION_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES; + public static final int MAX_PUBLIC_INVENTORY_BYTES = 8 * 1024 * 1024; + + /** Includes the 16 MiB owner binding, duplicated bounded freeze order, inventory, and framing. */ + public static final int MAX_WIRE_BYTES = 32 * 1024 * 1024; + + public SelectedOwnerWorldInventoryReadEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(inventory, "inventory"); + if (!request.freezeEvidence().equals(inventory.freezeEvidence()) + || inventory.canonicalBytes().length == 0 + || inventory.canonicalBytes().length > MAX_PUBLIC_INVENTORY_BYTES) { + throw new IllegalArgumentException( + "World owner inventory differs from exact bounded request"); + } + } + + /** A new read UUID is independent from both Account intake and World intake correlations. */ + public static Request create( + String namespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (Request.collides(readRequestId, binding, freezeEvidence)); + return new Request(SCHEMA_VERSION, namespace, readRequestId, binding, freezeEvidence); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding authorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || readRequestId == null + || new UUID(0L, 0L).equals(readRequestId)) { + throw new IllegalArgumentException("Canonical selected-owner World read identity required"); + } + Objects.requireNonNull(authorizationBinding, "authorizationBinding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + var scope = authorizationBinding.content().scope(); + var freeze = freezeEvidence.request(); + var selected = freeze.accountBinding().input().selection().selectedCommit(); + var publicationBinding = freeze.accountBinding(); + if (!targetNamespace.equals(scope.targetNamespace()) + || !targetNamespace.equals(freeze.targetNamespace()) + || !scope.selected().target().canonicalTenantId().equals(freeze.canonicalTenantId()) + || !scope.selected().target().canonicalVersionId().equals(freeze.canonicalVersionId()) + || !java.util.Arrays.equals(scope.selected().canonicalBytes(), selected.canonicalBytes()) + || collides(readRequestId, authorizationBinding, freezeEvidence) + || readRequestId.equals(publicationBinding.operationId()) + || readRequestId.equals(publicationBinding.fenceId())) { + throw new IllegalArgumentException( + "Selected-owner source binding differs from exact World freeze selection"); + } + String expectedPurpose = + authorizationBinding.owner() == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_RETENTION" + : "AUTOMATION_INTAKE_RETENTION"; + if (!authorizationBinding.purpose().equals(expectedPurpose) + || !authorizationBinding + .intendedReader() + .equals(ownerIntendedReader(authorizationBinding.owner(), targetNamespace))) { + throw new IllegalArgumentException( + "Original selected-owner recipient or retention purpose differs"); + } + if (authorizationBinding.canonicalBytes().length > MAX_INTAKE_AUTHORIZATION_BYTES) { + throw new IllegalArgumentException("Selected-owner authorization binding exceeds limit"); + } + } + + public static Request create( + String namespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + return SelectedOwnerWorldInventoryReadEvidence.create(namespace, binding, freezeEvidence); + } + + public String closureReadPurpose() { + return authorizationBinding.owner() == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"; + } + + private static String ownerIntendedReader(Owner owner, String namespace) { + String workload = + owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + return "spiffe://firemud/ns/" + namespace + "/sa/" + workload; + } + + private static boolean collides( + UUID candidate, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var account = freezeEvidence.request().accountBinding(); + var acknowledgement = freezeEvidence.acknowledgement(); + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()) + || candidate.equals(account.operationId()) + || candidate.equals(account.fenceId()) + || candidate.equals(acknowledgement.intakeRequestId()) + || candidate.equals(acknowledgement.publicationFence()); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java new file mode 100644 index 0000000000..44b36cf560 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java @@ -0,0 +1,180 @@ +package net.firedevops.firemud.common.publication; + +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.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryResponse; + +/** Closed wire mapping for the bounded recipient-specific World inventory read. */ +public final class SelectedOwnerWorldInventoryReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private SelectedOwnerWorldInventoryReadGrpcCodec() {} + + public static ReadSelectedOwnerWorldInventoryRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var freeze = request.freezeEvidence(); + var result = + ReadSelectedOwnerWorldInventoryRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom(request.authorizationBinding().canonicalBytes())) + .setIntakeAuthorizationDigest(request.authorizationBinding().digest()) + .setFreezeRequest( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())) + .setFreezeAcknowledgement( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())) + .setIntendedReader(request.authorizationBinding().intendedReader()) + .setClosureReadPurpose(request.closureReadPurpose()) + .build(); + requireWireSize(result.getSerializedSize()); + return result; + } + + /** Decode only after the receiver has authenticated an allowed owner peer. */ + public static Request fromRequest(ReadSelectedOwnerWorldInventoryRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize(request.getSerializedSize()); + requireNoUnknownFields(request, "ReadSelectedOwnerWorldInventoryRequest"); + if (request.getSchemaVersion() != SelectedOwnerWorldInventoryReadEvidence.SCHEMA_VERSION + || request.getTargetNamespace().isEmpty()) { + throw invalid("Canonical selected-owner World inventory read identity is required"); + } + UUID readRequestId = canonicalUuid(request.getReadRequestId(), "readRequestId"); + byte[] bindingBytes = request.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length + > SelectedOwnerWorldInventoryReadEvidence.MAX_INTAKE_AUTHORIZATION_BYTES) { + throw invalid("Selected-owner authorization binding is absent or oversized"); + } + SelectedOwnerIntakeAuthorizationBinding binding; + try { + binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + } catch (RuntimeException invalidBinding) { + throw invalid("Selected-owner authorization binding is invalid", invalidBinding); + } + if (!binding.digest().equals(request.getIntakeAuthorizationDigest())) { + throw invalid("Selected-owner authorization binding digest differs"); + } + if (!binding.intendedReader().equals(request.getIntendedReader())) { + throw invalid("Original selected-owner recipient differs"); + } + String expectedPurpose = + binding.owner() == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"; + if (!expectedPurpose.equals(request.getClosureReadPurpose())) { + throw invalid("Selected-owner World closure read purpose differs"); + } + if (!request.hasFreezeRequest() || !request.hasFreezeAcknowledgement()) { + throw invalid("Complete selected-owner World inventory freeze evidence is required"); + } + var freezeRequest = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(request.getFreezeRequest()); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, request.getFreezeAcknowledgement()); + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + readRequestId, + binding, + freezeEvidence); + } + + public static ReadSelectedOwnerWorldInventoryResponse toResponse( + Request request, WorldSelectedPublicationArtifactInventoryEvidence inventory) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(inventory, "inventory"); + if (!request.freezeEvidence().equals(inventory.freezeEvidence())) { + throw invalid("World inventory is not bound to the exact selected-owner freeze"); + } + byte[] inventoryBytes = inventory.canonicalBytes(); + if (inventoryBytes.length == 0 + || inventoryBytes.length + > SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES) { + throw invalid("World public inventory is absent or exceeds the recipient-read limit"); + } + var response = + ReadSelectedOwnerWorldInventoryResponse.newBuilder() + .setSchemaVersion(SelectedOwnerWorldInventoryReadEvidence.SCHEMA_VERSION) + .setRequest(toRequest(request)) + .setCanonicalPublicInventory(ByteString.copyFrom(inventoryBytes)) + .setPublicInventoryDigest(inventory.digest()) + .build(); + requireWireSize(response.getSerializedSize()); + return response; + } + + /** Requires the exact echoed request, then validates the existing typed inventory codec. */ + public static SelectedOwnerWorldInventoryReadEvidence fromResponse( + Request expected, ReadSelectedOwnerWorldInventoryResponse response) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(response, "response"); + requireWireSize(response.getSerializedSize()); + requireNoUnknownFields(response, "ReadSelectedOwnerWorldInventoryResponse"); + if (response.getSchemaVersion() != SelectedOwnerWorldInventoryReadEvidence.SCHEMA_VERSION + || !response.hasRequest() + || !response.getRequest().equals(toRequest(expected))) { + throw invalid("World changed the exact selected-owner inventory read request"); + } + requireNoUnknownFields(response.getRequest(), "echoed ReadSelectedOwnerWorldInventoryRequest"); + byte[] inventoryBytes = response.getCanonicalPublicInventory().toByteArray(); + if (inventoryBytes.length == 0 + || inventoryBytes.length + > SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES + || response.getPublicInventoryDigest().isEmpty()) { + throw invalid("World response lacks a complete bounded public inventory"); + } + var inventoryResponse = + ReadSelectedPublicationArtifactInventoryResponse.newBuilder() + .setSchemaVersion(1) + .setCanonicalPublicInventory(ByteString.copyFrom(inventoryBytes)) + .setPublicInventoryDigest(response.getPublicInventoryDigest()) + .build(); + var inventory = + WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + expected.freezeEvidence(), inventoryResponse); + return new SelectedOwnerWorldInventoryReadEvidence(expected, inventory); + } + + private static UUID canonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw invalid(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(label + " must be a canonical non-nil UUID", malformed); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid(label + " contains unsupported fields"); + } + } + + private static void requireWireSize(int size) { + if (size > SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES) { + throw invalid("Selected-owner World inventory message exceeds its wire limit"); + } + } + + 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/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java new file mode 100644 index 0000000000..8210b16b0d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedOwnerInventoryReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for the recipient-specific retained World inventory read. */ +public final class WorldSelectedOwnerInventoryGrpcClient + extends AbstractReloadingBlockingGrpcClient< + WorldSelectedOwnerInventoryReadServiceGrpc + .WorldSelectedOwnerInventoryReadServiceBlockingStub> + implements SelectedOwnerWorldInventoryReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldSelectedOwnerInventoryGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldSelectedOwnerInventoryGrpcClient.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("World owner inventory client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World owner inventory stub unavailable"); + } + initialized = true; + } + + @Override + public SelectedOwnerWorldInventoryReadEvidence read( + SelectedOwnerWorldInventoryReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World owner inventory read requires no ambient SQL"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException("World owner inventory namespace differs from client"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedOwnerWorldInventory( + SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(request)); + try { + return SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("World returned invalid owner inventory evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldSelectedOwnerInventoryReadServiceGrpc + .WorldSelectedOwnerInventoryReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldSelectedOwnerInventoryReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(SelectedOwnerWorldInventoryReadEvidence.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 WorldSelectedOwnerInventoryReadServiceGrpc + .WorldSelectedOwnerInventoryReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException("World owner inventory client is not initialized"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World owner inventory read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World owner inventory read requires file-backed TLS files"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World owner inventory read requires file-backed TLS files"); + } + Path path = Path.of(pathText); + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World owner inventory read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java new file mode 100644 index 0000000000..d263141833 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountSelectedOwnerIntakeAuthorizationGrpcClientTest { + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedWorkloadMtlsAndCanonicalNamespace() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, plaintext, new GrpcChannelFactory(), "test")) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) + .isInstanceOf(IllegalArgumentException.class); + + var properties = tlsFiles(); + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, properties, new GrpcChannelFactory(), "not/a/namespace")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsRemoteReadWithAmbientSqlOrSynchronizationBeforeChannelUse() throws IOException { + var client = + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + new ServiceEndpointsProperties(), tlsFiles(), new GrpcChannelFactory(), "test"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(null)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(null)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + client.close(); + } + + private CommonGrpcClientProperties tlsFiles() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(file("client.crt").toString()); + properties.setPrivateKey(file("client.key").toString()); + properties.setCaCert(file("ca.crt").toString()); + return properties; + } + + private Path file(String name) { + Path path = temporaryDirectory.resolve(name); + try { + return Files.createFile(path); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java new file mode 100644 index 0000000000..22735d97ef --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java @@ -0,0 +1,154 @@ +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.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import org.junit.jupiter.api.Test; + +/** Synthetic upstream value tests; mocks make no Account or Automation authentication claim. */ +class AccountSelectedOwnerIntakeSettlementReceiptTest { + private static final byte[] BINDING_BYTES = {1, 2, 3, 4}; + private static final String BINDING_DIGEST = DraftAuthorizationFenceBinding.digest(BINDING_BYTES); + private static final byte[] OWNER_RECEIPT_BYTES = {5, 6, 7}; + private static final String OWNER_RECEIPT_DIGEST = + DraftAuthorizationFenceBinding.digest(OWNER_RECEIPT_BYTES); + + @Test + void embedsCompleteImmutableEvidenceAndIgnoresOnlyFreshReadCorrelation() { + var binding = binding(); + var ownerReceipt = ownerReceipt(OWNER_RECEIPT_BYTES, OWNER_RECEIPT_DIGEST); + var firstEvidence = evidence(binding, ownerReceipt); + var first = AccountSelectedOwnerIntakeSettlementReceipt.create(firstEvidence); + + var reader = new DraftAuthorizationFenceBinding.FrameReader(first.canonicalBytes()); + reader.expect(AccountSelectedOwnerIntakeSettlementReceipt.DOMAIN); + reader.expect("1"); + assertThat(reader.bytes()).containsExactly(BINDING_BYTES); + reader.expect(BINDING_DIGEST); + reader.expect("1"); + reader.expect("test"); + String firstReadRequestId = reader.text(); + reader.expect("spiffe://firemud/ns/test/sa/account-service"); + reader.expect("AUTOMATION_INTAKE_TERMINAL_READ"); + assertThat(reader.bytes()).containsExactly(BINDING_BYTES); + reader.expect(BINDING_DIGEST); + assertThat(reader.bytes()).containsExactly(OWNER_RECEIPT_BYTES); + reader.expect(OWNER_RECEIPT_DIGEST); + reader.requireEnd(); + + var retryEvidence = evidence(binding, ownerReceipt); + var retried = AccountSelectedOwnerIntakeSettlementReceipt.create(retryEvidence); + assertThat(retryEvidence.request().readRequestId().toString()).isNotEqualTo(firstReadRequestId); + assertThat(first.sameImmutableOwnerReceipt(retryEvidence)).isTrue(); + assertThat(retried.canonicalBytes()).isNotEqualTo(first.canonicalBytes()); + + var changedOwnerReceipt = + ownerReceipt( + new byte[] {8, 9, 10}, DraftAuthorizationFenceBinding.digest(new byte[] {8, 9, 10})); + assertThat(first.sameImmutableOwnerReceipt(evidence(binding, changedOwnerReceipt))).isFalse(); + + byte[] exposed = first.canonicalBytes(); + exposed[0] ^= 0x7f; + assertThat(first.canonicalBytes()).isNotEqualTo(exposed); + assertThatThrownBy(() -> AccountSelectedOwnerIntakeSettlementReceipt.fromStored(exposed)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void keepsAutomationBoundsAndFramesWhileEntityUsesItsOwnTypedTerminal() { + assertThat(AccountSelectedOwnerIntakeSettlementReceipt.AUTOMATION_MAX_BYTES) + .isEqualTo(92356608); + assertThat(AccountSelectedOwnerIntakeSettlementReceipt.ENTITY_MAX_BYTES).isEqualTo(117506048); + var binding = binding(); + when(binding.owner()).thenReturn(Owner.ENTITY_MANAGEMENT); + when(binding.schema()).thenReturn("account-entity-intake-authorization/v1"); + when(binding.purpose()).thenReturn("ENTITY_INTAKE_RETENTION"); + var owner = mock(EntityEmptySelectedSourceIntakeReceipt.class); + when(owner.targetNamespace()).thenReturn("test"); + when(owner.authorizationBindingBytes()).thenReturn(BINDING_BYTES.clone()); + when(owner.authorizationBindingDigest()).thenReturn(BINDING_DIGEST); + when(owner.outcome()).thenReturn("COMMITTED_EMPTY"); + when(owner.canonicalBytes()).thenReturn(OWNER_RECEIPT_BYTES.clone()); + when(owner.receiptDigest()).thenReturn(OWNER_RECEIPT_DIGEST); + var first = + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding), owner); + var receipt = AccountSelectedOwnerIntakeSettlementReceipt.create(first); + var reader = new DraftAuthorizationFenceBinding.FrameReader(receipt.canonicalBytes()); + reader.expect(AccountSelectedOwnerIntakeSettlementReceipt.DOMAIN); + reader.expect("1"); + assertThat(reader.bytes()).isEqualTo(BINDING_BYTES); + reader.expect(BINDING_DIGEST); + reader.expect("1"); + reader.expect("test"); + reader.expect(first.request().readRequestId().toString()); + reader.expect("spiffe://firemud/ns/test/sa/account-service"); + reader.expect("ENTITY_INTAKE_TERMINAL_READ"); + assertThat(reader.bytes()).isEqualTo(BINDING_BYTES); + reader.expect(BINDING_DIGEST); + assertThat(reader.bytes()).isEqualTo(OWNER_RECEIPT_BYTES); + reader.expect(OWNER_RECEIPT_DIGEST); + reader.requireEnd(); + var retry = + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding), owner); + assertThat(receipt.sameImmutableOwnerReceipt(retry)).isTrue(); + assertThat(receipt.entityTerminalEvidence()).isSameAs(first); + assertThatThrownBy(receipt::terminalEvidence).isInstanceOf(IllegalStateException.class); + var changedOwner = mock(EntityEmptySelectedSourceIntakeReceipt.class); + when(changedOwner.targetNamespace()).thenReturn("test"); + when(changedOwner.authorizationBindingBytes()).thenReturn(BINDING_BYTES.clone()); + when(changedOwner.outcome()).thenReturn("COMMITTED_EMPTY"); + when(changedOwner.canonicalBytes()).thenReturn(new byte[] {9}); + when(changedOwner.receiptDigest()) + .thenReturn(DraftAuthorizationFenceBinding.digest(new byte[] {9})); + assertThat( + receipt.sameImmutableOwnerReceipt( + new EntitySelectedSourceIntakeTerminalReadEvidence(retry.request(), changedOwner))) + .isFalse(); + } + + private static SelectedOwnerIntakeAuthorizationBinding binding() { + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.canonicalBytes()).thenReturn(BINDING_BYTES.clone()); + when(binding.digest()).thenReturn(BINDING_DIGEST); + when(binding.owner()).thenReturn(Owner.AUTOMATION_SCRIPTING); + when(binding.schema()).thenReturn("account-automation-intake-authorization/v1"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.targetNamespace()).thenReturn("test"); + when(binding.operationId()).thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(binding.fenceId()).thenReturn(UUID.fromString("22222222-2222-4222-8222-222222222222")); + when(binding.intakeRequestId()) + .thenReturn(UUID.fromString("33333333-3333-4333-8333-333333333333")); + return binding; + } + + private static AutomationEmptySelectedSourceIntakeReceipt ownerReceipt( + byte[] bytes, String digest) { + var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(receipt.targetNamespace()).thenReturn("test"); + when(receipt.authorizationBindingBytes()).thenReturn(BINDING_BYTES.clone()); + when(receipt.authorizationBindingDigest()).thenReturn(BINDING_DIGEST); + when(receipt.outcome()).thenReturn("COMMITTED_EMPTY"); + when(receipt.canonicalBytes()).thenReturn(bytes.clone()); + when(receipt.receiptDigest()).thenReturn(digest); + return receipt; + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence evidence( + SelectedOwnerIntakeAuthorizationBinding binding, + AutomationEmptySelectedSourceIntakeReceipt receipt) { + return new AutomationSelectedSourceIntakeTerminalReadEvidence( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding), + receipt); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java new file mode 100644 index 0000000000..3217cdea5a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest { + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedWorkloadMtlsAndCanonicalNamespace() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, plaintext, new GrpcChannelFactory(), "test")) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, tlsFiles(), new GrpcChannelFactory(), "not/a/namespace")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsRemoteReadWithAmbientSqlOrSynchronizationBeforeChannelUse() throws IOException { + var client = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + new ServiceEndpointsProperties(), tlsFiles(), new GrpcChannelFactory(), "test"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.readHeld(null)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.readHeld(null)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + client.close(); + } + + @Test + void rejectsRequestOutsideConfiguredNamespaceBeforeChannelUse() throws IOException { + var client = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + new ServiceEndpointsProperties(), tlsFiles(), new GrpcChannelFactory(), "other"); + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + + assertThatThrownBy(() -> client.readHeld(request)).isInstanceOf(IllegalArgumentException.class); + client.close(); + } + + private CommonGrpcClientProperties tlsFiles() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(file("client.crt").toString()); + properties.setPrivateKey(file("client.key").toString()); + properties.setCaCert(file("ca.crt").toString()); + return properties; + } + + private Path file(String name) { + Path path = temporaryDirectory.resolve(name); + try { + return Files.createFile(path); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java new file mode 100644 index 0000000000..bb486bd891 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java @@ -0,0 +1,895 @@ +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 java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalResult; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.Config; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.Entry; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.OperationKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import org.junit.jupiter.api.Test; + +class SelectedOwnerEmptySourceInputsTest { + 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 ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final String TEMPLATE_CONFIG = + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"; + + @Test + void automationTerminalReadEchoesExactBindingAndRequiresCommittedEmptyReceipt() { + Fixture fixture = fixture(Owner.AUTOMATION_SCRIPTING, Options.defaults()); + var inputs = + new SelectedOwnerEmptySourceInputs( + fixture.authorization(), fixture.worldInventoryReadEvidence()); + var binding = fixture.authorization(); + var receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + inputs, + 9001L, + 9002L, + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + "test", binding, fixture.worldInventoryReadEvidence().request().freezeEvidence()), + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + OffsetDateTime.parse("2026-10-10T00:00:00Z")); + var request = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding); + var evidence = new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt); + var settlement = AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + assertThat( + AccountSelectedOwnerIntakeSettlementReceipt.fromStored(settlement.canonicalBytes()) + .canonicalBytes()) + .containsExactly(settlement.canonicalBytes()); + var requestWire = AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request); + var response = AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toResponse(evidence); + + assertThat(requestWire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .containsExactly(binding.canonicalBytes()); + assertThat(requestWire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + assertThat(request.readRequestId()) + .isNotIn(binding.operationId(), binding.fenceId(), binding.intakeRequestId()); + assertThat(request.intendedReader()).isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + assertThat(request.terminalReadPurpose()).isEqualTo("AUTOMATION_INTAKE_TERMINAL_READ"); + assertThat(response.getResult()) + .isEqualTo( + AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY); + assertThat(response.getCommittedEmptyReceipt().toByteArray()) + .containsExactly(receipt.canonicalBytes()); + assertThat(AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(requestWire)) + .isEqualTo(request); + assertThat( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response) + .receipt() + .canonicalBytes()) + .containsExactly(receipt.canonicalBytes()); + + var retry = AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding); + assertThat(retry.readRequestId()).isNotEqualTo(request.readRequestId()); + var retryEvidence = new AutomationSelectedSourceIntakeTerminalReadEvidence(retry, receipt); + assertThat(settlement.sameImmutableOwnerReceipt(retryEvidence)).isTrue(); + assertThat( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toResponse(retryEvidence) + .getCommittedEmptyReceipt()) + .isEqualTo(response.getCommittedEmptyReceipt()); + + var changedEcho = + response.toBuilder() + .setRequest(requestWire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, changedEcho)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setResult( + AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().clearCommittedEmptyReceipt().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder().setReceiptDigest("sha256:" + "0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedReceipt = response.getCommittedEmptyReceipt().toByteArray(); + changedReceipt[changedReceipt.length - 1] ^= 1; + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(changedReceipt)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void retainsTheExactEmptyInputsAndOriginalDeclarationForBothOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + Fixture fixture = fixture(owner, Options.defaults()); + + var result = + new SelectedOwnerEmptySourceInputs( + fixture.authorization(), fixture.worldInventoryReadEvidence()); + + assertThat(result.authorizationBinding()).isSameAs(fixture.authorization()); + assertThat(result.worldInventoryReadEvidence()) + .isSameAs(fixture.worldInventoryReadEvidence()); + assertThat(result.sourceContent()).isSameAs(fixture.authorization().content()); + var actualDeclaration = result.ownerSourceInventoryDeclaration(); + var expectedDeclaration = fixture.expectedDeclaration(); + assertThat(actualDeclaration.object()).isEqualTo(expectedDeclaration.object()); + assertThat(actualDeclaration.owner()).isEqualTo(owner); + assertThat(actualDeclaration.inventoryJson()).isEqualTo(expectedDeclaration.inventoryJson()); + assertThat(actualDeclaration.sourceBinding().canonicalBytes()) + .containsExactly(expectedDeclaration.sourceBinding().canonicalBytes()); + assertThat(actualDeclaration.sourceBinding().digest()) + .isEqualTo(expectedDeclaration.sourceBinding().digest()); + assertThat(actualDeclaration.sourceBinding().commitId()) + .isNotEqualTo(fixture.authorization().selected().commitId()); + assertThat(actualDeclaration.revisionOrder()).isEqualTo(expectedDeclaration.revisionOrder()); + assertThat(actualDeclaration.revisionId()).isEqualTo(expectedDeclaration.revisionId()); + assertThat(actualDeclaration.revisionOrder()) + .isEqualTo(owner == Owner.ENTITY_MANAGEMENT ? "0" : "1"); + assertThat( + fixture + .worldInventoryReadEvidence() + .inventory() + .publicEvidence() + .sourceModel() + .familyCounts()) + .extracting(FamilyCount::family) + .contains("ROOM", "ROOM_EXIT"); + } + } + + @Test + void rejectsChangedOriginalBindingContentNamespaceAndSelectedCommit() { + Fixture original = fixture(Owner.ENTITY_MANAGEMENT, Options.defaults()); + + Fixture changedBinding = + fixture( + Owner.ENTITY_MANAGEMENT, + Options.defaults().withOperation(id("55555555-5555-4555-8555-555555555551"))); + assertRejected(original.authorization(), changedBinding.worldInventoryReadEvidence()); + + Fixture changedContent = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withSourceEpoch("2")); + assertRejected(original.authorization(), changedContent.worldInventoryReadEvidence()); + + Fixture changedReadNamespace = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withNamespace("other")); + assertRejected(original.authorization(), changedReadNamespace.worldInventoryReadEvidence()); + + Fixture changedCommit = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withSelectedVariant(1)); + assertRejected(original.authorization(), changedCommit.worldInventoryReadEvidence()); + } + + @Test + void rejectsMissingAndOtherOwnerOnlyDeclarationsFromTemplateConfigSnapshot() { + Fixture missing = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withDeclarationOwners(List.of())); + assertThat(missing.authorization().content().templateConfigSource().canonicalJson()) + .contains(TemplateConfigSourceSnapshot.SCHEMA); + assertRejected(missing.authorization(), missing.worldInventoryReadEvidence()); + + Fixture otherOwnerOnly = + fixture( + Owner.ENTITY_MANAGEMENT, + Options.defaults().withDeclarationOwners(List.of(Owner.AUTOMATION_SCRIPTING))); + assertThat(otherOwnerOnly.authorization().content().templateConfigSource().canonicalJson()) + .contains(TemplateConfigSourceSnapshot.SCHEMA_V2); + assertRejected(otherOwnerOnly.authorization(), otherOwnerOnly.worldInventoryReadEvidence()); + } + + @Test + void rejectsAllOwnerSpecificTemplateReferencesInEveryEntry() { + for (String collection : List.of("items", "npcs")) { + String key = "items".equals(collection) ? "items" : "npcs"; + Config config = + new Config( + TEMPLATE_CONFIG.replace( + "\"" + key + "\":[]", + "\"" + + key + + "\":[{\"entityTemplateId\":\"" + + "33333333-3333-4333-8333-333333333333" + + "\"}]")); + Fixture fixture = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withEntries(List.of(config))); + assertRejected(fixture.authorization(), fixture.worldInventoryReadEvidence()); + } + + Config scripts = + new Config( + TEMPLATE_CONFIG.replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"authored-script\",\"eventBindings\":[]}]")); + Fixture scriptReference = + fixture(Owner.AUTOMATION_SCRIPTING, Options.defaults().withEntries(List.of(scripts))); + assertRejected(scriptReference.authorization(), scriptReference.worldInventoryReadEvidence()); + + Config patch = + new Config( + TEMPLATE_CONFIG.replace( + "\"presence\":\"ABSENT\"", + "\"presence\":\"PRESENT\",\"scriptPatchVersion\":\"patch-1\"")); + Fixture patchReference = + fixture(Owner.AUTOMATION_SCRIPTING, Options.defaults().withEntries(List.of(patch))); + assertRejected(patchReference.authorization(), patchReference.worldInventoryReadEvidence()); + } + + @Test + void rejectsLegacyOrMissingWorldClosureAndEntitySpawnBindings() { + Fixture legacyWorld = + fixture( + Owner.ENTITY_MANAGEMENT, Options.defaults().withWorldProfile(WorldProfile.LEGACY_V1)); + assertRejected(legacyWorld.authorization(), legacyWorld.worldInventoryReadEvidence()); + + assertThatThrownBy( + () -> + fixture( + Owner.ENTITY_MANAGEMENT, + Options.defaults().withWorldProfile(WorldProfile.MISSING_CLOSURE_V2))) + .isInstanceOf(IllegalArgumentException.class); + + Fixture entitySpawn = fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withSpawnBindings(1)); + assertRejected(entitySpawn.authorization(), entitySpawn.worldInventoryReadEvidence()); + } + + private static void assertRejected( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerWorldInventoryReadEvidence worldEvidence) { + assertThatThrownBy(() -> new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Fixture fixture(Owner owner, Options options) { + DraftCommitBinding selected = selected(options.selectedVariant()); + SelectedOwnerIntakeSourceReadScope scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + options.namespace(), + options.operation(), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + ACTOR, + selected); + var templateSnapshot = templateSnapshot(selected, options); + var sourceContent = sourceContent(scope, templateSnapshot); + var authorization = + new SelectedOwnerIntakeAuthorizationBinding(sourceContent, accountSources()); + var freezeEvidence = freezeEvidence(options.namespace(), selected, options.worldProfile()); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create( + options.namespace(), authorization, freezeEvidence); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freezeEvidence, + publicInventory(freezeEvidence, options.worldProfile(), options.spawnBindings())); + return new Fixture( + authorization, + new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory), + templateSnapshot.ownerSourceInventoryDeclarations().stream() + .filter(declaration -> declaration.owner() == owner) + .findFirst() + .orElse(null)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + DraftCommitBinding selected, Options options) { + var declarationPayloads = new ArrayList(); + for (Owner owner : options.declarationOwners().stream().sorted().toList()) { + if (owner == Owner.AUTOMATION_SCRIPTING) { + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + declarationPayloads.add(TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory)); + } else if (owner == Owner.ENTITY_MANAGEMENT) { + var inventory = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + declarationPayloads.add(TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory)); + } + } + var payloads = new ArrayList<>(declarationPayloads); + for (int index = 0; index < options.entries().size(); index++) { + payloads.add( + TemplateConfigSourceValues.createPayload("entry-" + index, options.entries().get(index))); + } + if (payloads.isEmpty()) + payloads.add(SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); + + DraftCommitBinding authored = authoredBinding(payloads); + var mutations = TemplateConfigSourceValues.mutations(authored); + var declarations = + mutations.stream() + .filter( + mutation -> mutation.operation() == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .sorted(java.util.Comparator.comparing(declaration -> declaration.owner().name())) + .toList(); + var entries = new ArrayList(); + for (int index = 0; index < options.entries().size(); index++) { + var revision = authored.revisions().get(declarationPayloads.size() + index); + entries.add( + new Entry( + Integer.toString(index + 1), + options.entries().get(index), + authored, + revision.revisionOrder(), + revision.revisionId(), + "entry-" + index)); + } + return new TemplateConfigSourceSnapshot( + selected, + options.sourceEpoch(), + declarations.isEmpty() ? null : authored.commitId(), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + entries, + declarations); + } + + private static DraftCommitBinding authoredBinding(List payloads) { + List revisions = new ArrayList<>(); + for (int index = 0; index < payloads.size(); index++) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(index))); + } + return DraftCommitBinding.create( + target(), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope, TemplateConfigSourceSnapshot templateSnapshot) { + var out = new java.io.ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + 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", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + return SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); + } + + private static List accountSources() { + return List.of( + source(SourceKind.TENANT, TENANT.toString(), "tenant"), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected(int variant) { + return DraftCommitBinding.create( + target(), + variant == 0 + ? id("33333333-3333-4333-8333-333333333333") + : id("35353535-3535-4535-8535-353535353535"), + variant == 0 + ? id("44444444-4444-4444-8444-444444444444") + : id("45454545-4545-4545-8454-454545454545"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static TargetProof target() { + return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + String namespace, DraftCommitBinding selected, WorldProfile profile) { + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + "9", + "selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + TENANT, + VERSION, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + freezeRequest, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + profile == WorldProfile.LEGACY_V1 ? 3 : 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + WorldProfile profile, + int spawnBindings) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + boolean closureProfile = profile != WorldProfile.LEGACY_V1; + InboundSourceClosureDeclaration closure = + profile == WorldProfile.INBOUND_CLOSURE_V2 ? emptyInboundClosure() : null; + var spawnInputs = + spawnBindings == 0 + ? List.of() + : List.of( + new WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput( + id("18181818-1818-4818-8818-181818181818"), + id("19191919-1919-4919-8919-191919191919"), + "ITEM", + "ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID", + TENANT, + VERSION, + id("20202020-2020-4020-8020-202020202020"), + 1, + 0)); + var sourceModel = + new SourceModel( + closureProfile + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL + : WorldSelectedPublicationArtifactInventoryEvidence.SOURCE_MODEL, + closureProfile + ? WorldSelectedPublicationArtifactInventoryEvidence + .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + : 2, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", spawnBindings)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + spawnInputs, + 0, + spawnBindings, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + closure); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + TENANT, + VERSION, + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + closureProfile + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA + : WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA, + closureProfile + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION + : WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint( + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + closureProfile ? 4 : 3), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static void frame(java.io.ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(java.io.ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private enum WorldProfile { + INBOUND_CLOSURE_V2, + LEGACY_V1, + MISSING_CLOSURE_V2 + } + + private record Options( + String namespace, + int selectedVariant, + UUID operation, + String sourceEpoch, + List declarationOwners, + List entries, + WorldProfile worldProfile, + int spawnBindings) { + private static Options defaults() { + return new Options( + "test", + 0, + id("55555555-5555-4555-8555-555555555555"), + "1", + List.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT), + List.of(), + WorldProfile.INBOUND_CLOSURE_V2, + 0); + } + + private Options withNamespace(String value) { + return new Options( + value, + selectedVariant, + operation, + sourceEpoch, + declarationOwners, + entries, + worldProfile, + spawnBindings); + } + + private Options withSelectedVariant(int value) { + return new Options( + namespace, + value, + operation, + sourceEpoch, + declarationOwners, + entries, + worldProfile, + spawnBindings); + } + + private Options withOperation(UUID value) { + return new Options( + namespace, + selectedVariant, + value, + sourceEpoch, + declarationOwners, + entries, + worldProfile, + spawnBindings); + } + + private Options withSourceEpoch(String value) { + return new Options( + namespace, + selectedVariant, + operation, + value, + declarationOwners, + entries, + worldProfile, + spawnBindings); + } + + private Options withDeclarationOwners(List values) { + return new Options( + namespace, + selectedVariant, + operation, + sourceEpoch, + values, + entries, + worldProfile, + spawnBindings); + } + + private Options withEntries(List values) { + return new Options( + namespace, + selectedVariant, + operation, + sourceEpoch, + declarationOwners, + values, + worldProfile, + spawnBindings); + } + + private Options withWorldProfile(WorldProfile value) { + return new Options( + namespace, + selectedVariant, + operation, + sourceEpoch, + declarationOwners, + entries, + value, + spawnBindings); + } + + private Options withSpawnBindings(int value) { + return new Options( + namespace, + selectedVariant, + operation, + sourceEpoch, + declarationOwners, + entries, + worldProfile, + value); + } + } + + private record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence, + TemplateConfigOwnerSourceInventoryDeclaration expectedDeclaration) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java new file mode 100644 index 0000000000..ae65cb4f3b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java @@ -0,0 +1,448 @@ +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.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.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import org.junit.jupiter.api.Test; + +/** Synthetic integrity fixtures do not establish Account authority, source census, or receipts. */ +class SelectedOwnerIntakeAuthorizationBindingTest { + 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 roundTripsBothClosedOwnerDomainsWithExactCanonicalFrameAndCompleteContent() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var content = content(owner, ACTOR); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, unsortedSources(ACTOR)); + byte[] expected = encode(binding, binding.sources()); + byte[] observed = binding.canonicalBytes(); + + assertThat(observed).isEqualTo(expected); + assertThat(binding.schema()).isEqualTo(schema(owner)); + assertThat(binding.purpose()).isEqualTo(purpose(owner)); + assertThat(binding.intendedReader()).isEqualTo(reader(owner, "test")); + assertThat(binding.digest()).isEqualTo(digest(expected)); + assertThat(binding.sources().stream().map(SourceEvidence::key)) + .containsExactly( + "ACCOUNT:" + ACTOR, "MEMBERSHIP:" + ACTOR + "/" + TENANT, "TENANT:" + TENANT); + + var restored = SelectedOwnerIntakeAuthorizationBinding.fromStored(expected); + assertThat(restored.canonicalBytes()).isEqualTo(expected); + assertThat(restored.digest()).isEqualTo(binding.digest()); + assertThat(restored.content().canonicalBytes()).isEqualTo(content.canonicalBytes()); + assertThat(restored.content().digest()).isEqualTo(content.digest()); + assertThat(restored.content().scope()).isEqualTo(content.scope()); + assertThat(restored.owner()).isEqualTo(owner); + assertThat(restored.targetNamespace()).isEqualTo("test"); + assertThat(restored.operationId()).isEqualTo(OPERATION); + assertThat(restored.fenceId()).isEqualTo(FENCE); + assertThat(restored.intakeRequestId()).isEqualTo(INTAKE); + assertThat(restored.actorAccountId()).isEqualTo(ACTOR); + assertThat(restored.selected()).isEqualTo(content.scope().selected()); + assertThat(restored.tenantId()).isEqualTo(TENANT); + assertThat(restored.versionId()).isEqualTo(VERSION); + for (String family : FAMILIES) { + assertThat(restored.content().snapshotBytes(family)) + .isEqualTo(content.snapshotBytes(family)); + } + } + } + + @Test + void preservesDefensiveCopiesOfSourceListAndCanonicalContent() { + var content = content(Owner.ENTITY_MANAGEMENT, ACTOR); + var input = new ArrayList<>(unsortedSources(ACTOR)); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, input); + byte[] expected = binding.canonicalBytes(); + byte[] exposed = binding.canonicalBytes(); + exposed[0] ^= 0x7f; + input.clear(); + byte[] exposedEvidence = binding.sources().getFirst().evidence(); + exposedEvidence[0] ^= 0x7f; + byte[] exposedContent = binding.content().canonicalBytes(); + exposedContent[0] ^= 0x7f; + + assertThat(binding.canonicalBytes()).isEqualTo(expected); + assertThat(binding.content().canonicalBytes()).isNotEqualTo(exposedContent); + assertThat(binding.sources()).hasSize(3); + assertThat(binding.sources().getFirst().evidence()).isNotEqualTo(exposedEvidence); + assertThatThrownBy(() -> binding.sources().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void rejectsChangedPurposeReaderAndContentDigests() { + var binding = + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.AUTOMATION_SCRIPTING, ACTOR), unsortedSources(ACTOR)); + byte[] encoded = binding.canonicalBytes(); + + assertInvalid( + encode( + binding, + binding.sources(), + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + "ENTITY_INTAKE_RETENTION", + "3", + null)); + assertInvalid( + encode( + binding, + binding.sources(), + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + reader(Owner.ENTITY_MANAGEMENT, "test"), + binding.purpose(), + "3", + null)); + assertInvalid( + encode( + binding, + binding.sources(), + binding.schema(), + binding.content().canonicalBytes(), + "sha256:" + "0".repeat(64), + binding.intendedReader(), + binding.purpose(), + "3", + null)); + + byte[] invalidFrame = encoded.clone(); + ByteBuffer.wrap(invalidFrame).putInt(0, Integer.MAX_VALUE); + assertInvalid(invalidFrame); + byte[] invalidUtf8 = encoded.clone(); + invalidUtf8[4] = (byte) 0xc3; + invalidUtf8[5] = 0x28; + assertInvalid(invalidUtf8); + } + + @Test + void rejectsActorMismatchAndSourceEvidenceForAnotherActorOrTenant() { + var original = + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.ENTITY_MANAGEMENT, ACTOR), unsortedSources(ACTOR)); + UUID otherActor = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"); + UUID otherTenant = id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + assertThatThrownBy( + () -> + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.ENTITY_MANAGEMENT, otherActor), unsortedSources(ACTOR))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new SelectedOwnerIntakeAuthorizationBinding( + original.content(), + List.of( + evidence(SourceKind.ACCOUNT, ACTOR.toString(), "changed"), + evidence(SourceKind.TENANT, otherTenant.toString(), "tenant")))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new SelectedOwnerIntakeAuthorizationBinding( + original.content(), + List.of( + evidence(SourceKind.ACCOUNT, otherActor.toString(), "actor"), + evidence(SourceKind.TENANT, TENANT.toString(), "tenant")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresNonemptyDistinctSourceEvidence() { + var content = content(Owner.ENTITY_MANAGEMENT, ACTOR); + SourceEvidence account = evidence(SourceKind.ACCOUNT, ACTOR.toString(), "account"); + + assertThatThrownBy(() -> new SelectedOwnerIntakeAuthorizationBinding(content, List.of())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new SelectedOwnerIntakeAuthorizationBinding(content, List.of(account, account))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsCountOrderTrailingAndUnknownSchemaChanges() { + var binding = + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.ENTITY_MANAGEMENT, ACTOR), unsortedSources(ACTOR)); + List sorted = binding.sources(); + byte[] canonical = binding.canonicalBytes(); + byte[] reversed = + encode( + binding, + reversed(sorted), + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + "3", + null); + + assertInvalid( + encode( + binding, + sorted, + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + "2", + null)); + assertInvalid( + encode( + binding, + sorted, + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + "03", + null)); + assertInvalid(reversed); + assertInvalid(append(canonical, new byte[] {1})); + assertInvalid( + encode( + binding, + sorted, + "account-entity-intake-authorization/v2", + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + "3", + null)); + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationBinding.fromStored(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationBinding.fromStored( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void changedValidSourceEvidenceChangesDigestAndReadsBackExactly() { + var content = content(Owner.AUTOMATION_SCRIPTING, ACTOR); + var original = new SelectedOwnerIntakeAuthorizationBinding(content, unsortedSources(ACTOR)); + var changedSources = new ArrayList<>(unsortedSources(ACTOR)); + changedSources.set(0, evidence(SourceKind.TENANT, TENANT.toString(), "changed tenant source")); + var changed = new SelectedOwnerIntakeAuthorizationBinding(content, changedSources); + + assertThat(changed.digest()).isNotEqualTo(original.digest()); + assertThat( + SelectedOwnerIntakeAuthorizationBinding.fromStored(changed.canonicalBytes()) + .canonicalBytes()) + .isEqualTo(changed.canonicalBytes()); + } + + private static SelectedOwnerIntakeSourceContent content(Owner owner, UUID actor) { + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, actor, selected()); + byte[] bytes = encodeContent(scope, snapshots(scope.selected())); + return SelectedOwnerIntakeSourceContent.fromStored(bytes, scope, digest(bytes)); + } + + private static List unsortedSources(UUID actor) { + return List.of( + evidence(SourceKind.TENANT, TENANT.toString(), "tenant"), + evidence(SourceKind.ACCOUNT, actor.toString(), "account"), + evidence(SourceKind.MEMBERSHIP, actor + "/" + TENANT, "membership")); + } + + private static List reversed(List values) { + var reversed = new ArrayList<>(values); + java.util.Collections.reverse(reversed); + return reversed; + } + + private static SourceEvidence evidence(SourceKind kind, String scope, String value) { + return new SourceEvidence( + kind, scope, null, "1", null, null, value.getBytes(StandardCharsets.UTF_8)); + } + + 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[] encodeContent( + SelectedOwnerIntakeSourceReadScope scope, List snapshots) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (FamilySnapshot snapshot : snapshots) { + frame(out, snapshot.family()); + frame(out, snapshot.bytes()); + frame(out, digest(snapshot.bytes())); + } + return out.toByteArray(); + } + + private static byte[] encode( + SelectedOwnerIntakeAuthorizationBinding binding, List sources) { + return encode( + binding, + sources, + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + Integer.toString(sources.size()), + null); + } + + private static byte[] encode( + SelectedOwnerIntakeAuthorizationBinding binding, + List sources, + String schema, + byte[] content, + String contentDigest, + String reader, + String purpose, + String count, + byte[] trailing) { + var out = new ByteArrayOutputStream(); + frame(out, schema); + frame(out, content); + frame(out, contentDigest); + frame(out, reader); + frame(out, purpose); + frame(out, count); + for (SourceEvidence source : sources) frame(out, source.canonicalBytes()); + if (trailing != null) out.writeBytes(trailing); + return out.toByteArray(); + } + + private static void assertInvalid(byte[] bytes) { + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationBinding.fromStored(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftCommitBinding selected() { + 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, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static String schema(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "account-entity-intake-authorization/v1" + : "account-automation-intake-authorization/v1"; + } + + private static String purpose(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_RETENTION" + : "AUTOMATION_INTAKE_RETENTION"; + } + + private static String reader(Owner owner, String namespace) { + return "spiffe://firemud/ns/" + + namespace + + "/sa/" + + (owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"); + } + + 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[] bytes) { + return DraftAuthorizationFenceBinding.digest(bytes); + } + + private static byte[] append(byte[] value, byte[] suffix) { + byte[] joined = Arrays.copyOf(value, value.length + suffix.length); + System.arraycopy(suffix, 0, joined, value.length, suffix.length); + return joined; + } + + 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/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java new file mode 100644 index 0000000000..991d91f0ad --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java @@ -0,0 +1,103 @@ +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.Metadata; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; +import org.junit.jupiter.api.Test; + +class SelectedOwnerIntakeAuthorizationProducerCredentialsTest { + private static final String SECRET = "original.creator.credential"; + + @Test + void acceptsOnlyTheAuthorizeSelectedOwnerIntakeMethod() { + String allowedMethod = + AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .getAuthorizeSelectedOwnerIntakeMethod() + .getFullMethodName(); + + assertThat(SelectedOwnerIntakeAuthorizationProducerCredentials.allowedMethod(allowedMethod)) + .isTrue(); + assertThat(SelectedOwnerIntakeAuthorizationProducerCredentials.allowedMethod("other/Method")) + .isFalse(); + assertThat( + SelectedOwnerIntakeAuthorizationProducerCredentials.allowedMethod( + "account.v1.OtherService/AuthorizeSelectedOwnerIntake")) + .isFalse(); + + var headers = new Metadata(); + headers.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(SECRET)); + assertThat( + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + headers, allowedMethod) + .value()) + .isEqualTo(SECRET); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + headers, "other/Method")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresExactlyOneCredentialAndRedactsItsTextRepresentation() { + var missing = new Metadata(); + var one = new Metadata(); + var credential = SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(SECRET); + one.put(SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, credential); + var duplicate = new Metadata(); + duplicate.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(SECRET)); + duplicate.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of("second.credential")); + String method = + AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .getAuthorizeSelectedOwnerIntakeMethod() + .getFullMethodName(); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + missing, method)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + duplicate, method)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(credential.toString()).doesNotContain(SECRET); + assertThat(SelectedOwnerIntakeAuthorizationProducerCredentials.forAuthorize(SECRET).toString()) + .doesNotContain(SECRET); + } + + @Test + void rejectsBlankWhitespaceNonAsciiAndOversizedCredentialsWithoutTrimming() { + for (String invalid : + new String[] { + null, + "", + " ", + "has whitespace", + "\ttab", + "non-ascii-\u00e9", + "x".repeat(SelectedOwnerIntakeAuthorizationProducerCredentials.MAX_CREDENTIAL_CHARS + 1) + }) { + assertThatThrownBy( + () -> SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat( + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of( + "x" + .repeat( + SelectedOwnerIntakeAuthorizationProducerCredentials + .MAX_CREDENTIAL_CHARS)) + .value()) + .hasSize(SelectedOwnerIntakeAuthorizationProducerCredentials.MAX_CREDENTIAL_CHARS); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java new file mode 100644 index 0000000000..e0dca16491 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java @@ -0,0 +1,256 @@ +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.account.v1.SelectedOwnerIntakeAuthorizationProducerResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +class SelectedOwnerIntakeAuthorizationProducerProtoCodecTest { + @Test + void roundTripsExactCanonicalSelectionAndCompleteOwnerAuthorization() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + var request = + new Request( + 1, + "test", + UUID.randomUUID(), + binding.intakeRequestId(), + owner, + binding.selected().canonicalBytes()); + var wireRequest = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(request); + + assertThat(SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromRequest(wireRequest)) + .isEqualTo(request); + assertThat(wireRequest.getSelectedDraftBinding().toByteArray()) + .containsExactly(binding.selected().canonicalBytes()); + var result = + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest()); + var response = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse(result); + assertThat(response.getRequest()).isEqualTo(wireRequest); + assertThat(response.getIntakeAuthorizationBinding().toByteArray()) + .containsExactly(binding.canonicalBytes()); + assertThat(response.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + + var decoded = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, response); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); + assertThat(decoded.digest()).isEqualTo(binding.digest()); + } + } + + @Test + void rejectsChangedTransportNamespaceIntakeOwnerAndSelectedDraftEchoes() { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = request(Owner.ENTITY_MANAGEMENT, binding); + var response = response(request, binding); + var exactEcho = response.getRequest(); + var changed = + List.of( + exactEcho.toBuilder().setTransportRequestId(UUID.randomUUID().toString()).build(), + exactEcho.toBuilder().setTargetNamespace("other").build(), + exactEcho.toBuilder().setIntakeRequestId(UUID.randomUUID().toString()).build(), + exactEcho.toBuilder() + .setOwner( + net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerOwner + .SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_AUTOMATION_SCRIPTING) + .build(), + exactEcho.toBuilder().setSelectedDraftBinding(ByteString.copyFromUtf8("{}")).build()); + + for (var echo : changed) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, response.toBuilder().setRequest(echo).build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void acceptsDifferentAccountSourceCaptureButRejectsMismatchedOwnerAndDigest() { + var entity = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var automation = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = request(Owner.ENTITY_MANAGEMENT, entity); + var response = response(request, entity); + + var changedSources = new java.util.ArrayList<>(entity.sources()); + var source = changedSources.get(0); + changedSources.set( + 0, + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[] {9, 8, 7})); + var changedCompleteBinding = + new SelectedOwnerIntakeAuthorizationBinding(entity.content(), changedSources); + var changedAccountSourceResponse = + response.toBuilder() + .setIntakeAuthorizationBinding( + ByteString.copyFrom(changedCompleteBinding.canonicalBytes())) + .setIntakeAuthorizationDigest(changedCompleteBinding.digest()) + .build(); + var accepted = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, changedAccountSourceResponse); + assertThat(accepted.binding().canonicalBytes()) + .containsExactly(changedCompleteBinding.canonicalBytes()); + + var mismatchedOwnerBinding = + response.toBuilder() + .setIntakeAuthorizationBinding(ByteString.copyFrom(automation.canonicalBytes())) + .setIntakeAuthorizationDigest(automation.digest()) + .build(); + var wrongDigest = + response.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); + + for (var changed : List.of(mismatchedOwnerBinding, wrongDigest)) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownDefaultMalformedAndOversizedRequestValues() { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = request(Owner.ENTITY_MANAGEMENT, binding); + var wire = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(request); + var unknown = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var nestedUnknown = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse( + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest())) + .toBuilder() + .setRequest( + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build(); + var malformed = + wire.toBuilder().setSelectedDraftBinding(ByteString.copyFrom(new byte[] {1, 2, 3})).build(); + var unspecifiedOwner = wire.toBuilder().clearOwner().build(); + var unknownOwner = wire.toBuilder().setOwnerValue(99).build(); + var oversizedSelection = + wire.toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte + [SelectedOwnerIntakeAuthorizationProducerEvidence.MAX_SELECTION_BYTES + 1])) + .build(); + + for (var changed : + List.of(unknown, malformed, unspecifiedOwner, unknownOwner, oversizedSelection)) { + assertThatThrownBy( + () -> SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + var unknownResponse = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse( + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest())) + .toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, nestedUnknown)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, unknownResponse)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMalformedNoncanonicalOrOversizedAuthorizationBinding() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = request(Owner.AUTOMATION_SCRIPTING, binding); + var exact = response(request, binding); + var malformed = + exact.toBuilder() + .setIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversized = + exact.toBuilder() + .setIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + var missing = SelectedOwnerIntakeAuthorizationProducerResponse.getDefaultInstance(); + + for (var changed : List.of(malformed, oversized, missing)) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsResponsesBeyondTheTwentyFourMibWireBudget() { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = request(Owner.ENTITY_MANAGEMENT, binding); + var oversizedEcho = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(request).toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationProducerProtoCodec.MAX_WIRE_BYTES])) + .build(); + var oversized = response(request, binding).toBuilder().setRequest(oversizedEcho).build(); + + assertThat(oversized.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeAuthorizationProducerProtoCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Request request(Owner owner, SelectedOwnerIntakeAuthorizationBinding binding) { + return new Request( + 1, + "test", + UUID.randomUUID(), + binding.intakeRequestId(), + owner, + binding.selected().canonicalBytes()); + } + + private static SelectedOwnerIntakeAuthorizationProducerResponse response( + Request request, SelectedOwnerIntakeAuthorizationBinding binding) { + return SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse( + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest())); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java new file mode 100644 index 0000000000..17196be056 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java @@ -0,0 +1,177 @@ +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.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import org.junit.jupiter.api.Test; + +/** Synthetic lookup evidence only; Account authentication establishes the HELD result. */ +class SelectedOwnerIntakeAuthorizationReadEvidenceTest { + private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); + private static final UUID INTAKE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID READ = id("88888888-8888-4888-8888-888888888888"); + + @Test + void requestDerivesOwnerReaderAndRetentionPurposeForBothClosedOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = binding(owner); + var request = Request.create("test", binding); + + assertThat(request.schemaVersion()).isEqualTo(1); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.readRequestId()) + .isNotIn(binding.operationId(), binding.fenceId(), binding.intakeRequestId()); + assertThat(request.intendedReader()).isEqualTo(binding.intendedReader()); + assertThat(request.retentionPurpose()).isEqualTo(binding.purpose()); + assertThat(request.binding()).isSameAs(binding); + } + } + + @Test + void rejectsInvalidNamespaceCorrelationVersionAndBindingNamespace() { + var binding = binding(Owner.ENTITY_MANAGEMENT); + assertThatThrownBy(() -> new Request(1, "not/a/namespace", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(2, "test", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "other", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", OPERATION, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", FENCE, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", INTAKE, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", new UUID(0, 0), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", READ, null)) + .isInstanceOf(IllegalArgumentException.class); + } + + static SelectedOwnerIntakeAuthorizationBinding binding(Owner owner) { + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + var selected = selected(tenant); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, actor, selected); + var content = content(scope); + return new SelectedOwnerIntakeAuthorizationBinding(content, sources(actor, tenant)); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = snapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] snapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + 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", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + if ("TEMPLATE_CONFIG".equals(family)) + return new TemplateConfigSourceSnapshot( + selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) + .canonicalBytes(); + return SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); + } + + private static List sources(UUID actor, UUID tenant) { + var values = new ArrayList(); + values.add(evidence(SourceKind.TENANT, tenant.toString(), "tenant")); + values.add(evidence(SourceKind.ACCOUNT, actor.toString(), "account")); + values.add(evidence(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership")); + return values; + } + + private static SourceEvidence evidence(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected(UUID tenant) { + UUID version = id("22222222-2222-4222-8222-222222222222"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + Owner.GAME_DESIGN_CONTROL_PLANE, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())), + 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); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java new file mode 100644 index 0000000000..c2c0d07d48 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java @@ -0,0 +1,174 @@ +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 net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Synthetic protobuf integrity cases only; HELD comes from Account's authenticated read. */ +class SelectedOwnerIntakeAuthorizationReadGrpcCodecTest { + @Test + void roundTripsClosedEntityAndAutomationRequestsAndExactHeldEchoes() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + var request = Request.create("test", binding); + var wire = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest(request); + + assertThat(wire.getSchemaVersion()).isEqualTo(1); + assertThat(wire.getTargetNamespace()).isEqualTo("test"); + assertThat(wire.getReadRequestId()).isEqualTo(request.readRequestId().toString()); + assertThat(wire.getIntendedReader()).isEqualTo(binding.intendedReader()); + assertThat(wire.getRetentionPurpose()).isEqualTo(binding.purpose()); + assertThat(wire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .isEqualTo(binding.canonicalBytes()); + assertThat(wire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + var decoded = SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(wire); + assertThat(decoded.schemaVersion()).isEqualTo(request.schemaVersion()); + assertThat(decoded.targetNamespace()).isEqualTo(request.targetNamespace()); + assertThat(decoded.readRequestId()).isEqualTo(request.readRequestId()); + assertThat(decoded.binding().canonicalBytes()).isEqualTo(binding.canonicalBytes()); + + var response = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toHeldResponse(request); + assertThat(response.getRequest()).isEqualTo(wire); + assertThat(response.getHeld()).isTrue(); + assertThat(SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse(request, response)) + .isEqualTo(new SelectedOwnerIntakeAuthorizationReadEvidence(request)); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + } + } + + @Test + void rejectsChangedClosedPurposeReaderNamespaceVersionDigestAndUuid() { + var request = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT))); + for (var changed : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setTargetNamespace("other").build(), + request.toBuilder().setReadRequestId("not-a-uuid").build(), + request.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/account-service") + .build(), + request.toBuilder().setRetentionPurpose("ENTITY_INTAKE_SOURCE").build(), + request.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build())) { + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownFieldsAndMalformedOrOversizedBindings() { + var request = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.AUTOMATION_SCRIPTING))); + var unknown = + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var malformed = + request.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversizedBinding = + request.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + + for (var changed : List.of(unknown, malformed, oversizedBinding)) { + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsNonHeldSubstitutedAndUnknownResponses() { + var request = + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT)); + var exact = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toHeldResponse(request); + var notHeld = exact.toBuilder().setHeld(false).build(); + var substituted = + exact.toBuilder() + .setRequest( + exact.getRequest().toBuilder() + .setReadRequestId("12121212-1212-4212-8212-121212121212")) + .build(); + var unknown = + exact.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var nestedUnknown = + exact.toBuilder() + .setRequest( + exact.getRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build())) + .build(); + for (var changed : List.of(notHeld, substituted, unknown, nestedUnknown)) { + assertThatThrownBy( + () -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse( + request, ReadHeldSelectedOwnerIntakeAuthorizationResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsWireMessagesBeyondTheTwentyFourMibBudget() { + byte[] oversizedBytes = + new byte[SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES + 1]; + var oversized = + ReadHeldSelectedOwnerIntakeAuthorizationRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(oversizedBytes)) + .build(); + assertThat(oversized.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(oversized)) + .isInstanceOf(IllegalArgumentException.class); + + var oversizedResponse = + ReadHeldSelectedOwnerIntakeAuthorizationResponse.newBuilder() + .setRequest(oversized) + .setHeld(true) + .build(); + assertThat(oversizedResponse.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.ENTITY_MANAGEMENT)), + oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class); + } +} 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..eac99183bf 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 @@ -21,8 +21,10 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; +import net.firedevops.firemud.common.publication.WorldSelectedOwnerInventoryGrpcClient; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -171,26 +173,42 @@ private interface Initialize { private record ClientHandle(AbstractReloadingBlockingGrpcClient client, Initialize initialize) {} private enum ClientKind { + AUTHORIZATION, + WORLD_CLOSURE_AUTHORIZATION, SOURCE_READ, - GAME_DESIGN_SOURCE; + AUTOMATION_TERMINAL, + GAME_DESIGN_SOURCE, + WORLD_INVENTORY; ClientHandle create( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tls, GrpcChannelFactory factory) { return switch (this) { - - + case AUTHORIZATION -> { + var client = new AccountSelectedOwnerIntakeAuthorizationGrpcClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLD_CLOSURE_AUTHORIZATION -> { + var client = new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } case SOURCE_READ -> { var client = new GrpcSelectedOwnerIntakeSourceReadClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } - + case AUTOMATION_TERMINAL -> { + var client = new AutomationSelectedSourceIntakeTerminalReadClient(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); } - + case WORLD_INVENTORY -> { + var client = new WorldSelectedOwnerInventoryGrpcClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } }; } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java new file mode 100644 index 0000000000..35d7f4ecde --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java @@ -0,0 +1,200 @@ +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.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementRequest; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Closed-schema codec tests; these values do not establish Account or Automation authority. */ +class SelectedOwnerIntakeSettlementGrpcCodecTest { + @Test + void roundTripsCanonicalRequestWithIndependentTransportCorrelation() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = Request.create("test", binding); + assertThat(SelectedOwnerIntakeSettlementEvidence.MAX_REQUEST_BYTES) + .isEqualTo(SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 64 * 1024); + assertThat(SelectedOwnerIntakeSettlementEvidence.MAX_RESPONSE_BYTES) + .isEqualTo( + AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES + + SelectedOwnerIntakeSettlementEvidence.MAX_REQUEST_BYTES + + 64 * 1024); + var wire = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(request); + + assertThat(wire.getSchemaVersion()).isEqualTo(1); + assertThat(wire.getTargetNamespace()).isEqualTo("test"); + assertThat(wire.getTransportRequestId()).isEqualTo(request.transportRequestId().toString()); + assertThat(wire.getTransportRequestId()) + .isNotIn( + binding.operationId().toString(), + binding.fenceId().toString(), + binding.intakeRequestId().toString()); + assertThat(wire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .containsExactly(binding.canonicalBytes()); + assertThat(wire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + assertThat(SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(wire)).isEqualTo(request); + } + + @Test + void rejectsDefaultUnknownAndChangedDigestRequestsWhileAcceptingClosedEntityOwner() { + assertThatThrownBy( + () -> + SelectedOwnerIntakeSettlementGrpcCodec.fromRequest( + SelectedOwnerIntakeSettlementRequest.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var valid = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(Request.create("test", binding)); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + + var changedDigest = + valid.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(changedDigest)) + .isInstanceOf(IllegalArgumentException.class); + + var entity = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var wrongOwner = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(entity.canonicalBytes())) + .setIntakeAuthorizationDigest(entity.digest()) + .build(); + assertThat( + SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(wrongOwner) + .authorizationBinding() + .owner()) + .isEqualTo(Owner.ENTITY_MANAGEMENT); + } + + @Test + void rejectsOversizedAuthorizationBeforeCanonicalDecoding() { + var oversized = + SelectedOwnerIntakeSettlementRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace("test") + .setTransportRequestId(UUID.randomUUID().toString()) + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)) + .build(); + + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("16 MiB"); + } + + @Test + void echoesRequestAndCarriesEverySettlementReceiptByteAndDigest() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = Request.create("test", binding); + byte[] completeReceipt = new byte[4096]; + for (int index = 0; index < completeReceipt.length; index++) { + completeReceipt[index] = (byte) (index * 31); + } + var receipt = mock(AccountSelectedOwnerIntakeSettlementReceipt.class); + when(receipt.authorizationBinding()).thenReturn(binding); + when(receipt.targetNamespace()).thenReturn("test"); + when(receipt.canonicalBytes()).thenReturn(completeReceipt.clone()); + when(receipt.digest()).thenReturn(DraftAuthorizationFenceBinding.digest(completeReceipt)); + + var response = + SelectedOwnerIntakeSettlementGrpcCodec.toResponse( + new SelectedOwnerIntakeSettlementEvidence.Result(request, receipt)); + + assertThat(response.getRequest()) + .isEqualTo(SelectedOwnerIntakeSettlementGrpcCodec.toRequest(request)); + assertThat(response.getSettlementReceipt().toByteArray()).containsExactly(completeReceipt); + assertThat(response.getSettlementReceiptDigest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(completeReceipt)); + } + + @Test + void rejectsChangedEchoUnknownResponseAndMalformedFullReceipt() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = Request.create("test", binding); + var base = + net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementResponse.newBuilder() + .setRequest(SelectedOwnerIntakeSettlementGrpcCodec.toRequest(request)) + .setSettlementReceipt(ByteString.copyFrom(new byte[] {1, 2, 3, 4})) + .setSettlementReceiptDigest("sha256:" + "0".repeat(64)) + .build(); + + var changedEcho = + base.toBuilder() + .setRequest( + base.getRequest().toBuilder().setTransportRequestId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> SelectedOwnerIntakeSettlementGrpcCodec.fromResponse(request, changedEcho)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed"); + + var unknown = + base.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromResponse(request, unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromResponse(request, base)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("malformed"); + } + + @Test + void rejectsCorrelationReuseAndReceiptDigestOrAuthorizationSubstitution() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + assertThatThrownBy(() -> new Request(1, "test", binding.operationId(), binding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("correlation"); + + var request = Request.create("test", binding); + byte[] receiptBytes = {10, 20, 30, 40}; + var badDigest = mock(AccountSelectedOwnerIntakeSettlementReceipt.class); + when(badDigest.authorizationBinding()).thenReturn(binding); + when(badDigest.targetNamespace()).thenReturn("test"); + when(badDigest.canonicalBytes()).thenReturn(receiptBytes); + when(badDigest.digest()).thenReturn("sha256:" + "0".repeat(64)); + assertThatThrownBy(() -> new SelectedOwnerIntakeSettlementEvidence.Result(request, badDigest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("receipt"); + + var substitutedBinding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var substitution = mock(AccountSelectedOwnerIntakeSettlementReceipt.class); + when(substitution.authorizationBinding()).thenReturn(substitutedBinding); + when(substitution.targetNamespace()).thenReturn("test"); + when(substitution.canonicalBytes()).thenReturn(receiptBytes); + when(substitution.digest()).thenReturn(DraftAuthorizationFenceBinding.digest(receiptBytes)); + assertThatThrownBy( + () -> new SelectedOwnerIntakeSettlementEvidence.Result(request, substitution)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("original authorization"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest.java new file mode 100644 index 0000000000..2a08a82d03 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest.java @@ -0,0 +1,57 @@ +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.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Synthetic lookup evidence only; Account authentication establishes the HELD result. */ +class SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest { + private static final UUID READ = UUID.fromString("88888888-8888-4888-8888-888888888888"); + + @Test + void derivesWorldReaderAndClosedPurposeFromBothOriginalOwnerBindings() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + var request = Request.create("test", binding); + + assertThat(request.schemaVersion()).isEqualTo(1); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.readRequestId()) + .isNotIn(binding.operationId(), binding.fenceId(), binding.intakeRequestId()); + assertThat(request.intendedReader()) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + assertThat(request.closureReadPurpose()) + .isEqualTo( + owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"); + assertThat(request.binding()).isSameAs(binding); + } + } + + @Test + void rejectsInvalidNamespaceCorrelationVersionAndBindingNamespace() { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + assertThatThrownBy(() -> new Request(1, "not/a/namespace", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(2, "test", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "other", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", binding.operationId(), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", binding.fenceId(), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", binding.intakeRequestId(), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", new UUID(0, 0), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", READ, null)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java new file mode 100644 index 0000000000..e75fee51c6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java @@ -0,0 +1,184 @@ +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 net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Synthetic protobuf integrity cases only; HELD comes from Account's authenticated read. */ +class SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest { + @Test + void roundTripsClosedOwnerRequestsAndExactHeldEchoes() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + var request = Request.create("test", binding); + var wire = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest(request); + + assertThat(wire.getSchemaVersion()).isEqualTo(1); + assertThat(wire.getTargetNamespace()).isEqualTo("test"); + assertThat(wire.getReadRequestId()).isEqualTo(request.readRequestId().toString()); + assertThat(wire.getIntendedReader()).isEqualTo(request.intendedReader()); + assertThat(wire.getClosureReadPurpose()).isEqualTo(request.closureReadPurpose()); + assertThat(wire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .isEqualTo(binding.canonicalBytes()); + assertThat(wire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + var decoded = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(wire); + assertThat(decoded.schemaVersion()).isEqualTo(request.schemaVersion()); + assertThat(decoded.targetNamespace()).isEqualTo(request.targetNamespace()); + assertThat(decoded.readRequestId()).isEqualTo(request.readRequestId()); + assertThat(decoded.binding().canonicalBytes()).isEqualTo(binding.canonicalBytes()); + + var response = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toHeldResponse(request); + assertThat(response.getRequest()).isEqualTo(wire); + assertThat(response.getHeld()).isTrue(); + assertThat( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, response)) + .isEqualTo(new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(request)); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + } + } + + @Test + void rejectsChangedClosedPurposeReaderNamespaceVersionDigestAndUuid() { + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT))); + for (var changed : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setTargetNamespace("other").build(), + request.toBuilder().setReadRequestId("not-a-uuid").build(), + request.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/account-service") + .build(), + request.toBuilder().setClosureReadPurpose("ENTITY_INTAKE_SOURCE").build(), + request.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build())) { + assertThatThrownBy( + () -> SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownFieldsAndMalformedOrOversizedBindings() { + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.AUTOMATION_SCRIPTING))); + var unknown = + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var malformed = + request.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversizedBinding = + request.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + + for (var changed : List.of(unknown, malformed, oversizedBinding)) { + assertThatThrownBy( + () -> SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsNonHeldSubstitutedAndUnknownResponses() { + var request = + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT)); + var exact = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toHeldResponse(request); + var notHeld = exact.toBuilder().setHeld(false).build(); + var substituted = + exact.toBuilder() + .setRequest( + exact.getRequest().toBuilder() + .setReadRequestId("12121212-1212-4212-8212-121212121212")) + .build(); + var unknown = + exact.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var nestedUnknown = + exact.toBuilder() + .setRequest( + exact.getRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build())) + .build(); + for (var changed : List.of(notHeld, substituted, unknown, nestedUnknown)) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMessagesBeyondTheTwentyFourMibBudget() { + byte[] oversizedBytes = + new byte[SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES + 1]; + var oversized = + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(oversizedBytes)) + .build(); + assertThat(oversized.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(oversized)) + .isInstanceOf(IllegalArgumentException.class); + + var oversizedResponse = + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse.newBuilder() + .setRequest(oversized) + .setHeld(true) + .build(); + assertThat(oversizedResponse.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.ENTITY_MANAGEMENT)), + oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java new file mode 100644 index 0000000000..3fe96e7796 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java @@ -0,0 +1,486 @@ +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 java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +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.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import org.junit.jupiter.api.Test; + +class SelectedOwnerWorldInventoryRecipientFieldsTest { + @Test + void rejectsChangedOriginalRecipientAndDerivedClosurePurposeForBothOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + String purpose = + owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"; + var base = + ReadSelectedOwnerWorldInventoryRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(binding.targetNamespace()) + .setReadRequestId("12121212-1212-4212-8212-121212121212") + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(binding.canonicalBytes())) + .setIntakeAuthorizationDigest(binding.digest()) + .setIntendedReader(binding.intendedReader()) + .setClosureReadPurpose(purpose) + .build(); + + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(base)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("freeze evidence"); + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest( + base.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/world-management-service") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("recipient differs"); + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest( + base.toBuilder().setClosureReadPurpose("ENTITY_INTAKE_RETENTION").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("closure read purpose differs"); + } + } + + @Test + void roundTripsCompleteOwnerRequestAndTypedPublicInventoryForBothOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = fixture(owner); + var requestWire = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var decodedRequest = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(requestWire); + + assertThat(requestWire.getSerializedSize()) + .isLessThanOrEqualTo(SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES); + assertThat(requestWire.getIntendedReader()).isEqualTo(fixture.binding().intendedReader()); + assertThat(requestWire.getClosureReadPurpose()) + .isEqualTo(fixture.request().closureReadPurpose()); + assertThat(decodedRequest.authorizationBinding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(decodedRequest.freezeEvidence().request()) + .isEqualTo(fixture.freezeEvidence().request()); + assertThat(decodedRequest.freezeEvidence().acknowledgement()) + .isEqualTo(fixture.freezeEvidence().acknowledgement()); + assertThat(decodedRequest.freezeEvidence()) + .isEqualTo(fixture.freezeEvidence()) + .hasSameHashCodeAs(fixture.freezeEvidence()); + + var responseWire = + SelectedOwnerWorldInventoryReadGrpcCodec.toResponse(decodedRequest, fixture.inventory()); + var decodedEvidence = + SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse(decodedRequest, responseWire); + + assertThat(fixture.inventory().canonicalBytes().length) + .isLessThanOrEqualTo(SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES); + assertThat(responseWire.getSerializedSize()) + .isLessThanOrEqualTo(SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES); + assertThat(responseWire.getRequest()).isEqualTo(requestWire); + assertThat(decodedEvidence.request().authorizationBinding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(decodedEvidence.request().freezeEvidence().request()) + .isEqualTo(fixture.freezeEvidence().request()); + assertThat(decodedEvidence.inventory().canonicalBytes()) + .containsExactly(fixture.inventory().canonicalBytes()); + assertThat(decodedEvidence.inventory().digest()).isEqualTo(fixture.inventory().digest()); + assertThat(decodedEvidence.inventory().publicEvidence()) + .isEqualTo(fixture.inventory().publicEvidence()); + } + } + + @Test + void rejectsChangedCompleteRequestEchoAndInventoryDigest() { + var fixture = fixture(Owner.ENTITY_MANAGEMENT); + var requestWire = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var response = + SelectedOwnerWorldInventoryReadGrpcCodec.toResponse(fixture.request(), fixture.inventory()); + var changedEcho = + response.toBuilder() + .setRequest( + requestWire.toBuilder().setReadRequestId("abababab-abab-4bab-8bab-abababababab")) + .build(); + String zeroDigest = "sha256:" + "0".repeat(64); + var changedDigest = + response.toBuilder() + .setPublicInventoryDigest( + fixture.inventory().digest().equals(zeroDigest) + ? "sha256:" + "1".repeat(64) + : zeroDigest) + .build(); + + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse( + fixture.request(), changedEcho)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected-owner inventory read request"); + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse( + fixture.request(), changedDigest)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInventoryBoundToDifferentFreezeAcknowledgement() { + var fixture = fixture(Owner.ENTITY_MANAGEMENT); + var requestWire = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var changedAcknowledgement = + requestWire.getFreezeAcknowledgement().toBuilder().setContentDigest("b".repeat(64)).build(); + var changedRequestWire = + requestWire.toBuilder().setFreezeAcknowledgement(changedAcknowledgement).build(); + var changedRequest = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(changedRequestWire); + + assertThat(changedRequest.freezeEvidence()).isNotEqualTo(fixture.freezeEvidence()); + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.toResponse( + changedRequest, fixture.inventory())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected-owner freeze"); + } + + private static Fixture fixture(Owner owner) { + String namespace = "test"; + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID version = id("22222222-2222-4222-8222-222222222222"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + var target = new TargetProof(tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + var selected = + DraftCommitBinding.create( + target, + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + var sourceScope = + new SelectedOwnerIntakeSourceReadScope( + owner, + namespace, + id("55555555-5555-4555-8555-555555555555"), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + actor, + selected); + var authorization = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent(sourceScope), + List.of( + source(SourceKind.TENANT, tenant.toString(), "tenant"), + source(SourceKind.ACCOUNT, actor.toString(), "account"), + source(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "9", + "selected-owner codec fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + target, + selected, + new VisibilityFence( + target, + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1}))); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + tenant, + version, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + freezeRequest, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + var request = + SelectedOwnerWorldInventoryReadEvidence.create(namespace, authorization, freezeEvidence); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freezeEvidence, publicInventory(freezeEvidence, selected, account)); + return new Fixture(authorization, freezeEvidence, request, inventory); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new java.io.ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + 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", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + if ("TEMPLATE_CONFIG".equals(family)) { + return new TemplateConfigSourceSnapshot( + selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) + .canonicalBytes(); + } + return SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freeze, + DraftCommitBinding selected, + AccountPublicationAuthorizationBinding account) { + var request = freeze.request(); + var acknowledgement = freeze.acknowledgement(); + var inboundClosure = + new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 0), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + inboundClosure); + var selection = account.input().selection(); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + new PublicOwnerScope( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + id("12121212-1212-4212-8212-121212121212"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("14141414-1414-4414-8414-141414141414"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)), + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint( + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + acknowledgement.digestSchemaVersion()), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(java.io.ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(java.io.ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record Fixture( + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence.Request request, + WorldSelectedPublicationArtifactInventoryEvidence inventory) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..7a7e4cc987 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java @@ -0,0 +1,247 @@ +package net.firedevops.firemud.common.entity.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.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalResult; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class EntitySelectedSourceIntakeTerminalReadGrpcCodecTest { + private static Fixture fixture; + + @BeforeAll + static void createSyntheticFixture() { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + } + + @Test + void roundTripsCompleteCanonicalReceiptAndOriginalBindingBytes() { + byte[] bindingBytes = fixture.authorization().canonicalBytes(); + byte[] receiptBytes = fixture.receipt().canonicalBytes(); + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + "test", fixture.authorization()); + var requestWire = EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request); + var decodedRequest = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(requestWire); + + assertThat(decodedRequest).isEqualTo(request); + assertThat(decodedRequest.readRequestId()) + .isNotIn( + fixture.authorization().operationId(), + fixture.authorization().fenceId(), + fixture.authorization().intakeRequestId()); + assertThat(decodedRequest.binding().canonicalBytes()).isEqualTo(bindingBytes); + assertThat(decodedRequest.binding().digest()).isEqualTo(fixture.authorization().digest()); + + var response = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())); + assertThat(response.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(response.getResult()) + .isEqualTo( + EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY); + assertThat(response.getRequest()).isEqualTo(requestWire); + var decoded = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.receipt().canonicalBytes()).isEqualTo(receiptBytes); + assertThat(decoded.receipt().authorizationBindingBytes()).isEqualTo(bindingBytes); + assertThat(decoded.receipt().authorizationBindingDigest()) + .isEqualTo(fixture.authorization().digest()); + assertThat(decoded.receipt().selectedSourceBytes()) + .isEqualTo(fixture.inputs().sourceContent().canonicalBytes()); + assertThat(decoded.receipt().selectedSourceDigest()) + .isEqualTo(fixture.inputs().sourceContent().digest()); + assertThat(decoded.receipt().selectedSourceRevisionBindingDigest()) + .isEqualTo(fixture.inputs().ownerSourceInventoryDeclaration().sourceBinding().digest()); + byte[] originalWorldRequest = + SelectedOwnerWorldInventoryReadGrpcCodec.toRequest( + fixture.inputs().worldInventoryReadEvidence().request()) + .toByteArray(); + assertThat(decoded.receipt().worldReadRequestBytes()).isEqualTo(originalWorldRequest); + assertThat(decoded.receipt().worldReadRequestDigest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(originalWorldRequest)); + assertThat(decoded.receipt().worldClosureBytes()) + .isEqualTo(fixture.inputs().worldInventoryReadEvidence().inventory().canonicalBytes()); + assertThat(decoded.receipt().worldClosureDigest()) + .isEqualTo(fixture.inputs().worldInventoryReadEvidence().inventory().digest()); + assertThat(decoded.receipt().familyStates()).hasSize(23); + assertThat(EntityEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes).canonicalBytes()) + .isEqualTo(receiptBytes); + } + + @Test + void rejectsNamespaceReaderPurposeOwnerAndAuthorizationDrift() { + var binding = fixture.authorization(); + assertThatThrownBy( + () -> + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + 1, "other", UUID.randomUUID(), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), fixture.wrongOwnerAuthorization())) + .isInstanceOf(IllegalArgumentException.class); + + var request = EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request()); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder().setTerminalReadPurpose("ENTITY_INTAKE_RETENTION").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedBinding = request.getOriginalIntakeAuthorizationBinding().toByteArray(); + changedBinding[4] ^= 1; + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding)) + .setIntakeAuthorizationDigest( + DraftAuthorizationFenceBinding.digest(changedBinding)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedReceiptDigestEchoUnknownFieldsAndTrailingBytes() { + var request = request(); + var response = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())); + + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setResult( + EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder().setReceiptDigest("sha256:" + "0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("12121212-1212-4212-8212-121212121212")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + var requestUnknown = + ReadSelectedSourceIntakeTerminalRequest.newBuilder() + .mergeFrom(EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)) + .setUnknownFields(unknownFields()) + .build(); + assertThatThrownBy( + () -> EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(requestUnknown)) + .isInstanceOf(IllegalArgumentException.class); + var responseUnknown = response.toBuilder().setUnknownFields(unknownFields()).build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, responseUnknown)) + .isInstanceOf(IllegalArgumentException.class); + + byte[] trailing = + java.util.Arrays.copyOf( + response.getCommittedEmptyReceipt().toByteArray(), + response.getCommittedEmptyReceipt().size() + 1); + trailing[trailing.length - 1] = 0x55; + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(trailing)) + .setReceiptDigest(DraftAuthorizationFenceBinding.digest(trailing)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedReceipt = response.getCommittedEmptyReceipt().toByteArray(); + changedReceipt[changedReceipt.length - 1] ^= 1; + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(changedReceipt)) + .setReceiptDigest(DraftAuthorizationFenceBinding.digest(changedReceipt)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsOverBudgetRequestAndReceipt() { + var request = request(); + byte[] oversizedBinding = + new byte + [net.firedevops.firemud.common.account.sourceintake + .SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + 1]; + var oversizedRequest = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(oversizedBinding)) + .build(); + assertThatThrownBy( + () -> EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(oversizedRequest)) + .isInstanceOf(IllegalArgumentException.class); + + byte[] oversizedReceipt = new byte[EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + 1]; + var oversizedResponse = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())) + .toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(oversizedReceipt)) + .build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static EntitySelectedSourceIntakeTerminalReadEvidence.Request request() { + return EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + "test", fixture.authorization()); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java new file mode 100644 index 0000000000..d20a72cca2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import 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.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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; + +/** Synthetic missing-receipt transport proof for client mTLS and server workload pinning only. */ +class AutomationSelectedSourceIntakeTerminalReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String AUTOMATION_URI = + "spiffe://firemud/ns/test/sa/automation-scripting-service"; + + @TempDir static Path tempDirectory; + + private static GameLogicIntakeSourceReadTransportTest.TestPki pki; + private static GameLogicIntakeSourceReadTransportTest.TestIdentity automationServer; + private static GameLogicIntakeSourceReadTransportTest.TestIdentity accountClient; + + private Server server; + private AutomationSelectedSourceIntakeTerminalReadClient client; + private final AtomicInteger calls = new AtomicInteger(); + + @BeforeAll + static void certificates() throws Exception { + pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + Path caStore = tempDirectory.resolve("terminal-test-ca.p12"); + Path caFile = tempDirectory.resolve("terminal-test-ca.crt"); + automationServer = + GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, caStore, caFile, "automation-terminal-server", AUTOMATION_URI, true); + accountClient = + GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, caStore, caFile, "account-terminal-client", ACCOUNT_URI, false); + } + + @AfterEach + void closeTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void authenticatesAccountClientAndPinsSameNamespaceAutomationServer() throws Exception { + startServer(automationServer); + final int serverPort = server.getPort(); + client = newClient(accountClient); + client.init(); + + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.NOT_FOUND)); + assertThat(calls).hasValue(1); + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + startServer(pki.wrongServer(), serverPort); + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(1); + } + + private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) + throws Exception { + startServer(identity, 0); + } + + private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity, int port) + throws Exception { + var service = + new AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceImplBase() { + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + observer.onError(Status.NOT_FOUND.asRuntimeException()); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", port)) + .maxInboundMessageSize( + net.firedevops.firemud.common.automation.sourceintake + .AutomationSelectedSourceIntakeTerminalReadGrpcCodec.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 AutomationSelectedSourceIntakeTerminalReadClient newClient( + GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAutomationScriptingService("localhost:" + server.getPort()); + return new AutomationSelectedSourceIntakeTerminalReadClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence.Request request() { + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.owner()) + .thenReturn( + net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + when(binding.targetNamespace()).thenReturn(NAMESPACE); + when(binding.schema()).thenReturn("account-automation-intake-authorization/v1"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.canonicalBytes()).thenReturn(new byte[] {1, 2, 3}); + when(binding.digest()).thenReturn("sha256:" + "a".repeat(64)); + when(binding.operationId()).thenReturn(UUID.randomUUID()); + when(binding.fenceId()).thenReturn(UUID.randomUUID()); + when(binding.intakeRequestId()).thenReturn(UUID.randomUUID()); + return AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java new file mode 100644 index 0000000000..d2ff343574 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import 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.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.entity.sourceintake.GrpcEntitySelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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; + +/** Synthetic missing-receipt transport proof for client mTLS and server workload pinning only. */ +class GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String ENTITY_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + + @TempDir static Path tempDirectory; + + private static GameLogicIntakeSourceReadTransportTest.TestPki pki; + private static GameLogicIntakeSourceReadTransportTest.TestIdentity entityServer; + private static GameLogicIntakeSourceReadTransportTest.TestIdentity accountClient; + + private Server server; + private GrpcEntitySelectedSourceIntakeTerminalReadClient client; + private final AtomicInteger calls = new AtomicInteger(); + + @BeforeAll + static void certificates() throws Exception { + pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + Path caStore = tempDirectory.resolve("terminal-test-ca.p12"); + Path caFile = tempDirectory.resolve("terminal-test-ca.crt"); + entityServer = + GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, caStore, caFile, "entity-terminal-server", ENTITY_URI, true); + accountClient = + GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, caStore, caFile, "account-terminal-client", ACCOUNT_URI, false); + } + + @AfterEach + void closeTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void authenticatesAccountClientAndPinsSameNamespaceEntityServer() throws Exception { + startServer(entityServer); + final int serverPort = server.getPort(); + client = newClient(accountClient); + client.init(); + + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.NOT_FOUND)); + assertThat(calls).hasValue(1); + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + startServer(pki.wrongServer(), serverPort); + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(1); + } + + private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) + throws Exception { + startServer(identity, 0); + } + + private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity, int port) + throws Exception { + var service = + new EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceImplBase() { + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + observer.onError(Status.NOT_FOUND.asRuntimeException()); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", port)) + .maxInboundMessageSize( + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.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 GrpcEntitySelectedSourceIntakeTerminalReadClient newClient( + GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("localhost:" + server.getPort()); + return new GrpcEntitySelectedSourceIntakeTerminalReadClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static EntitySelectedSourceIntakeTerminalReadEvidence.Request request() { + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.owner()) + .thenReturn( + net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + when(binding.targetNamespace()).thenReturn(NAMESPACE); + when(binding.schema()).thenReturn("account-entity-intake-authorization/v1"); + when(binding.purpose()).thenReturn("ENTITY_INTAKE_RETENTION"); + when(binding.canonicalBytes()).thenReturn(new byte[] {1, 2, 3}); + when(binding.digest()).thenReturn("sha256:" + "a".repeat(64)); + when(binding.operationId()).thenReturn(UUID.randomUUID()); + when(binding.fenceId()).thenReturn(UUID.randomUUID()); + when(binding.intakeRequestId()).thenReturn(UUID.randomUUID()); + return EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodecTest.java new file mode 100644 index 0000000000..f8f12666cb --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodecTest.java @@ -0,0 +1,40 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import org.junit.jupiter.api.Test; + +class SelectedOwnerWorldInventoryReadGrpcCodecTest { + @Test + void rejectsIncompleteOrUnknownRequestsBeforeOwnerStorageCanBeReached() { + var missing = ReadSelectedOwnerWorldInventoryRequest.getDefaultInstance(); + var unknown = + missing.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(missing)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsWireMessagesAboveTheFiniteRecipientReadBudget() { + var oversized = + ReadSelectedOwnerWorldInventoryRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding( + com.google.protobuf.ByteString.copyFrom( + new byte[SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES + 1])) + .build(); + + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire limit"); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java new file mode 100644 index 0000000000..27402243de --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedOwnerInventoryReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered recipient-specific gRPC boundary; authenticates before parsing the request. */ +public final class WorldSelectedOwnerInventoryReadGrpcService + extends WorldSelectedOwnerInventoryReadServiceGrpc + .WorldSelectedOwnerInventoryReadServiceImplBase { + private final String trustedNamespace; + private final WorldSelectedOwnerInventoryReadService readService; + + public WorldSelectedOwnerInventoryReadGrpcService( + String trustedNamespace, WorldSelectedOwnerInventoryReadService readService) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + this.readService = Objects.requireNonNull(readService, "readService"); + } + + @Override + public void readSelectedOwnerWorldInventory( + ReadSelectedOwnerWorldInventoryRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedOwnerPeer(responseObserver)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "World owner inventory read requires an independent owner operation"); + return; + } + + final SelectedOwnerWorldInventoryReadEvidence.Request decoded; + try { + decoded = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete bounded selected-owner World inventory request is required"); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace()) + || !peerMatchesOwner(decoded.authorizationBinding().owner())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "World inventory namespace and owner must match the authenticated recipient"); + return; + } + + final ReadSelectedOwnerWorldInventoryResponse response; + try { + var evidence = readService.read(decoded); + response = SelectedOwnerWorldInventoryReadGrpcCodec.toResponse(decoded, evidence.inventory()); + } catch (StatusRuntimeException failure) { + responseObserver.onError(failure); + return; + } catch (SecurityException denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Account did not confirm the exact selected-owner World closure read"); + return; + } catch (WorldDesignPublicationFenceRepository.ConflictException + | IllegalArgumentException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Exact retained World artifact inventory is unavailable"); + return; + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "World selected inventory owner storage is unavailable"); + return; + } catch (RuntimeException failure) { + fail( + responseObserver, + Status.UNAVAILABLE, + "World selected-owner authorization or inventory read failed"); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedOwnerPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + fail( + responseObserver, + Status.UNAUTHENTICATED, + "Verified Entity or Automation workload required"); + return false; + } + boolean entity = isExpectedPeer(peer, "entity-management-service"); + boolean automation = isExpectedPeer(peer, "automation-scripting-service"); + if ((entity || automation) && !SessionContext.hasAuthenticatedCallerContext()) return true; + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only a same-namespace Entity or Automation workload without end-user context is allowed"); + return false; + } + + private boolean isExpectedPeer(GrpcPeerIdentity peer, String service) { + String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/" + service; + return expected.equals(peer.uri()) + && peer.isService(service) + && peer.isInNamespace(trustedNamespace); + } + + private boolean peerMatchesOwner(Owner owner) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedService = + owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + return peer != null && isExpectedPeer(peer, expectedService); + } + + private static void fail(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java new file mode 100644 index 0000000000..e3c170b6fa --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-confirmed composition for the exact recipient-specific retained World inventory. */ +final class WorldSelectedOwnerInventoryReadService { + private final String trustedNamespace; + private final WorldSelectedPublicationArtifactInventoryReadService inventoryReadService; + private final SelectedOwnerIntakeWorldClosureAuthorizationReadClient accountReadClient; + + WorldSelectedOwnerInventoryReadService( + String trustedNamespace, + WorldSelectedPublicationArtifactInventoryReadService inventoryReadService, + SelectedOwnerIntakeWorldClosureAuthorizationReadClient accountReadClient) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = Objects.requireNonNull(trustedNamespace, "trustedNamespace"); + this.inventoryReadService = + Objects.requireNonNull(inventoryReadService, "inventoryReadService"); + this.accountReadClient = Objects.requireNonNull(accountReadClient, "accountReadClient"); + } + + SelectedOwnerWorldInventoryReadEvidence read( + SelectedOwnerWorldInventoryReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World owner inventory read requires no ambient SQL"); + } + if (!trustedNamespace.equals(request.targetNamespace())) { + throw new SecurityException("World owner inventory namespace differs from this workload"); + } + requireAuthenticatedRecipient(request); + var accountRequest = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + trustedNamespace, request.authorizationBinding()); + while (accountRequest.readRequestId().equals(request.readRequestId())) { + accountRequest = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + trustedNamespace, request.authorizationBinding()); + } + var accountEvidence = accountReadClient.readHeld(accountRequest); + if (accountEvidence == null || !sameAccountRequest(accountRequest, accountEvidence.request())) { + throw new SecurityException("Account changed the exact World closure authorization read"); + } + + var inventory = inventoryReadService.readRetained(request.freezeEvidence()); + return new SelectedOwnerWorldInventoryReadEvidence(request, inventory); + } + + private void requireAuthenticatedRecipient( + SelectedOwnerWorldInventoryReadEvidence.Request request) { + var binding = request.authorizationBinding(); + String service = + binding.owner() == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/" + service; + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!expected.equals(binding.intendedReader()) + || peer == null + || !expected.equals(peer.uri()) + || !peer.isService(service) + || !peer.isInNamespace(trustedNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException("Exact same-namespace selected-owner workload is required"); + } + } + + private static boolean sameAccountRequest( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request expected, + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request actual) { + return actual != null + && expected.schemaVersion() == actual.schemaVersion() + && expected.targetNamespace().equals(actual.targetNamespace()) + && expected.readRequestId().equals(actual.readRequestId()) + && expected.intendedReader().equals(actual.intendedReader()) + && expected.closureReadPurpose().equals(actual.closureReadPurpose()) + && Arrays.equals(expected.binding().canonicalBytes(), actual.binding().canonicalBytes()); + } +} diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java new file mode 100644 index 0000000000..5fbdea3f93 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java @@ -0,0 +1,504 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic exact source/freeze fixtures; Account and retained storage are explicit boundaries. */ +class WorldSelectedOwnerInventoryReadServiceTest { + private static final String NAMESPACE = "firemud"; + + @AfterEach + void clearRequestContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesOwnerWorkloadBeforeParsingAndRequiresIndependentRead() { + var inventory = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + var orchestrator = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventory, account); + var receiver = new WorldSelectedOwnerInventoryReadGrpcService(NAMESPACE, orchestrator); + var malformed = ReadSelectedOwnerWorldInventoryRequest.getDefaultInstance(); + + var anonymous = new RecordingObserver(); + withoutPeer(() -> receiver.readSelectedOwnerWorldInventory(malformed, anonymous)); + assertDenied(anonymous, Status.Code.UNAUTHENTICATED); + + var wrongWorkload = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, wrongWorkload)); + assertDenied(wrongWorkload, Status.Code.PERMISSION_DENIED); + + var wrongNamespace = new RecordingObserver(); + withPeer( + peer("other", "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, wrongNamespace)); + assertDenied(wrongNamespace, Status.Code.PERMISSION_DENIED); + + SessionContext.setContext( + "11111111-1111-4111-8111-111111111111", java.util.List.of(), java.util.Map.of()); + var endUser = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "automation-scripting-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, endUser)); + assertDenied(endUser, Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + var ambient = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, ambient)); + assertDenied(ambient, Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + var authenticatedMalformed = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, authenticatedMalformed)); + assertDenied(authenticatedMalformed, Status.Code.INVALID_ARGUMENT); + + var authenticatedAutomationMalformed = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "automation-scripting-service"), + () -> + receiver.readSelectedOwnerWorldInventory(malformed, authenticatedAutomationMalformed)); + assertDenied(authenticatedAutomationMalformed, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(inventory, account); + } + + @Test + void accountConfirmationPrecedesTheExactRetainedReadForBothOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = fixture(owner); + var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + var retainedInventory = mock(WorldSelectedPublicationArtifactInventoryEvidence.class); + when(retainedInventory.freezeEvidence()).thenReturn(fixture.freezeEvidence()); + when(retainedInventory.canonicalBytes()).thenReturn(new byte[] {1, 2, 3}); + when(retainedInventory.digest()).thenReturn("sha256:" + "a".repeat(64)); + + var callOrder = new ArrayList(); + when(account.readHeld(any())) + .thenAnswer( + invocation -> { + var request = + (SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request) + invocation.getArgument(0); + callOrder.add("account"); + assertThat(request.binding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(request.intendedReader()) + .isEqualTo("spiffe://firemud/ns/firemud/sa/world-management-service"); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.readRequestId()).isNotEqualTo(fixture.request().readRequestId()); + assertThat(request.closureReadPurpose()) + .isEqualTo( + owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"); + return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(request); + }); + when(inventoryRead.readRetained(fixture.freezeEvidence())) + .thenAnswer( + invocation -> { + callOrder.add("retained-world"); + return retainedInventory; + }); + + var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); + var result = + withPeer(peer(NAMESPACE, serviceName(owner)), () -> service.read(fixture.request())); + + assertThat(callOrder).containsExactly("account", "retained-world"); + assertThat(result.request()).isEqualTo(fixture.request()); + assertThat(result.request().authorizationBinding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(result.inventory()).isSameAs(retainedInventory); + verify(account).readHeld(any()); + verify(inventoryRead).readRetained(fixture.freezeEvidence()); + } + } + + @Test + void absentOrChangedAccountEchoNeverReadsWorldStorage() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = fixture(owner); + for (boolean absent : List.of(true, false)) { + var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + when(account.readHeld(any())) + .thenAnswer( + invocation -> { + var expected = + (SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request) + invocation.getArgument(0); + if (absent) return null; + var changed = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + NAMESPACE, fixture.binding()); + while (changed.readRequestId().equals(expected.readRequestId())) { + changed = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + NAMESPACE, fixture.binding()); + } + return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(changed); + }); + var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); + + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, serviceName(owner)), () -> service.read(fixture.request()))) + .isInstanceOf(SecurityException.class); + verify(inventoryRead, never()).readRetained(any()); + } + } + } + + @Test + void domainServiceRejectsWrongRecipientEndUserAndAmbientSqlBeforeAccountCall() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = fixture(owner); + var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); + String caller = serviceName(owner); + String wrongCaller = + serviceName( + owner == Owner.ENTITY_MANAGEMENT + ? Owner.AUTOMATION_SCRIPTING + : Owner.ENTITY_MANAGEMENT); + + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, wrongCaller), () -> service.read(fixture.request()))) + .isInstanceOf(SecurityException.class); + + SessionContext.setContext("abababab-abab-4bab-8bab-abababababab", List.of(), Map.of()); + try { + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, caller), () -> service.read(fixture.request()))) + .isInstanceOf(SecurityException.class); + } finally { + SessionContext.clear(); + } + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, caller), () -> service.read(fixture.request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(account, inventoryRead); + } + } + + private static Fixture fixture(Owner owner) { + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID version = id("22222222-2222-4222-8222-222222222222"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + var selected = + DraftCommitBinding.create( + new TargetProof(tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("synthetic-fixture-command"))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + version.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + id("55555555-5555-4555-8555-555555555555"), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + actor, + selected); + var content = sourceContent(scope); + var binding = + new SelectedOwnerIntakeAuthorizationBinding( + content, + List.of( + source(SourceKind.TENANT, tenant.toString(), "tenant"), + source(SourceKind.ACCOUNT, actor.toString(), "account"), + source(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership"))); + + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "9", + "source-intake test", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var publicationBinding = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1}))); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + tenant, + version, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + publicationBinding); + var acknowledgement = + new Acknowledgement( + freezeRequest, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 3); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + return new Fixture( + binding, + freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, binding, freezeEvidence)); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = sourceSnapshot(family, scope.selected()); + DraftAuthorizationFenceBinding.frame(out, family); + DraftAuthorizationFenceBinding.frame(out, snapshot); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + return switch (family) { + case "COMMAND" -> + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest( + "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + 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()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "TEMPLATE_CONFIG" -> + new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); + }; + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static String serviceName(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record Fixture( + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence.Request request) {} + + private static void assertDenied(RecordingObserver observer, Status.Code code) { + assertThat(Status.fromThrowable(observer.error).getCode()).isEqualTo(code); + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static T withPeer(GrpcPeerIdentity peer, java.util.function.Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + withPeer( + peer, + () -> { + action.run(); + return null; + }); + } + + private static void withoutPeer(Runnable action) { + Context previous = Context.ROOT.attach(); + try { + action.run(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingObserver + implements StreamObserver { + ReadSelectedOwnerWorldInventoryResponse response; + Throwable error; + boolean completed; + + @Override + public void onNext(ReadSelectedOwnerWorldInventoryResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Test observer intentionally retains the reported failure.") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 288cb2a8f0b0798ec9d575a5d523510a3618a38e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:08:18 +1300 Subject: [PATCH 02/27] Prepare final intake migrations after selected source frontier --- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 2 +- ...ted_owner_intake_final_authorizations.sql} | 0 ...cted_owner_intake_terminal_settlement.sql} | 0 ...cted_owner_intake_terminal_settlement.sql} | 0 ...eAuthorizationPostgresIntegrationTest.java | 145 ++++++++++++++---- .../AccountControlUiOwnerSourcesFixture.java | 4 +- 7 files changed, 121 insertions(+), 32 deletions(-) rename services/account-service/src/main/resources/db/migration/{V1007__selected_owner_intake_final_authorizations.sql => V1008__selected_owner_intake_final_authorizations.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V1008__selected_owner_intake_terminal_settlement.sql => V1009__selected_owner_intake_terminal_settlement.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V1009__entity_selected_owner_intake_terminal_settlement.sql => V1010__entity_selected_owner_intake_terminal_settlement.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 e69b679bdf..23d07d3fc1 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 intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement in forward V1006–V1009. It preserves the actual V1005 combined parent and prior protection/disposal guards. These components remain unregistered and unqualified; 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 intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. PostgreSQL upgrade and final-owner proofs have not run. These components remain unregistered and unqualified; 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 9caa623ba1..982b34f2c5 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. New forward Account V1006–V1009 follow the actual V1005 plus Saga parent; existing publication, World participation, protection and disposal history remains unchanged. The prepared upgrade proofs retain parent rows, source bytes, history and xmin, but have not run. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. Qualification and publication are pending; no selected-full attestation 4 or genuine Gameplay handoff is complete, 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. Prepared forward Account V1008–V1010 final authorization and terminal settlement follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. The prepared combined-V1007 upgrade proof compares complete prior Flyway metadata and xmin, populated Account/source/disposal/Saga rows and preliminary reservation bytes, and inherited protection, alignment and source-exclusion guards. The separate V1009-to-V1010 proof retains Automation terminal bytes and pending Entity participation. These proofs have not run. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. Qualification and publication are pending; no selected-full attestation 4 or genuine Gameplay handoff is complete, 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/V1007__selected_owner_intake_final_authorizations.sql b/services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_final_authorizations.sql rename to services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql diff --git a/services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_terminal_settlement.sql rename to services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql diff --git a/services/account-service/src/main/resources/db/migration/V1009__entity_selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V1009__entity_selected_owner_intake_terminal_settlement.sql rename to services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 3f612b8225..696b0f34d7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -813,7 +813,54 @@ void commitsExactEntityEmptySettlementAndReleasesOnlyThatOperation() throws Exce } @Test - void migratesRetainedV1008AutomationBytesWithoutReleasingPendingEntity() throws Exception { + void upgradesCombinedV1007ParentThroughFinalAuthorizationAndBothTerminalOwnersWithoutBackfill() + throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), + redis.getHost(), redis.getMappedPort(6379), temporary, UUID.randomUUID(), + Clock.systemUTC(), "1007")) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + assertThat(f.dsl.fetch("SELECT version FROM flyway_schema_history WHERE success") + .getValues(0, String.class)) + .contains("1000", "1001", "1002", "1005", "1006", "1007") + .doesNotContain("1008", "1009", "1010"); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservations = new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var scope = asGameDesign(() -> reservations.reserveSourceRead( + issued.compact(), UUID.randomUUID(), Owner.ENTITY_MANAGEMENT, selected, issued.environment())); + seedRetainedCombinedParentRows(f.dsl); + var retainedRows = retainedCombinedParentRows(f.dsl); + assertThat(retainedRows.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 NOT IN ('1008', '1009', '1010') ORDER BY installed_rank"; + var retainedHistory = f.dsl.fetch(historyQuery).getValues(0, String.class); + var inheritedGuards = retainedInheritedGuardDefinitions(f.dsl); + assertThat(inheritedGuards.get("account_ss_activation_settlement_insert_guard()")) + .contains("terminal->>'activationResultSha256' IS DISTINCT FROM 'sha256:' || encode(sha256(result_bytes), 'hex')"); + Flyway upgrade = intakeMigration(f, "1010"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(3); + upgrade.validate(); + assertThat(f.dsl.fetch(historyQuery).getValues(0, String.class)).isEqualTo(retainedHistory); + assertThat(retainedCombinedParentRows(f.dsl)).isEqualTo(retainedRows); + assertThat(retainedInheritedGuardDefinitions(f.dsl)).isEqualTo(inheritedGuards); + for (String table : List.of("account_selected_owner_intake_authorizations", + "account_selected_owner_intake_sources", "account_selected_owner_intake_settlements")) { + assertThat(f.dsl.fetchCount(org.jooq.impl.DSL.table(table))).isZero(); + } + assertThat(f.dsl.fetchSingle("SELECT account_selected_owner_intake_source_read_is_pending(?)", + scope.operationId()).get(0, Boolean.class)).isTrue(); + } + } + + @Test + void migratesRetainedV1009AutomationBytesWithoutReleasingPendingEntity() throws Exception { try (var fixture = new AccountControlUiOriginalOrderFixture( postgres.getJdbcUrl(), @@ -824,7 +871,7 @@ void migratesRetainedV1008AutomationBytesWithoutReleasingPendingEntity() throws temporary, UUID.randomUUID(), Clock.systemUTC(), - "1008")) { + "1009")) { var issued = fixture.issueCreator(); var f = issued.sources(); var selected = selectedForSettlement(f.tenant); @@ -834,11 +881,11 @@ void migratesRetainedV1008AutomationBytesWithoutReleasingPendingEntity() throws new AccountSelectedOwnerIntakeSourceReservationService( issued.actors(), f.fences, repository, f.manager, "test"); var automation = - finalizeAutomationBinding(issued, reservations, repository, selected, "retained-v1008"); + finalizeAutomationBinding(issued, reservations, repository, selected, "retained-v1009"); var original = f.tx(() -> repository.settleCommittedEmpty(terminalEvidence(automation, 8801, 8802))); var entity = - finalizeEntityBinding(issued, reservations, repository, selected, "pending-v1008-entity"); + finalizeEntityBinding(issued, reservations, repository, selected, "pending-v1009-entity"); var terminal = entityTerminalEvidence(entity, 8901, 8902); byte[] retainedAuthorization = f.dsl @@ -859,36 +906,22 @@ void migratesRetainedV1008AutomationBytesWithoutReleasingPendingEntity() throws terminal.receipt().canonicalBytes(), "active Automation authorization"); - String historyQuery = "SELECT installed_rank || ':' || version || ':' || script || ':' " - + "|| checksum || ':' || success FROM flyway_schema_history " - + "WHERE version IS NOT NULL AND version <> '1009' ORDER BY installed_rank"; + seedRetainedCombinedParentRows(f.dsl); + var retainedParents = retainedCombinedParentRows(f.dsl); + 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 <> '1010' " + + "ORDER BY installed_rank"; var retainedHistory = f.dsl.fetch(historyQuery).getValues(0, String.class); Map> retainedRows = retainedSelectedOwnerRows(f.dsl); - String schema = f.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); - Path current = Path.of("").toAbsolutePath(); - while (current != null - && !java.nio.file.Files.isDirectory( - current.resolve("services/account-service/src/main/resources/db/migration"))) { - current = current.getParent(); - } - Path migrations = - Objects.requireNonNull(current, "Account migrations must be available") - .resolve("services/account-service/src/main/resources/db/migration"); - Flyway.configure() - .dataSource(Objects.requireNonNull(f.manager.getDataSource())) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("filesystem:" + migrations, - "filesystem:" + Objects.requireNonNull(current) - .resolve("services/common-saga/src/main/resources/db/migration/saga")) - .target("1009") - .load() - .migrate(); + Flyway upgrade = intakeMigration(f, "1010"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); + upgrade.validate(); assertThat(f.dsl.fetch(historyQuery).getValues(0, String.class)).isEqualTo(retainedHistory); assertThat(retainedSelectedOwnerRows(f.dsl)).isEqualTo(retainedRows); + assertThat(retainedCombinedParentRows(f.dsl)).isEqualTo(retainedParents); var recovered = f.tx(() -> repository.findSettlement(automation).orElseThrow()); assertThat(recovered.canonicalBytes()).isEqualTo(original.canonicalBytes()); @@ -2178,6 +2211,62 @@ private static void awaitSourceLockWait(DSLContext dsl, int writerBackendPid) throw new AssertionError("Source writer did not block on settlement-held source locks"); } + private static Flyway intakeMigration(AccountControlUiOwnerSourcesFixture f, String target) { + String schema = f.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + Path root = Path.of("").toAbsolutePath(); + while (root != null && !java.nio.file.Files.isDirectory( + root.resolve("services/account-service/src/main/resources/db/migration"))) { + root = root.getParent(); + } + Path repositoryRoot = Objects.requireNonNull(root, "Account migrations must be available"); + return Flyway.configure() + .dataSource(Objects.requireNonNull(f.manager.getDataSource())) + .schemas(schema).defaultSchema(schema).placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + repositoryRoot.resolve("services/account-service/src/main/resources/db/migration"), + "filesystem:" + repositoryRoot.resolve("services/common-saga/src/main/resources/db/migration/saga")) + .target(target).load(); + } + + private static void seedRetainedCombinedParentRows(DSLContext dsl) { + Long sagaId = dsl.fetchSingle( + "INSERT INTO saga_instance(saga_name, state) VALUES (?, ?) RETURNING id", + "retained-final-intake-upgrade", "PENDING").get(0, Long.class); + dsl.execute("INSERT INTO saga_step(instance_id, name, status, attempt) VALUES (?, ?, ?, ?)", + sagaId, "retained-step", "PENDING", 3); + dsl.execute( + "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(StandardCharsets.UTF_8)); + } + + private static Map> retainedCombinedParentRows(DSLContext dsl) { + Map> rows = new LinkedHashMap<>(); + for (String table : List.of("accounts", "account_authority_source_records", + "account_initial_gameplay_login_disposals", "saga_instance", "saga_step", + "account_selected_owner_intake_source_read_reservations", + "account_selected_owner_intake_source_read_sources")) { + rows.put(table, dsl.fetch( + "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + + table + " t ORDER BY to_jsonb(t)::TEXT").getValues(0, String.class)); + } + return rows; + } + + private static Map retainedInheritedGuardDefinitions(DSLContext dsl) { + Map definitions = new LinkedHashMap<>(); + for (String signature : List.of("account_ss_admission_assert_no_pending(text[])", + "account_ss_activation_insert_guard()", "account_ss_activation_settlement_insert_guard()", + "account_initial_gameplay_login_disposal_immutable()", "account_initial_gameplay_login_writer_guard()", + "account_control_ui_hold_required_sources(text[])", "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()")) { + definitions.put(signature, + dsl.fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature).get(0, String.class)); + } + return definitions; + } + private static Map> retainedSelectedOwnerRows(DSLContext dsl) { Map> rows = new LinkedHashMap<>(); for (String table : List.of("account_selected_owner_intake_source_read_reservations", 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 791d65e020..e50c960ced 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) && !"1008".equals(migrationTarget)) { + if (migrationTarget != null && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) && !"1007".equals(migrationTarget) && !"1009".equals(migrationTarget)) { throw new IllegalArgumentException( - "Only the preserved 160.1 source-retention, 1006 preliminary source-read, or 1008 selected-owner predecessor is supported"); + "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, or 1009 selected-owner predecessor is supported"); } this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); From 9beb52cc41d55ddc5757705c7e89d21baa18af79 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 03/27] 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 0075516cc0bc01e1efa814446c3236c8d12baf0e 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 04/27] 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 ec4941df1f175cfdc7cdeff36dc98cfc43a240ed Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:51:30 +1300 Subject: [PATCH 05/27] fix: preserve complete settlement files after carry resolution --- .../player-access-and-session.md | 361 +++++++++++++++ .../AccountControlUiOwnerSourcesFixture.java | 431 ++++++++++++++++++ ...electedOwnerIntakeClientLifecycleTest.java | 99 ++++ 3 files changed, 891 insertions(+) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 91277eaa2c..5f2234f6cd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -11,3 +11,364 @@ This is a non-normative implementation tracker for player access and session. Ca 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. Prepared forward Account V1008–V1010 final authorization and terminal settlement follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. The prepared combined-V1007 upgrade proof compares complete prior Flyway metadata and xmin, populated Account/source/disposal/Saga rows and preliminary reservation bytes, and inherited protection, alignment and source-exclusion guards. The separate V1009-to-V1010 proof retains Automation terminal bytes and pending Entity participation. These proofs have not run. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. Qualification and publication are pending; no selected-full attestation 4 or genuine Gameplay handoff is complete, 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. + +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. + +### 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. + +Local qualification passes the Account check/static/format and all five focused PostgreSQL cases on the canonical PostgreSQL 18 image: 1,414 Account units have no failures or errors and four known skips; native cases have no failures, errors or skips. The namespace proof uses actual Account reservation/finalization and retained original scope, refuses cross-namespace HELD, terminal dispatch, settlement and replay, and preserves six intake tables including row metadata. R3 Common proof executes 630 cases with one oversized large-wire fixture failure; the other 625 cases outside that five-case class remain passing at R3. After correcting the bounded fixture, R5 freshly passes all five mTLS client cases and full Common static/format checks in 43s, including an actual response above the default 4MiB limit and within the 24MiB transport bound. R6 receives the published World preparation parent and passes the focused Account check/static/format, intake unit/native, Common compilation and documentation gate in 1m43s. All five native cases execute freshly without failures, errors or skips; unchanged broad units retain R3 attribution. Published CI and review remain separate. The native Account fixture controls the upstream ORIGINAL AUTHOR readback; it does not prove genuine authoring, the Game Logic retention pipeline or end-to-end settlement. The actual Game Logic intake owner and Game Design receipt pipeline are the next dependency, followed by selected launch-descriptor production. This prerequisite closes no genuine Gameplay handoff and does not resume Unit 1B/corpus. Canonical authority remains in [Account API contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); the receiving source consequence is recorded in [Gameplay Rules](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-intake-prerequisite). + +Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. The [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) provide the bounded executed proof anchors. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player-command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#canonical-gameplay-roster-owner-reads) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). + +The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. + +### Unregistered canonical runtime membership snapshot + +The local Account snapshot preparation uses [AccountCanonicalRuntimeMembershipSnapshotRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java) and [its transaction service](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalRuntimeMembershipSnapshotService.java) to read existing canonical Account/tenant provenance, current owner generations and fence, roles, pair state and four exact source streams. It returns the existing shared content-validator carrier without writes. Tenant generations are equality-only; same-generation billing cutoff fields must equal the actual current tenant source/checkpoint, while different historical generations fail closed. The existing v1 tenant-event codec moved into Common with caller updates and a fixed full-payload/digest regression; the billing receipt remains provenance rather than entitlement authority. + +Focused proof is split by unchanged source attribution: twelve shared validator cases and twenty-two Account transaction/JOIN unit cases passed in the preceding run whose sole failure was an incorrect golden literal. After independently correcting the entitlement request digest in that literal, the full-byte codec case and nine actual PostgreSQL cases pass, including four new snapshot cases and five retained first-JOIN cases, with zero failures, errors or skips. The final 1m 28s gate passes affected Account/Common static and formatting checks. The native snapshot tests cover committed first JOIN, proven missing membership, a different Account UUID and missing role evidence, with unchanged rows and transaction identities on successful reads. Earlier failed source compile and test-vector attempts remain failed evidence. No transport registration, caller authentication, private-realm grant support, entitlement provisioning, actor supply, PLAY activation or full fresh/restart proof is established; `AA-2.1` remains partial. The complete prepared patch still requires independent review before publication. + +### Original StartSession source-protection storage + +The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. + +The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). + +The subsequent Hosted/CLI correction on develop `18f8063306c2ddb4337646de50b73619915a0e25` executed 18 focused Account PostgreSQL cases with zero failures, errors or skips. Acquisition now rejects admission data that cannot satisfy immutable settlement bounds; committed activation fixtures run the acquisition, source-child and deferred-completeness guards. The proof includes the 256-source boundary, canonical Base64 and UTF-16 ordering, a complete activation tuple above 135,168 bytes, and settlement after lease expiry. Actual jOOQ generation, compilation, integration Checkstyle and SpotBugs, formatting and documentation checks passed. This corrects the bounded fixture proof; the older broad source-CI counts remain historical and do not qualify the changed SQL or establish genuine owner production. + +The acquisition/settlement alignment now applies one closed outer lifecycle validator to PREPARING acquisition and ACTIVE settlement, retaining opaque nested launch evidence exactly rather than duplicating its codec or authenticating World. Its final focused gate passes 22 physical PostgreSQL cases (18 admission and four activation), zero failures, errors or skips, in 1m29s: 40 malformed acquisition variants leave no protection/source rows or writer exclusion, while the 58 settlement negatives, retained V1003 upgrade/history/rows, valid ACTIVE and separate ABORTED release remain covered. The control-plane request bound reuses the existing UTF-16 helper. The first attempt failed before SQL in four Activation cases; one bounded retry established the intended red by accepting malformed PREPARING evidence. The subsequent green gate generated jOOQ and passed formatting, integration Checkstyle and SpotBugs. Migration-tip proof now checks all current resolved migrations and explicit V1003/V1004 presence while retaining the frozen 112-artifact parent; the isolated V1003-to-V1004 upgrade remains pinned. + +Exact-source cloud proof for the preceding published `02401d4df0276b04c7f0ff780441a050c4b72fc8` on develop `683c2a2b3417456a2eb5758401a9bc347e53e29a` passes 1,291 executed Account units (four additional defined cases skipped) and all 246 physical integration cases in Validation `38475212382`, job `115564246534`, JUnit artifact `11855135658`. Runtime `38475212357` executes both legacy WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK flows; its separate Smoke Gate fails on missing REST step metadata, with the tooling correction owned by Overseer. These results qualify that preceding SQL only, not this acquisition repair. The original failed local full run remains failed; newer exact-candidate CI and packaged proof remain required. + +The preceding review correction adds forward V1004 lifecycle integrity without rewriting V1003 or earlier applied migrations. The focused final run passed 21 physical PostgreSQL cases (18 admission and three activation), zero failures, errors or skips, in 1m15s. It proves the 114-artifact fresh combined manifest, actual V1002 receiving-parent upgrade, retained V1003 pending protection/source rows and unchanged prior migration ranks/checksums through V1004, closed ACTIVE evidence and 58 malformed carriers retaining writer exclusion, and exact ACTIVE/ABORTED release. jOOQ generation and formatting passed. The broader Account run executed 1,295 unit cases with zero failures/errors and four existing filesystem skips, and 246 integration cases with four failures: two stale manifest assertions, then PostgreSQL connection refusal and Redis fixture startup timeout. The manifest corrections pass in the focused 21-case run; both unavailable endpoint cases subsequently pass in a separate two-case physical retry on unchanged Account inputs. The original full run remains failed and the endpoint cause is unknown; these replacement results do not claim another unfiltered execution. Final integration Checkstyle/SpotBugs and documentation checks passed in 21 seconds. Current published-head CI remains separate, and full local Compose is paused. Upstream owner inputs remain stipulated; authenticated production and activation remain unproved. + +Forward [V1004.1](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql) rejects a COMMITTED settlement with a regressing World `lifecycleEpoch` or `rowVersion`. The corrected focused run passed all 22 physical PostgreSQL cases with zero failures, errors or skips in 1m40s, including the pinned V1003-to-V1004 historical upgrade, a separate V1004-to-V1004.1 comparison of prior migration ranks/checksums and retained pending-protection/source bytes and `xmin`, both counter decreases retaining writer exclusion, and a valid increased epoch with equal row version. The initial consolidated run failed one new fixture assertion because its proposed row-version decrease was equal to the retained zero; that failed result remains retained. The fixture now starts that case at row version one without changing the guard or other fixture defaults. Account integration static and formatting checks pass; jOOQ generation and the broader Account static/unit checks passed in the initial invocation (1,295 unit cases, four existing filesystem skips). Entity checks also passed with 237 unit and 28 integration cases. These are controlled storage fixtures, not authenticated World production or activation; published-head CI remains separate. + +Forward [V1004.2](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql) applies the existing closed PREPARING validator during COMMITTED settlement, covering protection rows legitimately retained by V1003 before V1004 acquisition validation. The focused consolidated run passed 24 physical PostgreSQL cases (18 admission and six activation) with zero failures, errors or skips in 1m58s. Controlled V1003 fixtures remove each counter or encode `lifecycleEpoch` with the wrong JSON type, then upgrade through V1004 and V1004.1 to V1004.2 and require SQLSTATE `23514` while preserving protection/source rows, bytes, `xmin`, history and source-writer exclusion. A separate V1004.1-to-V1004.2 fixture requires uppercase activation-request UUID spelling to fail acquisition with SQLSTATE `23514`, leave no protection or source-child rows, and leave the source writer unblocked. jOOQ generation, affected formatting and static checks passed, as did seven focused Entity selection unit cases after correcting their coverage name. These are storage-integrity proofs only; no authenticated World production or activation is claimed. + +Forward [V1004.3](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) closes the remaining acquisition gap for whitespace-bearing Base64 spellings in the tuple, projection, launch-read, and PREPARING lifecycle carriers. Its controlled PostgreSQL regression matrix covers newline, space, tab, and carriage return per field, requiring SQLSTATE `23514`, no retained protection or source children, and an unblocked source writer; the V1004.2-to-V1004.3 retained-row/history upgrade and all 16 rejection variants pass in the consolidated 3m55s gate. The gate runs 25 fresh Account PostgreSQL cases and full Entity proof of 237 unit and 29 PostgreSQL cases, all without failures, errors or skips. It also proves nullable condition expiry and resource values through the typed legacy INSERT-SELECT path, and passes Account jOOQ, affected static analysis, formatting and documentation checks. Manual-event Flyway self-tests and Ruff pass separately. This remains passive Account storage integrity; no authenticated World production, runtime activation, or full authenticated flow is established. + +The prior local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. + +### Entity character-creation denial + +The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). + +### Account World participation source preparation + +The next source stage prepares the standalone, unregistered World participation terminal-settlement receiver and its strict Common transport. It delegates to the existing Account owner, which independently reads World terminal evidence; caller-provided outcomes cannot settle participation. R80 passes the receiving Account check/static/format gate in 3m15s, freshly executing 1,397 units with zero failures/errors and four existing skips, plus three PostgreSQL participation cases with zero failures/errors/skips. The new receiver and loopback mTLS tests account for seven passing units and use a mocked Account settlement owner; they do not establish actual World terminal authority. R89 freshly passes all five Account participation PostgreSQL/Redis cases, including retained V160.1 scalar-child/unsafe-parent refusal after upgrade. The separate World composition passes three fresh physical cases and exercises actual Account issue/redemption, currentness and participation with controlled upstream issuer/environment inputs. Its wide-fence Account-to-Game Session handoff preserves exact tuple bytes and BIGINT values across actual owners; upgrade refusals preserve retained bytes and row metadata. R92 then passes the full World gate with all 88 native integration and three composition cases executed, retaining the unchanged Account results from R89. Neither source preparation closes genuine issuer authority, current production terminal settlement, deployment, protected activation or any Gameplay handoff. The [Account API owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [World preparation tracker](./world-runtime-and-movement.md#original-startsession-world-preparation-and-recovery) retain those boundaries. + +The current Account source adds an immutable full source capture for the original StartSession operation, Account-owned World participation acquisition and historical-read services, exact current Game Session attempt evidence, and local terminal-settlement storage. The receiving methods remain unregistered and default-inactive. Acquisition reads the actual original Game Session attempt before its Account transaction, then preserves the complete original tuple, attempt/fence, exact response, and unchanged lease expiry beside the separate World participation identity while revalidating and locking the current Account source and reference. The capture reference remains independent of the issuance fence. The historical read is credential-free and returns retained evidence; terminal settlement requires an exact World-owned result. These sources add no credential issuance, redemption, renewal, runtime admission, or new authority. + +Migration intake maps donor V128 source capture to receiving V158, donor V129 World participation to V159, and donor V131 actual-original-Game-Session-attempt evidence to V160. Published [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql) separately replaces the legacy bundle-source/issuance-fence equality with the canonical positive-BIGINT source-fence check; capture and issuance fences remain independent. Prior receiving migrations through V157 and the protected V1–V40, V40.1, V53, and V73 remain unchanged. This source cut does not include the World runtime owner or the continuous Game Session admission protection tracked by V133/V134. The shared World terminal value and client/codec remain internal integrity and transport sources, not genuine World terminal authority. At original child tip `38c5a26e21d73282f75183d7c58f2746f9c9e391`, the authorized Account/Common checks, jOOQ generation, integration-source compilation, and Checkstyle gate passed. The Account/Common test results report 1,224 unit/test cases with zero failures and four skipped, plus 193 integration cases with zero failures and 190 skipped. All 20 focused PostgreSQL-backed cases were skipped: authorization repository (8), source capture (1), World participation repository (1), original-attempt evidence (3), owner composition (1), and disclosure handoff (6). No physical PostgreSQL or Redis execution, current real-key custody, runtime activation, or playable closure is claimed. Account-local contract and storage consequences are recorded in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status); this tracker records implementation and proof status only. The normative original-operation read constraints remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). + +At reconciled local candidate head `94aece5bbe4ca1aa537dcb6367921f99e439423e`, `FIREMUD_LOCK_GRADLE_WAIT=1 bash dev-tools/validation/run-locked-gradle.sh :account-service:check linkCheck lintMarkdown -PfullCheck` passed in 2m 38s. Fresh Account XML reports 1,255 unit cases with zero failures, zero errors, and four skipped, plus 205 integration cases with zero failures, zero errors, and 202 skipped. All 20 focused PostgreSQL-backed cases were skipped. This exact-head local check does not establish physical PostgreSQL or Redis execution, current real-key custody, runtime activation, or playable completion. + +At local current-parent source `c7a61401f2220f70d567b7709397b967daf5e991`, the Account/Common Security full gate failed in 11m39s after 1,278 unit cases passed (four skips) and 222 physical integration cases ran with zero skips: 214 passed, while eight `AccountFirstJoinAuthorityStorageIntegrationTest` cases refused `localhost:55056` before Flyway migration (`SQLState 08001`). Captured PostgreSQL TCP readiness preceded Testcontainers startup and all failures preceded normal cleanup; no source fixture mistake or OOM was demonstrated, and the host-endpoint cause remains unknown. This does not claim a passing full Account gate; the replacement exact-head CI and subsequent current-parent proof are recorded in the next paragraph. + +Published commit `0a84bfa2800c6f33f3d85023c786a9fdd80ff0ba` passed [exact-head validation run 38276405663](https://github.com/benhook1013/FireMUD/actions/runs/38276405663): all 1,278 unit cases had zero failures or errors (four skipped), and all 222 physical integration cases passed with zero failures, errors, or skips, including the eight FirstJoin storage cases previously refused locally. The local current-parent carry at `932f2e1334a9ffa31fdf3be177a0fdbcd588a0e5` then passed the locked Account check and focused `AccountGameplayDelegationRedisIntegrationTest`, along with formatting and documentation checks, in 2m56s: 1,280 unit cases had zero failures or errors (four skipped), and five targeted physical integration cases had zero failures, errors, or skips. This carry changed only three inherited Account paths, preserving the child-owned source and SQL history. These results prove the listed exact-head CI scope and focused current-parent composition; they do not establish an unfiltered 222-case physical integration run on the new head or runtime activation. + +At correction source `0f049f5bf5d45b2b9663385eec53efff8f1bf757`, local unit checks passed 1,289 Account cases (four skips), 437 Common Core cases and 159 Common Security cases without failures or errors. Ten selected physical PostgreSQL/Redis cases passed without failures, errors or skips: seven [disclosure-handoff cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java), two [participation repository cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java), and one [Account original-authorization/acquisition/settlement composition case](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java). The new repository case commits real Account evidence, discards the acquisition response, waits for the retained original lease to expire, verifies current lookup refusal and recovers the immutable participation coordinates from the unchanged original tuple; the upstream Game Session observation is stipulated. This was a filtered physical run. The subsequent full local Account gate ran 224 physical cases with zero skips: 220 passed and four `AccountControlUiOwnerWorkflowPostgresIntegrationTest` cases failed before Flyway because `localhost:57418` refused connections (`SQLState 08001`). The endpoint cause remains unknown; the full gate did not pass. Static-only closeout then passed without rerunning the physical suite. These results do not establish a genuine World terminal, failed-acquisition settlement, deployed owner custody, runtime registration or admission. + +This preparation is owned by the existing `AA-1.3` row, which already tracks the original StartSession operator authorization/reference and original-ACK sources. Its implementation anchors include [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), and [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java). + +The owner-tuple source prepares Account-returned complete post-authorization evidence for ISSUE/RECOVER/REDEEM; Logging & Admin compares and persists that tuple for handoff, and Game Session retains and compares it for redemption and launch. The canonical binding and read rules remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with service consequences in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md). StartSession current-execution checks apply ADR 0047's exact `reservationClaimFence` representation rule; the local combined correction gate passed 444 Common Core unit cases and 19 physical Game Session owner-attempt PostgreSQL cases with no failures, errors, or skips, including safe-boundary, adjacent wide-fence and maximum-fence replay. Affected static, formatting and documentation checks passed. Current published-head CI and the commissioned independent review remain separate. Historical scalar projections remain read-only and do not satisfy current-use verification. The prepared sources do not activate runtime ingress or establish genuine Account authority. + +At observed tracker HEAD `a578e07864a5385ab0879ca252e2fb66a47268b2`, 13 producer postimages were independently tested on baseline `85a` and then committed as `c3caf701a9bf4543446acc6263b9573bb4a11bcd`: Account passed 1,291 unit cases (four skipped) and three PostgreSQL cases; Logging & Admin passed 249 unit and 14 PostgreSQL cases, all without failures or errors. The Game Session producer run covered only its unchanged 2,132-case baseline. Consumer checks exercised 30 dirty consumer postimages on baseline `85a`, not a clean commit-only consumer revision: Common Core 441 and Common Security 159 unit cases passed; Account passed 1,291 unit cases (four skipped) and 13 PostgreSQL cases; Game Session's full 2,136 unit cases passed, and the corrected focused run passed four affected unit cases and 45 PostgreSQL cases without failures, errors, or skips. The checked-in test anchors are [Account authority bundle](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java), [Account original-attempt storage](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java), [Logging reservation persistence](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java), [shared post-authorization tuple](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java), [shared mTLS client](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java), [Game Session operator-attempt storage](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java), and [Game Session launch preparation](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java). Affected formatting, Checkstyle, SpotBugs and gRPC/proto contract checks passed. Documentation validation passed. The receiving correction is published in #3183, with all 30 tested postimages preserved at its original correction commit `ccf0528c352d6e57f790d6c3a0e007c23ddfeaa7`; later ancestry carries retain that proof boundary. Current-head CI and initial complete review remain pending. The source-CI nullable fixture-row warning was corrected without weakening the historical-byte/current-rejection assertions; integration SpotBugs, Checkstyle and all nine focused physical association-read cases passed. Composed runtime execution, activation and genuine external authority transport are not established by these bounded fixtures. + +The passive Account source-fence seam leaves Draft source mutation and abort pending while a matching World participation is unsettled, and blocks hosted-terms disclosure preparation and new dispatch authorization for that source until settlement. The immutable `HostedTermsDisclosureHandoff` value and repository use the existing V98 journal; their opaque evidence bytes are not authenticated by the passive value. No verifier, dispatcher, or transport is registered. The six physical PostgreSQL disclosure-handoff storage cases are specifically attributed to published commit `0a84bfa2800c6f33f3d85023c786a9fdd80ff0ba` and [exact-head validation run 38276405663](https://github.com/benhook1013/FireMUD/actions/runs/38276405663); they also ran within the failed local full check at `c7a61401f2220f70d567b7709397b967daf5e991`. The separate local carry at `932f2e1334a9ffa31fdf3be177a0fdbcd588a0e5` covered five targeted physical integration cases and does not include those six handoff cases. These results prove bounded storage and transaction behavior only. No focused executable proof establishes a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. Hosted-terms authority remains defined by [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). + +### Initial private gameplay LOGIN issuance source intake + +The approved 74-path source parcel is now present as candidate `2be06e2d7ec8e6ece7c856d606941039020dcbce`, carried on parent `d94e1d6de69bbf867aee02ff6f8764a23a66bd3e`; the donor remains `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. Donor preparation proof paragraphs below remain tied to their stated historical baselines and invocations. The complete current-parent locked Account/Game Session gate passed in 26m23s: Account ran 1,368 fresh unit cases with zero failures/errors and four existing filesystem skips, plus 272 fresh physical integration cases with zero failures, errors, or skips; Game Session ran 2,373 fresh unit, 305 fresh native integration, and 39 fresh cross-service cases, all with zero failures, errors, or skips. Both jOOQ checks, static analysis, formatting, and documentation checks passed. The prior failed PostgreSQL connection-refusal result remains retained with unknown cause; this successful full gate does not erase that history. That full gate tested source `2be06e2` on parent `d94e1d6`. Subsequent candidate `f63a83184a995bd8dd2ecbb1343095b9442c0a5c` carries parent `e0a49fcc3767ea14956ff07a815345c4173ff18f`, retains all 74 owned paths and every non-documentation owned postimage, and passes the affected current-parent gate in 1m30s: 24 fresh Account admission/activation PostgreSQL cases, zero failures, errors or skips, plus Account jOOQ, formatting and documentation checks. The initial affected invocation ran no tests because its package filter was wrong and is retained as a failed gate. This is selected affected proof after carry, not a replacement unfiltered full Account/Game Session run. Published-source CI and review remain pending. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation, or playable LOGIN. + +At local source `0a685173e0982ba3c0006acb3e378d228daeadbb`, normally reconciled to published parent `7b2ce6340309198ed4fabd0e58629102ba717706`, the focused gate passed in 2m36s: 150 fresh unit cases and 35 physical Redis-context/PostgreSQL-journal cases, all with zero failures, errors or skips, plus Game Session Checkstyle, SpotBugs, formatting and documentation checks. The subsequent two composed-owner test additions on that local baseline passed all 28 physical Redis-context/PostgreSQL cases in the 57-second affected gate, with zero failures, errors or skips and affected static/format checks. The initial test-package compilation failures remain failed history; production constructor visibility was preserved. The unregistered [InitialGameplayLoginOwner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java) reserves and independently reads back distinct server UUIDv4 request/context coordinates at fence 1 before create-only `PENDING`, then calls the [canonical Account client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java) with its bounded same-deadline retry guarded by current original credential custody. It records and reads back the verified nonsecret witness before exact-result installation and transfers the still-live private result to its caller; uncertain results and actual original pre-admission custody loss retain exact-original cleanup. This original-attempt lifecycle remains separate from already-admitted retained-edge rebind. The [owner proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java), [Redis integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java), and [journal integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java) exercise controlled composition and physical storage fixtures only. The composed physical cases check independently committed original coordinates before the first Redis mutation, actual PENDING creation and non-admitting installation, and same-invocation credential closure after a controlled Account response followed by exact-original Redis closure, frozen witness-bearing retirement, a PENDING disposal receipt and owned-result erasure. Account signing/disposal responses and external Redis qualification remain controlled inputs. The later 28-case evidence belongs to the local changed test postimage, not an authenticated production receiving chain. Caller registration, trusted Gateway/Proxy identity and protected custody, production Redis qualification, real Account mTLS/signing, qualified retained binding-history recovery, runtime activation, gameplay admission, and LOGIN wire success remain unproved; `AA-2.1` remains partial. See the canonical [session and identity model](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes), [plain-text LOGIN mapping](../../architecture/system-architecture-authentication.md#plain-text-login-logon-command-mapping), [original-attempt coordination](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination), [bounded non-edge recovery](../../architecture/system-architecture-reconnection.md#bounded-non-edge-restart-recovery), [initial-context aggregate](../../architecture/system-architecture-redis.md#initial-login-context-aggregate), and [Redis operation](../../architecture/system-architecture-redis-ops-access.md) owners. + +The donor inactive preparation adds the Game Session-owned single-key context codec, registered Lua/descriptor, protected binding policy, compare-only installation and acknowledged original-only closure adapter. The external recovery/maintenance qualification remains an interface with no production provider, and PENDING records are supplied only by controlled fixture setup. Four focused unit suites pass 27 cases and the native Redis primary/replica plus PostgreSQL journal composition suite passes 24 cases, with zero failures, errors or skips. The 24 controlled cases cover exact installation/readback and matching replay, malformed/missing/replaced/newer/closed/expiry denial, live ACL and qualification refusal, a real sufficient WAITAOF response dropped by a bounded loopback relay, separately insufficient replica acknowledgement, interrupted readback, delayed installation after closure and actual PostgreSQL journal/cleanup continuation. Initial consolidated static gates failed on broad exception catches and an ambiguous test cleanup varargs call; narrow corrections preserve the mutation guards. Selected main/test/integration Checkstyle, SpotBugs, formatting and documentation checks pass across qualified invocations; configuration-cache serialization warnings remain. The final cleanup call uses the existing typed-key-array pattern; its fresh 24-case native rerun and documentation checks pass in 51 seconds after the integration static and formatting checks pass in 33 seconds. This is not trusted ingress, context creation, current denied-marker authority or playable LOGIN. Actual GS HTTP/WebSocket intake has no authenticated Gateway/proxy provenance capability and defaults to the unqualified raw-header path; genuine receiving-chain custody and the canonical server UUID producer remain open. The [Redis owner](../../architecture/system-architecture-redis.md#initial-login-context-aggregate) defines key/payload policy, with acknowledgement and reset requirements at their linked owners. `AA-2.1` stays partial. Coherent source publication is approved; current-parent candidate proof passed as recorded above, while ordinary parent carry, published-source CI and review remain pending. Full receiving-chain qualification and activation holds remain. + +The donor journal preparation adds the unregistered Game Session original-LOGIN PostgreSQL journal and cleanup owner selected by the [token coordination contract](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). Forward V1012 retains original request/context/fence, irreversible abandonment, separately appended validated token witness, immutable frozen retirement bytes and original disposal receipt. The owner commits and independently reads back reservation, abandonment and request freezing; cleanup crosses a typed exact-original acknowledged-closure boundary before the existing Account retirement client, outside the SQL transaction. Private credential/token custody is not reconstructed from retained evidence. Focused proof passes 42 unit cases and nine native PostgreSQL cases with zero failures, errors or skips across qualified invocations. The PostgreSQL suite exercises committed identity/readback, rollback and owner replacement, exact conflicting reuse, frozen witness absence/presence, late-result serialization on a real row lock, immutable receipt replay and physical retention guards, transaction/durability refusal and bounded retained inventory. The first physical run passed six cases before PostgreSQL administrator-command shutdown interrupted a later migration and two subsequent fixtures; its failed gate remains retained and the initiator is unproved. Fresh isolated proof passes all nine cases without weakening guards. Selected Checkstyle, SpotBugs and formatting, owning jOOQ generation, pinned-parent Flyway validation, architecture contracts and documentation checks pass; configuration-cache serialization warnings remain. Unit closure/Account doubles and locally signed result fixtures do not supply physical Redis closure, current denied-marker protection, genuine authenticated custody or terminal Account nonissuance provenance. This is local source work, not a published or activated capability. The separate donor CAS preparation above qualifies physical registered Redis closure/CAS in controlled fixtures; trusted TCP custody, canonical caller-context production and composed LOGIN remain open, and `AA-2.1` remains partial. + +The donor original-LOGIN disposal preparation adds a separate proto method and unregistered Account receiver/owner, closed optional token witness, Account-derived disposal digest, forward V1005 durable guard/state/immutable owner-proof storage and exact-hash denied Redis tombstone script with pinned `WAITAOF` and physical readback. Original-request checks fence issuance, commit, activation, response recovery and exact-token use. The closed response pairs `RETIRED` with `PHYSICAL_TOKEN_DENIAL` and `NO_TOKEN` with `NO_ISSUANCE_BINDING`; `PENDING` has no terminal proof. Known-hash disposal covers bound pending, SQL committed/Redis pending and active inputs without requiring current expiry/keys. The settled no-key contract is defined at the [token owner](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal): it is conditional owner nonissuance proof, not physical Redis absence and not a claim that transient signing never occurred. Current source independently reads back the durable-primary no-key guard and complete binding shape without Redis, but lacks a protected retained binding-history/restore qualification producer, so it does not produce terminal nonissuance proof and retains no-row/unbound `PENDING`. Retention and cleanup remain held without an invented TTL. + +Current disposal source was validated as local owned postimages on baseline `198cfec5bec3f4c76f1c8bffc582c426a6318ac2`, rather than as a published candidate. The earlier negative-cutoff fixture and missing historical migration fixtures were corrected without relaxing production guards. Account unit proof passed 1,368 cases with four skips. A selected physical integration run passed 265 of 272 cases; seven Hosted Terms cases refused their PostgreSQL endpoint before migration and subsequently passed in an isolated seven-case rerun. This is qualified proof across separate invocations, not a passing unfiltered full Account gate. Within that selected physical scope, all 15 issuance persistence, one response recovery, three historical evidence and 17 native Redis cases passed, covering pending/committed/active disposal, interrupted stages, lost commit acknowledgement, immutable original-request serialization, late registration/activation denial and denial-marker reassertion after loss. Historical schema upgrade assertions preserve original bytes and `xmin`. These are bounded fixtures under their stated custody and trust assumptions. + +After the narrow static-analysis corrections, 30 focused Account receiver cases and 71 Game Session client/result cases passed; unchanged result behavior additionally passed its 47-case focused rerun. Account and Game Session SpotBugs, formatting and documentation checks passed. No-key cases establish durable guard/current-shape readback and fail-closed `PENDING`, without fabricating Redis lookup or a live history-continuity producer. Positive terminal `NO_ISSUANCE_BINDING`, real restore qualification, genuine authenticated transport loss, composed runtime Game Session caller/context-CAS integration, protected caller custody, retention horizons and runtime activation remain incomplete. + +This preparation is owned by `AA-2.1` in [Capability Status](#capability-status). + +Account now contains an unregistered initial private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157.1 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation are outside this cut. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. At original source head `8df6c870801f96a902742da0223f42cd1cfe527f`, consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Its Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. At reconciled head `996959aa2477890ec901154e2c2376538da9012a`, consolidated Account formatting/fullCheck, static analysis, integration-source compilation and documentation checks passed in 1m 59s (93 tasks). Its XML reports 1,187 unit cases with four skips and 191 integration cases with 188 skips, with zero failures/errors; the skipped PostgreSQL/Redis cases remain unproved physically. Those historical local runs did not establish physical PostgreSQL/Redis proof. The later published source at `f9922f2b6c59b836c730bcb47100719c3498dbe0` passed fresh exact-head Account CI with 1,194 unit cases (four skips) and 207 PostgreSQL/Redis integration cases with zero failures, errors or skips (Validation `38247785958`, Account job `114806613509`, artifact `11747377390`); that exact-head proof includes the required V157.1 guard and physical TRUNCATE rejection coverage. This is bounded fixture proof; it does not establish caller authorization, deployed ACL/TLS or authority custody, gameplay admission, runtime activation, or end-to-end consumers. The later retained tenant/member replay proof is recorded in the later replay-proof paragraph below. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). + +At exact source head `50c22969698303ffdc6f3aab42d19dc499e47c5d`, the consolidated local full gate passed in 10m57s: 1,202 Account unit cases with four skips and 208 physical PostgreSQL/Redis integration cases with zero failures, errors, or skips, including the new 129 captured-head-loss/gap proof. This gate provides retained-source replay and fixture evidence for that exact head. It predates the subsequent projection republish/compare and bounded-page transport corrections. Their later local gate executed 1,207 unit cases with four skips and zero failures/errors, plus 208 physical PostgreSQL/Redis cases with zero skips; 206 passed, including all five delegation Redis cases for real commit-time publication and the 128+1 retained-page replay. The two `AccountAuthorityCurrentnessIntegrationTest` cases failed acquiring `localhost:53626` before Flyway migration (`SQLState 08001`, connection refused). Captured PostgreSQL logs show final TCP readiness before test startup and normal cleanup after the failures; the host-endpoint refusal cause remains unknown. The full local Account gate therefore failed despite the focused correction proof, and current published-head CI remains separate. At published source `1620a15e4a93461da5107aa940aaf41860f37cfd`, CI executed all 1,207 unit cases (four skips) and 208 physical integration cases with zero failures or errors; the Validation gate failed on a redundant-null-check static-analysis finding instead. The subsequent issuer-TTL and integer-transport corrections passed 1,210 unit cases (four skips), then a focused physical rerun passed all 21 cases across issuance persistence, response recovery and real delegation Redis, alongside Account/Common Security static, formatting and documentation checks (1m40s). That rerun was filtered; it does not claim a newer unfiltered 208-case pass. The earlier full local run of this correction batch passed 200 of 208 physical cases; the eight failures were the two Redis fixture mocks that lacked the exact issuer no-TTL stub, corrected before the focused rerun. Neither this source replay nor its fixture proof establishes deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, runtime activation, or authenticated full-owner physical composition. + +The retained-original-key rotation correction published at source `7dc4d3b7be0368c31b8a9924f34ebcc141f452cf` passed focused local proof on its matching postimages: 1,212 Account unit cases (four skips) and all five PostgreSQL/Redis cases, including retained-key acceptance and withdrawn-key denial without changing stored Redis bytes or expiry. Its [exact-head Validation run 38278570811](https://github.com/benhook1013/FireMUD/actions/runs/38278570811) passed all 208 physical Account integration cases without failures, errors or skips and 1,212 unit cases with four skips; those results belong to the named source, not to later review corrections. + +The unregistered [primary credential verifier](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifier.java) now composes the canonical LOGIN owner with Account’s existing password/email-OTP authority without minting a legacy JWT or session. Canonical verification performs two KDF comparisons using the existing Argon2 profile, padding with private process-local random decoy evidence; the missing-Account path grants no authentication and changes no challenge state. Verification retains an exact OTP challenge identity, and the owner consumes it only after creating its new PENDING issuance in the same writable transaction. Exact pending retries skip credential verification and consumption. + +Focused local proof passes 40 [unit cases](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java) and 13 [physical PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java), with zero failures, errors or skips. Actual Account/challenge/issuance repositories and owner transactions prove denial accounting, expiry deletion, atomic PENDING/challenge consumption, rollback on SQL rejection, unchanged pending retry and changed-binding conflicts. Account birth and challenge issuance are controlled upstream inputs; external commit/recovery owners stop before signing, registry activity or credential release. This proves interruption before release, not post-release response loss. Authenticated transport, real signer custody, representative operational timing parity, runtime activation and protected Gameplay closure remain unproved. + +The later [physical Redis composition suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java) passes seven executed PostgreSQL/Redis cases, including two new PASSWORD/EMAIL_OTP flows, with zero failures, errors or skips; integration Checkstyle and SpotBugs pass. Real primary credentials, canonical LOGIN/commit/recovery owners, signing cryptography and encrypted-response storage compose through committed PENDING, COMMITTED SQL proof and active Redis registration. Discarding the produced response and retrying returns the same token bytes, original operation/JTI, expiry and registry deadline without re-verification or repeated OTP consumption; changed request/caller bindings preserve the original state. Account birth, challenge issuance, keys and caller context remain controlled inputs; protected signer/materializer/JWKS trust is mocked. Redis uses the existing pinned loopback primary/replica ACL/AOF fixture without TLS. This is source-owner composition and simulated discarded delivery, not authenticated network-loss, deployed custody, runtime activation or protected Gameplay proof. + +After ordinary reconciliation to the published World-source parent `b41a1f8c9853e87592e09f0b4194dca8965b2cc0`, source `6c651ed8deec260e1857a421bfbf2f4baf8bbcf3` passed fresh focused Account proof: 221 unit cases (181 existing authentication and 40 primary-verifier cases) and 42 physical PostgreSQL/Redis cases (13 credential, seven delegation composition, 18 admission-protection and four activation-protection cases), with zero failures, errors or skips. The four Account Checkstyle/SpotBugs tasks executed successfully. These results preserve the source and controlled-fixture boundaries above; genuine authenticated LOGIN callers, retained-state disposal policy, deployed custody, runtime activation and protected playable closure remain open. + +The source-fence allocator intentionally locks one singleton row until the Account transaction commits. This preserves the current global source-fence contract and serializes first-time evidence capture across Accounts; signing and binding work in that transaction extend the lock duration. Representative throughput measurement and any canonical allocator redesign remain required before gameplay activation. This preparation does not change allocation semantics or claim a production throughput bound. + +Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). + +### Account signer/currentness storage evidence preparation + +Account V99–V125 and the associated owner repositories, typed evidence carriers, mounted-bundle signer source, and validator-profile sources form a passive storage/evidence preparation only. The selected RPCs, coordinators, transport composition, provisioning, receiver execution, runtime registration, and consumer enforcement are not included or activated. The earlier local result of 727 Account and 154 Common Security cases is historical. The later local Account result is 738 cases with one skip; integration sources compiled, while local integration execution skipped 99 of 101 definitions without Docker. Exact-head hosted Account integration task 114264913703 passed on `607004fe786b2a9e1270a31c90f9031b486b3278` and is historical; its retained evidence does not expose per-suite case or skip counts. The later exact-head result at `7b79a8860baa6f08d3b4ae51d166f64ccf08004f` is also historical: hosted Account task 114304559873, Validation 38083268673, and artifact 11681094163 recorded physical PostgreSQL 18.6 readiness storage proof with 1 case, 70.952 seconds, and 0 skipped, including lawful expired-dispatch recovery. At `e63729562c39e664513bad2be2222e11a6886388`, the required Validation and Smoke checks passed. Hosted Account run 38088195334, task 114319172067, and artifact 11683606431 tested merge commit `05304721b3e705925b4344280a98a65c094f8823`, with parents `75e92718a983ac134cbb75fafbf173ac6b0360e0` and `e63729562c39e664513bad2be2222e11a6886388`, using immutable PostgreSQL 18.6 image `sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336`; the readiness and inventory suites each passed 2 of 2 cases with zero skips or failures. This is bounded storage proof with synthetic inventory/resource inputs, not evidence of live Kubernetes currentness, readiness activation, or signer activation. The AA-1.3 capability remains `partial` / `drift-found`; this subsection updates its passive anchors and proof limits without changing that state or closing a gate. Other capability rows and prior gates remain unchanged. Runtime readiness is not claimed. This preparation does not establish an issuer/currentness path or close `PLAY`, admission, or playable readiness; the canonical design remains [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md), with Account-local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + +This preparation is owned by AA-1.3 in [Capability Status](#capability-status), whose state remains `partial` / `drift-found`. Its production anchors are [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), [V99](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql), and [V125](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql). Focused proof anchors are [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java) and [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java). The older exact-head readiness result on `7b79a8860baa6f08d3b4ae51d166f64ccf08004f` and the earlier signer-suite result are historical; the signer artifact has no per-suite count. The latest published proof is the hosted PostgreSQL 18.6 result detailed above: readiness 2/2 and inventory 2/2, zero skips or failures, with synthetic inventory/resource inputs. The subsequent snapshot/matrix closure correction and isolated expiry-recovery regression have passed local compilation and migration parsing, but their three PostgreSQL test definitions skipped without Docker; replacement exact-head physical execution remains pending. No runtime registration, live Kubernetes currentness, readiness activation, or signer activation is established. + +The added `AccountDraftSourceCompositionService`, `AccountControlUiAuthority`, and `AccountControlUiSigningSpec` remain unregistered and transaction-bound source preparation. They do not issue a JWT, authorize receiver execution, or establish runtime currentness/readiness. + +### Account operation and signer source preparation + +[V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql) adds one immutable cleanup deadline to newly prepared Control-UI owner rows, separate from the JWT `exp` horizon and bound to the same registry bytes and Redis readback receipt. The retained-row migration case in [AccountControlUiIssuancePostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java) confirms that a pre-deadline row keeps its original fields, retains a null deadline, and is denied current use and advancement after migration. Direct PostgreSQL proof that a newly recorded deadline cannot be changed is still missing. The preparation remains source-only under AA-1.3; bounded cleanup and late revocation remain incomplete, and token issuance is not activated. + +The direct expiry-erasure correction adds [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql) and an owner-only repository primitive, preserving compact authorization and redemption evidence. [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java) defines fresh-install, retained-V126, early-erasure, resurrection and exact-retry proof. The correction passed 35 focused unit cases without failures, errors or skips, jOOQ generation, integration-source compilation, Checkstyle and Spotless. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Account authorization-repository PostgreSQL suite passed 15/15 with zero skips, failures or errors, covering those migration and erasure cases; see the current AA-1.3 proof record in [Capability Status](#capability-status). This is bounded storage proof; automatic cleanup and runtime activation are not claimed. Its local storage consequence is owned by [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + +The current Account cut adds V126 operator-authorization storage, default-inactive StartSession authorization sources, Control-UI issuance and Redis coordination, Account-owned JWKS and signer-materialization adapters, and readiness-probe sources. This preparation is tracked under AA-1.3, whose state remains `partial` / `drift-found`. StartSession composition is disabled by default. Materializer trust is disabled by default, and absent trust denies every materializer RPC. Missing bootstrap-coordinator composition denies enrollment and promotion operations; trusted generation requests, observations, and result reads remain available. No runtime issuer, signer-promotion coordinator, or consumer coordinator is registered. Production anchors include [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java), [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java), and [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql). Focused test anchors include [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java), [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java), [AccountControlUiOwnerWorkflowPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java), [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java), and [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql). At pinned head `22a6c39e3f1754acebf95477d6968c69edde66fd`, Validation run `38096949593` and Account artifact `11686863341` record the nine changed PostgreSQL/Redis integration suites executing 35 cases with zero failures, errors, or skips, plus 23 RestoredInventory unit cases. That proof remains historical and applies only to its recorded head and fixtures. Later hosted Validation run `38113324723` succeeded at head `f6d34031221a3337e7a958ac4b085554460668c9`; Account job `114394304424` and artifact `11693535744` record four owner-workflow PostgreSQL tests physically executed, including signer quarantine. This is bounded physical fixture proof, not deployment or runtime activation. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, Validation run `38117703529`, Account job `114405941820`, and artifact `11693819544` tested merge commit `9ca30839c8a46446f01d0a441e6e830fab8bca86` with ordered parents `4ab98ba1f0a2464349ed21ce59e7ef44ecd79e8c` and `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`; the Control-UI issuance PostgreSQL suite passed 5/5 and the StartSession authorization repository PostgreSQL suite passed 15/15 with zero skips, failures, or errors. This is bounded exact-head fixture proof, not deployment or runtime activation, and aggregate validation remains red on the unrelated Gateway fixture. The Account-owned [reservation-evidence client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java) uses the existing Logging & Admin proto contract; completing the flow also depends on the out-of-cut Logging & Admin authorization coordinator/client and Game Session redemption composition. mTLS execution, the complete Logging & Admin/Game Session/World flow, player-facing JWT readiness, and activation remain unproved. V126/V126.1/V126.2 remain passive storage/source preparation; bounded cleanup and late revocation remain incomplete. Canonical JWT and signer behavior remains in [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md), with Account-local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + +### Account fresh original-ACK storage preparation + +This preparation is owned by AA-1.3 in [Capability Status](#capability-status), whose state remains `partial` / `drift-found`; it adds passive original-ACK storage preparation only and does not change the capability state or close an activation gate. + +The receiving Account cut imports the preserved original-ACK storage preparation from `codex/gameplay-game-design-publication-storage-foundation-20261009` at `d66d36951d3df780641e0ef04819f15df52ddc39` plus its uncommitted PostgreSQL 18 fresh-path changes. Only the receiving migration filenames are allocated anew: V140 ← source V118 (lease operations), V141 ← V119 (unknown-decision abort), V142 ← V120 (original-finalization stamp and experimental confirmation storage), V143 ← V121 (global pending fences), V144 ← V122 (original-ACK receipt), V145 ← V136 (experimental confirmation write retirement), and V146 ← V139 (PostgreSQL 18 fresh-insert guard). Their SQL bytes, including historical version comments, are preserved. Source V122 retains SHA-256 `c4f66ce16c77514717cbc9d2e0d65bc8c8ee0882239371d8518f587a0ef53490`, matching the historical `2cb445617f584d25c805f5c08e9dde67fff4efc4` migration; no donor renumbering or external migration application is performed. + +The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs are explicitly PostgreSQL 18-only; retained COMMITTED retries cannot mint another acknowledgement, and the unchanged historical durable reader still denies PostgreSQL 18 recovery or retained-receipt retries. The `AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest` PostgreSQL prototype contains 18 `@Test` cases and uses the receiving canonical `AccountPostgresIntegrationFixture(true)` without importing another fixture or build dependencies. The copied unit proof sources are separate mocked-JDBC cases. Full-check selected the PostgreSQL cases, but they skipped because local Docker was unavailable; physical PostgreSQL proof remains pending the consolidated gate. No donor or earlier receiving result proves this new intake. Authentication, current ownership/admission, runtime registration, activation and playable capability status remain unchanged. Account-local storage consequences remain in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + +### Restricted original-claim evidence continuation preparation + +This inactive owner continuation may read or replay the exact immutable association pin and create at most one immutable descriptor evidence pin under that same association and original `PENDING` claim, attempt, and fence. Authenticated Account and Game Design reads occur outside SQL; owner and association state is locked and rechecked before descriptor pinning. Initial association creation also requires the exact original Account authorization reference to remain unexpired at the PostgreSQL write, independently of the owner-claim lease. Existing association replay and historical reads retain their reconciliation semantics; this preparation does not renew or reissue authorization or create a replacement claim. Its classes remain unregistered; added proto/schema support does not activate a runtime route or grant mutation authorization or player admission. Descriptor evidence does not complete canonical launch, initial World-backed admission, or historical owner reconciliation. The canonical boundary is [Game Session restricted original-claim evidence continuation](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md). + +Previously recorded focused local unit and transport evidence includes the [authorization coordinator test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java), [continuation service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java), [redemption client test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java), and [mTLS redemption client test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java). The implementation anchors are [authorization coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java), [owner attempt repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java), [template association repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java), and [descriptor continuation service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java), with schema support in [V35](../../../services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql), [V37](../../../services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql), and [V38](../../../services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql). + +#### Consolidated exact-head and historical proof + +Historical earlier-head [Validation run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected PostgreSQL cases with zero skips; that result applies only to its selected fixtures and source head. Historical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases: 20 shared-fixture timestamp violations and one source-bound tenant guard rejection. Later exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 passed with zero skips, failures, or errors. Its JUnit artifacts include the owner-attempt (12), template-association (10), launch-descriptor (12), original-association read (8), authorization-coordinator (3), and V34.3 request-ID migration (1) suites, plus the historical owner producer and workload-guard unit suites (6 and 4). This is aggregate physical proof for the recorded source head and listed fixtures; the artifact does not map the earlier job's failures one by one, and it does not prove current code at a later source head, runtime registration, World-backed admission, namespace-aware atomic takeover, issuer-index or region reconciliation, retained-binding inventory/conversion, final Account admission, live playable closure, or the complete migration-driver PostgreSQL/Redis path. The V34.3 fixture result does not establish that complete driver path. + +The restricted original-claim continuation remains inactive and default-denied: its owner repositories, typed Account read/pin clients, and descriptor evidence producer remain unregistered, do not alter the composed production implementation, and authorize neither mutation nor player admission. The exact-head run recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof) physically executed the listed owner/history integration suites; it does not prove runtime registration, World-backed admission, historical-owner reconciliation, or playable closure. The earlier local check that compiled integration sources without running PostgreSQL is historical local-environment evidence, superseded for the listed fixture suites by that hosted result. + +The inactive hold client reads the exact immutable identity, actual hold status, and full lifecycle snapshot over workload mTLS. The original STARTING association read carries the stored post-authorization tuple and actual owner attempt/fence, but requires an unexpired pending claim; it is not an after-expiry association endpoint. Historical failure provenance and the later artifact's limitation in matching those failures are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). Hold snapshots and retained tuples do not supply continuous commit authority. The authenticated historical original-owner evidence producer remains unregistered and undeployed; live hold validation, continuous protection through pointer/audit commit, and cross-owner terminal reconciliation remain incomplete. + +Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Earlier Docker-disabled local snapshots compiled the PostgreSQL fixtures but did not execute them locally; the listed physical fixture execution is recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). + +The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event, and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator, and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier local checks that reused cached task outputs and lacked Docker are historical local-only results; they do not supersede the limited exact-head evidence recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof) or establish activation. World Management's published change `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup, and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. + +The newer inactive consumer adds exact mTLS World acquisition/identity and lifecycle read clients, the V28-backed durable pre-hold intent repository, and a coordinator that commits immutable intent before contacting World and attaches only the exact returned hold identity in a separate owner transaction. Remote failure preserves pending intent for the same request; attached or terminal replay returns historical evidence only. Owner repositories also expose non-mutating historical reads of the complete original StartSession tuple, actual attempt/fence, attached Account projection, and immutable first template pin after expiry, separately from the still-unexpired live continuation. The listed PostgreSQL suite results are in the [consolidated proof record](#consolidated-exact-head-and-historical-proof); they do not prove the consumer is registered, that a genuine World verifier participates at runtime, or that hold authority remains continuous through pointer/audit commit. Cross-owner terminal reconciliation, concurrent termination/restart proof, and playable closure remain open. + +The exact-head artifact and the historical owner/history suite results are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof), including the limitation that the aggregate artifact does not map the earlier job's failures one by one. The `AA-2.1` capability remains partial because namespace-aware atomic takeover, final Account admission, runtime activation, and live playable proof are still open. + +The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + +Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` results remain historical evidence only. Physical Account job `114042562197` on `c69fa3645f3ddf16d2eaafd3838a29a52141736f` executed 98 integration cases with zero skips and one canonical-order Game Logic fixture failure; its correction passed Account job `114050124577` on `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`. The subsequent `f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7` Account job `114059401680` in run `38001172632`, artifact `11648894382`, executed 101 PostgreSQL integration cases with zero skips and one trigger-catalog fixture failure. The new inspection-lock, immutable TRUNCATE and exact disclosure-source regressions passed. PostgreSQL truncates identifiers to its `name` type's capacity; the catalog assertion now compares through `?::name` while retaining enabled statement-level TRUNCATE checks and actual rejection tests. The final `14eaa6c9568928f0079830159ac66f37ead2c146` Account job `114067421524` in run `38003644164` passed its physical integration task with Docker active, including the corrected settlement/source-vector fixture classes in its aggregate JaCoCo execution inventory. Successful case-level JUnit totals were not retained, so no new exact per-case counts are claimed. All five required exact-head gates and subsequent metadata-preservation gates passed. This bounded evidence does not establish runtime activation or playable closure. + +Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections. + +Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. + +Account's persisted UUID now backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. Authentication results and JWTs, profile and tenant DTO identity fields, Game Session carriers, `PLAY`, and Entity Management remain outside this output slice. Numeric Account-claim consumers remain outside this slice in common-security `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, Social & Groups current-account authorization, and Game Session's numeric control-plane owner authorization. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no UUID-authentication or downstream runtime-proof upgrade. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). + +Internal Account-carrier typing is prepared in Game Session, while current producers, JWT claims/parsers, and numeric-only collaborators remain unchanged. This does not activate canonical Account UUID authentication or Entity roster/entry behavior and does not backfill historical command UUIDs; canonical identity/namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused unit proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. #2898 is not fixed by this preparation. + +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. + +Official-hosted creator-content acceptance remains an unregistered target workflow. Source-only persistence now includes Creator Party and hosted-terms/environment-binding evidence plus V98 disclosure handoff and source-evidence tables; these relations do not supply external environment observation, authenticated publication, a legal authority verifier, dispatch, a consumer, registry/runtime binding, creator UI, or downstream write-gate proof. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Its target authority remains under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md), outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. + +Account runtime admission reads remain a security/proof blocker: both `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are currently configured as public gRPC methods, and handlers accept caller-selected identifiers without exact Game Session/World Management workload or tenant binding. The target internal-workload boundary and required negative proof are canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). + +PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. + +Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` path provides read-only baseline evidence only. Namespace-aware shared-versus-isolated playable-state persistence exists for current state families, but the Account-owned restricted-synthetic identity/isolation verifier and corresponding persistent/shared mutation proof remain unavailable; independent two-transport mutation parity remains unimplemented and unproved. Run-owned Compose mutation and teardown remain implemented and proved at their bounded scope. See the [canonical testing owner](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). + +SEC-04 does not move player session ownership into Logging & Admin. Game Session `/sessions*` lifecycle routes remain current owner-local hooks with direct owner edge exposure denied; the target external operator path forwards from Logging & Admin to Game Session after Account issues the authorization reference and the receiving Game Session redeems that same reference. That target lifecycle family, and other operator mutation families gated by action schemas, shared `mutationDigest/v1` vectors, and the authorization-reference flow, are not currently available to players or operators. + +## Retained Account Source Prerequisite + +V40 deliberately does not enroll retained pre-V40 Accounts into fresh authority-source baselines. Fresh repository-created Accounts use owner-proven source baselines, and security-relevant updates require that source. Password-reset completion now atomically claims and consumes its token with the Account update, canonical event/receipt, and current-source readback. If source evidence is missing or an earlier source intent remains `WAITING`, the owner transaction rolls back and returns retryable `AUTH_UNAVAILABLE`; the handler does not wait for source settlement on a thread. An exact retry preserves the original intent and may proceed after its owner-fence outcome is known. The `WAITING` intent retains the Argon2 password verifier required for that retry; terminal source commit or abort clears the verifier while retaining its digest and immutable source binding and receipt. No finite receipt lifetime is selected; receipt retention remains an owning-policy gap. Retained pre-V40 rows remain denied and are neither backfilled nor admitted; unrelated transaction or database failures are not converted by this handler. + +For AA-1.3 source-currentness, [AccountAuthoritySourceEventReadback](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java) and the source-fenced reset path in [AccountServiceImpl](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) are production anchors; [AccountAuthoritySourceEventReadbackTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java), [AccountServiceImplTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java), [PasswordResetAuthorityProducerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java), and [AccountAuthoritySourceEvidencePersistenceIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) are focused proof anchors. The Account authority-event reader still rejects generic source events that lack a supported exact closed-operation receipt as `AUTH_UNAVAILABLE`, so this does not claim complete LOGIN/currentness closure. Physical PostgreSQL results and the pending corrected-fixture CI validation are summarized in the [current proof qualification](#current-status). Reset-driven revocation and the broader recovery/session/logout family remain incomplete. + +Deployment must not advertise retained credential/security-write workflows as ready merely because V40 installs successfully. A separately authorized, provenance-complete retained-source enrollment mechanism and its migration/rollback proof remain prerequisites for retained Accounts; no enrollment or backfill is implemented. Password-reset token consumption is now implemented atomically for Accounts with valid current source evidence; reset-driven revocation and other recovery workflows remain incomplete. Physical PostgreSQL status and pending current-head validation are summarized in the [current proof qualification](#current-status). This consequence does not activate public JOIN, LOGIN/PLAY, recovery-token release, or change capability status; see [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md). + +## Packet 4 Status and Proof Gaps + +- `AA-2.1` / `AA-2.2` / `AA-3.3`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) remains the canonical target link for stable namespace-aware selection, admission, reconnect, and runtime replacement; [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) owns namespace-scoped controller identity, uniqueness, takeover, and binding-generation fencing. Existing account/session and realm-routing evidence remains partial and does not prove namespace-aware atomic takeover, replacement, or cleanup behavior. +- `AA-3.3`: [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) adds the player-visible lifecycle consequence that only an active, admissible realm is exposed; Temporal coordination does not become admission authority. Existing lifecycle and reconnect caveats remain. +- The finite namespace controller-index migration-driver prefix is source and packaging preparation only. The most recent independent Common Security and Game Session full checks completed without failures or errors; those checks do not prove the newly adjudicated fixes or complete physical PostgreSQL/Redis execution. Distribution packaging, exact source-to-jar migration resource comparison, synthetic missing/changed/duplicate resource rejection, ShellCheck, and documentation checks pass. The [V34.3 intent request-ID PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) passed in the exact-head run summarized in the [consolidated proof record](#consolidated-exact-head-and-historical-proof); that fixture does not establish the complete migration-driver PostgreSQL/Redis path. Complete driver execution, final image build and immutable image authority, trusted bootstrap/execution, and live playable proof remain unrun; Docker-disabled local checks do not establish PostgreSQL fixture behavior. Issuer-index and region reconciliation and final Account admission have no proof in this slice. This status does not establish an empty retained-binding inventory, prove conversion of non-empty retained data, or authorize running the driver. `AA-2.1` and `AA-2.2` remain `partial` / `drift-found`; gameplay completion under #2967/#2898 remains separate. See [Game Session Operations](../../architecture/microservices/game-session-service/operations.md#namespace-controller-index-migration-driver) and the canonical [Legacy controller-index migration gate](../../architecture/system-architecture-session-behavior.md#legacy-controller-index-migration-gate). + +These links add decision provenance only; they do not upgrade player-access or session capability status. + +### Canonical first-party receiving preparation + +The local receiving preparation uses the dedicated Gateway RS256 non-JWT envelope defined by [Authentication and authorization](../../architecture/system-architecture-authentication.md#gateway-to-game-session-connect-context-normative). [GatewayFirstPartyConnectContextEnvelope](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java) verifies the complete closed schema, canonical bytes, signature, receiver binding, bounded expiry, exact copied Account evidence, and decimal-string counters. Twelve focused controlled-key tests pass; this does not qualify an Account producer, Gateway replay consumption, or key delivery. + +[FirstPartyConnectContextService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java) joins that verified context to the current [canonical route owner read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java). Logical UUID authority stays separate from owner-supplied private storage handles. Retention keeps the original compact envelope and resolved owner snapshot, re-verifies expiry and current owner evidence on reads, and rejects old partial selector fragments, corruption, or unavailable authority. Main's latest focused evidence reports 12 controlled-key envelope tests, 199 Game Session unit cases after two narrow fixes, 184 Account unit cases after the fixture mock-history correction, 15 Gateway unit cases, and six physical Redis cases. The local socket-ownership correction requests transport close after send failure and performs disconnect cleanup only when the close callback atomically removes the exact registered transport. Forty-seven focused ownership unit cases and affected static/format gates pass. A fresh PostgreSQL-backed WebSocket class run passes 19 of 20 cases after default-off route-reader wiring is repaired; its remaining fixture-room assertion is corrected and that case passes in a separate focused run. The original startup and assertion failures and earlier all-skipped result remain retained; no genuine first-party admission authority is claimed. See [Session Behavior](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes). These partial results do not establish a complete consumer gate or packaged runtime. + +Account connect-token issuance retains its existing bootstrap and scope authentication checks, then denies before cached-success replay, token minting, or session mutation while the canonical producer is unavailable. Gateway removes the legacy HMAC context mint and replay fallback; first-party cookie admission and public gameplay readiness remain unavailable. The separate trusted TCP Proxy listener path retains its existing boundary. First-party bare `LOGIN` and `PLAY` preserve the complete context and deny before legacy Account, Entity, or binding effects pending the genuine authority, lease, and finalization consumers. This entire source batch is local preparation; the `AA-2.1` capability remains partial and no new publication boundary or playable completion is claimed. + +## Capability Status + +| Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | +| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | +| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [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. | +| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | +| `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | + +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. + +Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. + +## Canonical Design Sources + +- [Authentication and authorization](../../architecture/system-architecture-authentication.md) defines global account identity, tenant membership and authorization, access grants, credentials, and gameplay admission. +- [Reconnection](../../architecture/system-architecture-reconnection.md) defines reconnect eligibility, bounded semantic recent context, fresh redraw, takeover, and the bounded continuity envelope. +- [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) defines the login, play, session, and control-plane protocol boundaries. +- [Redis architecture](../../architecture/system-architecture-redis.md) defines session keys and gameplay binding persistence. +- [Account Service](../../architecture/microservices/account-service/README.md) owns account identity, credential policy, membership, and non-public realm grants. +- [Game Session Service](../../architecture/microservices/game-session-service/README.md) owns text-command lifecycle, session context, gameplay binding, and reconnect redraw orchestration. +- [TCP Proxy protocols](../../architecture/microservices/tcp-proxy-service/protocols.md) and [Spring Cloud Gateway client behavior](../../architecture/microservices/spring-cloud-gateway/client-behavior.md) define transport handoff and client-visible retry behavior. +- [TCP Proxy Service](../../architecture/microservices/tcp-proxy-service/README.md) and [Spring Cloud Gateway](../../architecture/microservices/spring-cloud-gateway/README.md) own trusted transport ingress and the stable edge bridge. + +## Consolidated Implementation Record + +### Account, Tenant, and Realm Authority + +Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. + +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; ordinary credential `PLAY` evaluates the same authorities independently. The current `/auth/connect-token` validates bootstrap and connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/runtime reads, token minting, or replay/session mutation. The earlier cache-hit and fresh-issuance behavior is historical and does not establish current gameplay authority. A canonical producer must still validate the applicable non-public grant and current Account/runtime authority before it can issue context. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). + +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Current `/auth/connect-token` fails closed before replay or issuance and does not create membership. The canonical `JoinPublicProductionMembership` Account writer and `POST /auth/bootstrap/join` controller/operation are implemented locally, including a policy-bound v1 digest and membership/audit outbox transaction; the current Gateway guard still blocks external exposure. Game Session text `JOIN` dispatch remains with #2898, so first-party text `Join & Play` is unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam remains open under #2848, as does direct text-client proof, so ADR 0025 is not complete. The membership-authority-generation reread remains a requirement for any future connect-token producer under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). + +Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. + +The Account-authorized request flow forwarded to Game Session remains target-state, not live or proved; affected operator paths remain gated. Current Game Session `/sessions*` lifecycle routes are owner-local/internal, with direct owner edge exposure denied. The canonical authorization-reference and durable owner-execution contracts are owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md), [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md). + +Live Account authentication hashes and verifies passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with character-array handling and post-use wiping. Profile, external-account persistence/service scaffolds, recovery and verification, notification, payment, subscription, and virtual-currency surfaces have live foundations; the unsupported caller-asserted external-link REST route is removed and denied at the public edge. The broader account lifecycle state machine, server-verified provider linking, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial or unavailable as tracked below. + +### Text Protocol and Credential Policy + +Telnet and generic WebSocket clients share one Game Session line-oriented parser/interpreter and gameplay queue. The parser trims input, accepts case-insensitive command names, handles empty or malformed lines, and maps unknown commands to `UNKNOWN`; Telnet performs no separate gameplay parsing. The current canonical flow is optional `WORLDS`, `LOGIN`, `PLAY`, and gameplay commands such as `LOOK` and `SAY`, with built-in `LOGOUT`. `LOGON` remains an accepted login spelling where the protocol documents it. The old typed `SESSION` attach flow is not part of the canonical initial-development protocol; future smart-client metadata, if revived, is transport metadata rather than a player command and is never authoritative. + +TCP Proxy bootstrap metadata is proxy-owned hidden transport context, not a player-visible attach command. `TelnetSessionContext` and `TelnetServerHandler` validate the envelope before forwarding it, record connect events with session/tenant/client identity, reconnect with bounded backoff, preserve ordered buffered input, and close once `MAX_BUFFER_DEPTH` is exhausted while metering discarded input. Telnet logging redacts `LOGIN` arguments. `NotifyDisconnect` validates proxy/session identity, maps a proxy connection to the authenticated session where possible, records suspension for unexpected loss, and returns application-level `ErrorDetail` results while metering duplicate, missing-context, transport-failure, and application-error classes. **Current implementation gap:** Redis sequence dedupe fails open on Redis errors and is reset-loss-vulnerable, and no current connection/generation binding guard precedes presence, region-exit, or `GameInstance` suspension effects. The live path is therefore not yet proof of the target advisory safety contract; the eventual binding design is not specified here. + +`LOGIN` is available in parameterized text form as `LOGIN ` and in challenge-initiation form as `LOGIN `. The supplied secret is one opaque value forwarded to Account Service. Account Service interprets it from the account's enabled modes rather than guessing from its shape: live policy tries a valid active email code before password fallback when both are enabled, and rejects modes that do not permit email OTP. Successful Account authentication is required before Game Session creates authenticated session state or accepts gameplay commands. Failures map to canonical `ErrorDetail` and text `ERROR ` responses, including invalid credentials, locked accounts, upstream unavailability, and unauthenticated gameplay. + +The live account mode set is `PASSWORD` and `EMAIL_OTP`, exposed through global account-settings reads and replacements. New accounts default to `PASSWORD,EMAIL_OTP`; the requested set must be nonempty and supported, and enabling `EMAIL_OTP` requires a verified email. Email challenges are account-specific, short-lived, hashed, single-use, invalidated when replaced, resend-rate-limited, and bounded for failed attempts. Generic login challenge responses remain neutral for account-enumeration resistance. Signup-time mode selection, authenticator-app TOTP enrollment, and any dormant TOTP credential/field are not live. Secrets and OTP values are redacted from transport logs. Prompt/help text describes the optional-secret grammar without making text clients a separate authentication system. + +Account Service publishes `/.well-known/jwks.json` from the configured mounted JWKS file with a classpath fallback. Common Security can hot-reload a configured JWT secret through `ReloadableJwtUtil` and `JwtSecretWatcher` when `FIREMUD_AUTH_JWT_SECRET_PATH` is present; this conditional mechanism is not deployment-wide proof of validator convergence or automated signing-key rotation. + +The maintained integration path uses the real Account/Redis/GameInstance/downstream-service topology. Historical optimistic-success, dependency-light, proxy-only echo, GHCR placeholder, and fake-session shortcuts are not part of normal smoke or integration workflows; any remaining developer stub must be explicit and narrowly scoped. + +### Admission and Gameplay Binding + +Trusted proxy, first-party, bootstrap, and connect-token inputs fail closed before they can establish or preserve routing state. Signed actor identity requires positive, matching `sub` and `accountId` claims. Gameplay routing requires a complete positive bundle of `tenantId`, `gameInstanceId`, `worldSlug`, `realmSlug`, and `pointerVersion`; blank slugs, partial bundles, stale pointers, mismatched world/realm targets, and malformed claims are rejected before routing reuse or persistence. + +Game Session owns the canonical admitted-runtime normalization through `GameplayAdmissionPointerSnapshots`. `LoginCommandHandler` and `SessionRoutingNormalizationService` validate strict runtime identity while remaining scope-agnostic about `playableStateScope`; command-routing-authoritative seams such as `CommandServiceImpl` enforce scope-aware durable routing metadata. Game Logic and Entity Management receive a complete-or-absent admitted routing bundle and fail rather than consuming a partial one. Room identifiers are opaque text routing identities such as `R-*`, not positive numeric IDs. + +First-party selector state used as connect or admission authority is also complete-or-absent. A pre-`PLAY` session shell may retain a normalized `{worldSlug, realmSlug, pointerVersion}` trio only as a non-authoritative lobby selection hint while `playableStateScope=UNSPECIFIED`; that hint cannot establish or preserve a runtime route, authorize `PLAY`, or become downstream gameplay metadata. A missing registry entry combined with any other partial persisted selector fails as `CONNECT_CONTEXT_INVALID` rather than degrading into ordinary realm selection, and malformed or incomplete bootstrap/connect authority is rejected before route preservation. Gateway trust-boundary failures and handshake scope failures remain distinct (`403`/trust rejection versus `CONNECT_SCOPE_MISMATCH`), while invalid first-party signed context is `CONNECT_CONTEXT_INVALID` or `CONNECT_TOKEN_REJECTED` according to the owning seam. + +`PLAY` remains the gameplay-binding step after ordinary credential authentication and, in the target first-party path, after verified first-party identity. Public first-party identity is currently unavailable: Gateway cookie admission fails closed and Game Session bare first-party `LOGIN`/`PLAY` deny before downstream Account, Entity, or binding effects. Generic credential `PLAY` remains separately implemented. Canonical admission semantics and outcome mappings are owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md); implementation and proof status are recorded under `AA-2.1`. + +The canonical gRPC `GameSessionGrpcService.startSession` path preflights IP admission before replacing an existing session. Replacement transfers/reserves the IP slot safely, leaves the existing session alive until the new session and reservation succeed, and on failed admission stops only the tentative session. The shared `GameInstanceService.startSession` default is non-destructive; replacement is explicit. Once replacement is admitted, failure to tear down the old session is warning/cleanup follow-up rather than grounds to revoke the newly accepted session. REST `/sessions` is explicitly noncanonical operator/bootstrap behavior. + +### Session Lifecycle and Logout + +Redis-backed session context carries the authenticated account/tenant identity and gameplay binding, including character and game-instance context. Namespace-aware takeover/transfer remains unimplemented and unproved: current implementation remains keyed by `{tenantId, gameInstanceId, characterId}` and supports explicit replacement at that scope, but current proof does not establish the target namespace/replacement boundary from [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) or the binding-generation transfer, old-source input fencing, and preservation of admitted-work identity owned by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md). An unexpected transport loss can preserve the underlying session and queues for resume. Resume and takeover emit structured identity-bearing logs and bounded metrics such as `gamesession.session.resume`, `gamesession.session.takeover`, `gamesession.session.resume_denied`, and `gamesession.session.fresh_entry_fallback`. + +The lifecycle classes are deliberately distinct: + +- Unexpected disconnect may mark the session suspended/reconnect-eligible, preserve bounded replay state, and allow later `PLAY` to request recovery. +- Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. +- Deliberate `LOGOUT` is termination, not suspension. It deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, clears reconnect eligibility, invokes the canonical World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. It does not delete bounded durable `resume_transcript_entry`/screen-buffer rows. Logout before login is a bounded in-band failure. + +Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay the retained output; unexpected transport loss remains reconnect-eligible. Earlier first-party screen-buffer tests exercised a post-logout replay path, but that behavior is historical: current public first-party `LOGIN`/`PLAY` is denied before admission and cannot establish current reconnect eligibility. Revisit the target rule that deliberate logout is not a recovery replay path when the protected first-party receiver is qualified. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. + +### Reconnect and Continuity + +For generic Telnet and WebSocket, reconnect uses current identity and current Account runtime membership/entitlement authority, not only a prior backend token. Revoked membership, removed realm access, unavailable tenant gameplay, stale runtime target, and failed authority reads fail closed as appropriate. Current implementation resolves the effective disconnected-resume window but does not enforce it in `PLAY`; backend authority unavailability remains retryable temporary-unavailable behavior. A fresh `LOOK` redraw is the current-state authority after successful resume or fresh fallback. Reconnect target behavior and proof requirements remain canonical in [Reconnection](../../architecture/system-architecture-reconnection.md). + +Current durable reconnect rows remain game-instance-keyed, so namespace-key migration is partial. Redis may cache them but is not authoritative gameplay state. The connection-local TCP Proxy input buffer is distinct from durable context and supports only a still-established edge rebind; it is never durable replay of input, transport bytes, frames, or unsent transient output. Current implementation/proof of the bounded reconnect context and prompt behavior remains partial; the canonical continuity contract is [Reconnection](../../architecture/system-architecture-reconnection.md). + +Public first-party `/ws/game/**` is currently unavailable. Account validates bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation; Gateway rejects a presented cookie and reports route readiness unavailable while the canonical producer, shared replay readiness, and dedicated signing keys remain unqualified. Game Session retains complete signed-context and canonical-route/private-handle revalidation sources, but bare first-party `LOGIN` and `PLAY` deny before legacy Account, Entity, or binding effects and do not fall back from partial selectors. Earlier positive first-party handshake, screen-buffer, and reconnect results are historical. Canonical authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md), [Authentication and authorization](../../architecture/system-architecture-authentication.md), and [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). + +Gateway owns the downstream `/ws/game/**` socket and a stable edge transport session id. Its custom bridge can rebind an upstream Game Session socket after bounded loss without immediately dropping the player socket, reusing that edge id. Focused ordinary-transport proofs cover abrupt upstream loss, a Game Session-like process bounce with isolated Reactor resources, and post-restart Game Logic commands (`LOOK`, movement-derived room context, and communication inputs) against shared state. These transport continuity results do not establish first-party authenticated admission. Edge-visible retry taxonomy is reserved for actual edge-route loss or exhausted rebind windows; this does not guarantee in-flight command or byte replay. + +Shared coordination state carries reconnect/connect-context tracking, disconnect deduplication, gameplay-identity screen-buffer access, and bounded takeover information, while the in-process socket remains local. These stores do not produce authenticated first-party ingress. Shipped close-metadata proof covers missing or unattributed metadata on a public WebSocket emitting close `1011`/`internal_error`, and missing or invalid top-level metadata on an established authenticated TCP Proxy bridge rendering `DISCONNECT backend_unavailable ...`; it does not establish a successful first-party handshake, command/byte replay, the broader handler taxonomy, or the complete continuity contract. Remaining gaps are tracked in [TCP Proxy Operations](../../architecture/microservices/tcp-proxy-service/operations.md#implementation-status); duplicate and missing disconnect hints remain separately metered. + +### Fail-Closed Boundary Convergence + +The auth/session/routing guardrail family is complete at its current bounded seams and is now a standing regression boundary, not a claim that every future ingress path has been audited. Shared helpers and direct adopters cover: + +- `JwtClaims`, `SessionClaims`, current-account access, current global-role-based gameplay classification drift, and downstream gRPC bearer creation. The current Common Security seam still uses legacy session attestation and service-identity handling; the target replaces that with certificate-derived mTLS workload identity plus allowlists and typed `PlayerExecutionContext` for player scope; +- bootstrap/connect-scope/runtime membership/grant/entitlement claim readers, account-subject coherence, replay readers/writers, and account REST/gRPC request readers in Account Service; +- `GameplayAdmissionPointerSnapshots`, `ControlPlaneRequestParser`, `SessionIdParsing`, positive-ID readers, gameplay-character parsing, partial-shell classification, IP counter parsing, and command/control-plane routing normalization in Game Session; +- fail-closed first-party Gateway handshake/readiness and the source-prepared signed-context kernel, plus `TrustedTcpProxyIdentity`, `TelnetRoutingBundle`, and hidden bootstrap envelope handling at TCP Proxy; +- the corresponding positive-ID, room-scope, actor-scope, replay-payload, current-account, routing-bundle, and REST error-envelope readers in World Management, Entity Management, Social Groups, Automation, Logging & Admin, Game Design, and Game Logic. + +The current numeric-reader guardrail is: numeric identifiers still used by an implemented seam must be present, well-formed, and positive; opaque room ids remain textual. This is not the durable cross-boundary target. [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) makes durable cross-boundary account, tenant, game-instance, character, and version identities scoped UUIDs, so replacing current numeric forms and proving scope-qualified comparison remains tracked migration work. Malformed or contradictory JWT/signed-token claims reject before identity comparison; partial routing bundles are absent or rejected, never completed by fallback; malformed persisted replay state is ignored/rejected or terminalizes only its affected durable work item; and request validation occurs before replay lookup when malformed shape could otherwise be masked by a stored effect. Malformed persisted Automation tenant identity terminalizes only that work item rather than aborting the batch. Unexpected parser/runtime bugs are not mislabeled as auth failures. + +This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and invalid session JWTs used only for presence classification consistently degrade to the ordinary `PLAYER` presence role. The current classifier still maps a valid global `platformAdmin` claim to in-game `ADMIN`, contrary to the target rule that only explicit tenant-scoped gameplay grants may elevate presence or capabilities. Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. + +Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` denies after bootstrap/scope validation before any replay read, token mint, or replay/session mutation. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. + +Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The [gRPC owner contract](../../architecture/system-architecture-grpc.md#outcome-and-transport-classification) uses typed result unions for successfully produced expected domain outcomes and canonical non-OK status with bounded details when a domain result cannot be produced. Current Game Session/peer handlers still return many response-level `ErrorDetail` payloads, while transport failures cover infrastructure and some pre-domain cases; exact per-RPC migration and proof remain gaps. Shared REST exception handling continues to produce `ApiResponse` envelopes and field-specific `INVALID_ARGUMENT` responses instead of framework-default JSON. These seams log application warnings, meter `grpc.app_error` where applicable, and preserve span/error-code classification. + +## Validation and Proof + +The evidence records focused unit, controller, gRPC, WebSocket, cross-service, and restart/rebind proofs for text parsing and Telnet parity; real Account-backed generic login and authenticated `PLAY`; takeover, resume, logout, and replay cleanup; public-production membership idempotency; session-start IP ordering; malformed claim and positive-ID rejection; replay identity/payload mismatch; current REST/gRPC error envelopes; and Gateway upstream/process restart continuity. Earlier positive first-party handshake/reconnect proofs describe the superseded HMAC-cookie path and are historical. Current focused first-party tests cover denial and unavailable readiness; envelope, owner, retained-context, and consumer proofs remain bounded as recorded above and do not qualify production ingress. It does not yet prove the owner gRPC typed-result/non-OK classification across every adopter. The Telnet cross-service harness uses a lightweight Gateway stub only as a test fixture and has a successful `TelnetGatewayGameSessionCrossServiceIntegrationTest`; the maintained runtime path is not the stub. + +The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. Earlier first-party fresh-token, bare-login, `PLAY` scope, replay/expiry/context, screen-buffer restore, and fresh-redraw proofs describe the superseded path; current first-party coverage is fail-closed and does not establish playable admission. + +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox boundary, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. + +- **Validation record:** Required current documentation, contract, settings-generation, allocation, ADR, and `git diff --check` gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Runtime proof is not applicable to this documentation-only change. + +## Active Gaps + +- Account authentication has no stable attempt identity or replayable result contract. Game Session now avoids automatically retrying an ambiguous credential-consuming transport failure, but Account still needs durable request identity and idempotent result lookup before authentication itself is safely retryable. +- Signup-time login-mode selection and authenticator-app TOTP enrollment/management are not implemented; the live credential contract remains password plus email OTP. Richer MFA policy for elevated users is also future work. +- Tenant membership currently persists admission permission rather than the designed tenant-role set; Account JWT issuance does not emit tenant `scopedRoles`, and realm grants have no expiry or tenant-admin management surface. +- The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; `past_due` is currently gameplay-available and public-join-eligible. Durable `purchase_entitlement` fulfillment/revocation is also absent. +- Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam accept parameterized credentials; public non-proxy `/ws/game/**` currently fails closed, and first-party bare `LOGIN`/`PLAY` do not reach legacy Account, Entity, or binding effects. +- Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect after its protected receiving chain is qualified, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. +- Earlier first-party post-logout replay behavior is historical and unreachable while first-party admission fails closed. Recheck it when the protected receiver is qualified; durable transcript retention alone must not establish reconnect eligibility. +- Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. +- Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. +- Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. +- Account hard-delete currently fails closed; retained payment and subscription lifecycle and deletion reconciliation remain incomplete. +- Account deletion also remains blocked by any retained JOIN operation row, including terminal receipts, through the current fail-closed `hasRetainedOperation` guard. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented; Account's retention/deletion workflow owns them under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), dependent on #2848 JOIN receipt and unknown-outcome reconciliation. No universal retention duration is selected. +- Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. +- Automated signing-key rotation, overlap/pruning, and deployment-wide validator-convergence proof remain deferred even though JWKS publication and conditional file watching are live. +- The continuity boundary intentionally excludes generalized chaos testing, arbitrary command replay, transport-byte replay, and reconstruction of queue/tick ownership if Game Logic later owns durable execution. +- The guardrail family should reopen only for a new concrete auth/session/routing regression; it is not a completed audit of every future service ingress. + +## To Discuss + +No competing target state is currently recorded. Future design discussion is required before changing credential modes or introducing the shared OTP/TOTP enrollment model, changing Account-owned admission authority or the account-versus-tenant ownership split, expanding reconnect guarantees beyond bounded redraw, or making non-edge restart continuity depend on durable queue/tick ownership. Future smart-client attach metadata must remain non-authoritative if revived. + +## Service and Contract Map + +| Owner | Current responsibility | Primary contract boundary | +| --- | --- | --- | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN; canonical gameplay connect-token production currently fails closed after bootstrap/scope validation | Account REST/gRPC APIs, including `/auth/bootstrap/join` and the local JOIN RPC; `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | +| Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | +| TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | +| Spring Cloud Gateway | Trusted TCP Proxy handshake validation, stable edge socket/session id, upstream gameplay bridge and rebind; public first-party cookie admission and route readiness currently fail closed pending canonical producer/replay/key qualification | `/ws/game/**`; `TrustedTcpProxyIdentity`; current first-party cookie denial and separate TCP Proxy listener boundary | +| Game Session | Text parser/interpreter, generic login/play/logout, Redis session context, takeover/resume, gameplay presence, admission normalization, command/control-plane routing, and redraw; first-party signed-context/route/private-handle receiving sources are local preparation, while bare first-party LOGIN/PLAY deny before downstream effects; StartSession retains and rechecks the Account-compared owner tuple | Text-command protocol; WebSocket ingress; Game Session gRPC/control plane; Account and World/Entity calls; first-party context consequence in [Authentication and authorization](../../architecture/system-architecture-authentication.md#gateway-to-game-session-connect-context-normative); owner-tuple consequence in [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | +| World and Entity Management | Current room/runtime authority, gameplay admission dependencies, runtime teardown, actor/item/room reads, and presence cleanup | Gameplay-attested gRPC/REST seams; World termination and Entity cleanup called by Game Session | +| Social Groups and Automation | Authenticated gameplay-adjacent communication/presence and runtime script/event admission using the same identity/routing guardrails | Positive-ID/current-account readers; gameplay routing bundles; canonical REST/gRPC error envelopes | +| Logging & Admin | Authenticated operator/control-plane reads, mutation/remediation actor identity, audit and response projection; StartSession compares and persists the Account-returned owner tuple for handoff | Control-plane client readers; `ApiResponse` REST boundary; owner-tuple consequence in [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | +| Game Logic | Current-state command aggregation after recovery; currently stateless `LOOK`, movement-derived room context, and communication fan-out inputs | Post-restart gameplay command paths backed by shared world/session state | 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 2ca0ed01c0..eb94669b74 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 @@ -135,3 +135,434 @@ final class AccountControlUiOwnerSourcesFixture { String migrationTarget) throws Exception { if (migrationTarget != null && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) && !"1007".equals(migrationTarget) && !"1009".equals(migrationTarget)) { + throw new IllegalArgumentException( + "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, or 1009 selected-owner predecessor is supported"); + } + this.tenant = Objects.requireNonNull(tenant); + String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = new DriverManagerDataSource(jdbcUrl, username, password); + dataSource.setSchema(schema); + migrationSource = dataSource; + migrationSchema = schema; + var migrations = migrationConfiguration(); + if (migrationTarget != null) migrations.target(migrationTarget); + migrations.load().migrate(); + manager = new DataSourceTransactionManager(dataSource); + transactions = new TransactionTemplate(manager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + accounts = new AccountRepository(dsl, sourceEvidence); + account = + tx( + () -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("owner-" + suffix); + candidate.setEmail(suffix + "@example.test"); + candidate.setPasswordHash(hash("test-only-disabled-password")); + candidate.setLoginAuthModes("EMAIL_OTP"); + return accounts.save(candidate); + }); + var creator = testCreation(account.getAccountUuid(), tenant); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + tx( + () -> { + fresh.importVerified(creator.creationEvidence()); + generations.initializeTenantIfAbsent(tenant); + return null; + }); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var reader = + new AccountCreatorMembershipSourceReader( + accounts, + new AccountJoinOperationRepository(dsl), + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sourceEvidence, + bootstrapOperations); + var beans = new StaticListableBeanFactory(); + AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = + (actual, mutation) -> { + if (!creator.equals(actual) + || !TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Exact test-only external bootstrap fixture required"); + } + return mutation.get(); + }; + beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); + var bootstrap = + new AccountTenantCreationBootstrapService( + accounts, + fresh, + reader, + pairs, + memberships, + roles, + outbox, + new AccountAuditOutboxRepository(dsl), + bootstrapOperations, + beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); + tx(() -> bootstrap.bootstrap(creator)); + var party = + new IndividualCreatorPartySource( + UUID.randomUUID(), + account.getAccountUuid(), + VerificationStatus.VERIFIED, + 1L, + "test-only-policy", + 1L, + "test-only-verification", + 1L, + 1L); + insertTestParty(dsl, party); + var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); + tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); + fences = new DraftAuthorizationFenceRepository(dsl); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindings = new HashMap<>(); + terms = + new AccountHostedTermsService( + manager, + new HostedTermsRepository(dsl), + parties, + fences, + id -> externalFixture(publications, id), + id -> externalFixture(actions, id), + new HostedTermsEnvironmentBindingRepository(dsl), + id -> externalFixture(bindings, id), + () -> { + requireOutsideTransaction(); + return boundary.get(); + }); + UUID publication = UUID.randomUUID(); + publications.put( + publication, + new AccountHostedTermsService.PublicationEvidence( + UUID.randomUUID(), + "Test-only Operator", + 1L, + bytes("Test-only initial terms"), + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-audit", + 1L, + "test-only-notice", + 1L, + Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); + var catalog = terms.publish(publication).candidate(); + UUID action = UUID.randomUUID(); + actions.put( + action, + new AccountHostedTermsService.AcceptanceAction( + action, + true, + account.getAccountUuid(), + party.creatorPartyId(), + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-affirmative-action", + 1L, + OffsetDateTime.now(ZoneOffset.UTC))); + terms.accept(action); + UUID binding = UUID.randomUUID(); + bindings.put( + binding, + new HostedTermsEnvironmentBinding.PublicationEvidence( + "test-production", + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + "test-only-environment-publisher", + "test-only-environment-publication/" + binding, + null, + null)); + terms.publishEnvironmentBinding(binding); + authority = + new AccountControlUiAuthority( + new AccountDraftSourceCompositionService( + dsl, parties, bootstrap, terms, sourceEvidence)); + challenges = new AccountEmailLoginChallengeRepository(dsl); + tx( + () -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); + var primaryTarget = + new AccountServiceImpl( + accounts, + generations, + sourceEvidence, + outbox, + mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + mock(AccountAuditOutboxRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + .class), + mock(AccountJoinOperationRepository.class), + challenges, + null, // Realm grants are not used by primary authentication. + null, // Tenant memberships are not used by primary authentication. + Mappers.getMapper(AccountMapper.class), + null, // Profiles are not used by primary authentication. + null, // Profile mapper is not used by primary authentication. + null, // Payment transactions are not used by primary authentication. + null, // Subscriptions are not used by primary authentication. + null, // External identities are not used by primary authentication. + null, // Password reset tokens are not used by primary authentication. + null, // Email verification tokens are not used by primary authentication. + null, // Notifications are not used by primary authentication. + null, // Email delivery is not used by primary authentication. + null, // Mail properties are not used by primary authentication. + null, // Token properties are not used by primary authentication. + null, // JWT auth properties are not used by primary authentication. + null, // Game Session client is not used by primary authentication. + null, // Entity Management client is not used by primary authentication. + null, // JWT utility is not used by primary authentication. + null, // Session service is not used by primary authentication. + manager); + // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. + var primaryProxy = new ProxyFactory(primaryTarget); + primaryProxy.setProxyTargetClass(true); + primaryProxy.addAdvice( + new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); + primary = (AccountServiceImpl) primaryProxy.getProxy(); + if (!installNegativeIssuer) { + service = null; + return; + } + var signerFixture = new AccountControlUiSignerFixture(this, root); + signerFixture.prepareInitialPrepublication(); + var signer = signerFixture.signer; + var operations = new AccountControlUiIssuanceRepository(dsl); + var crypto = + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); + var registry = + new AccountControlUiCoordination( + () -> { + coordinationCalls.incrementAndGet(); + throw new IllegalStateException("No physical Redis fixture in this negative proof"); + }, + new AcknowledgementRequirements(1, 1, 1000), + RedisScriptCatalog.fromContributions(List.of())); + var publicSource = + new AccountJwtJwksTrustedSource( + signerFixture.client, + signerFixture.trust, + signerFixture.desired, + signerFixture.publication, + manager); + var actors = + new AccountControlUiActorService( + operations, + authority, + signer, + registry, + publicSource, + fences, + manager, + Clock.systemUTC()); + service = + new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signer, + crypto, + registry, + actors, + manager, + Clock.systemUTC(), + 300_000L, + CALLER); + } + + AccountControlUiIssuanceService.Request request(String secret) { + return new AccountControlUiIssuanceService.Request( + request, account.getEmail(), secret, tenant, callerContext); + } + + T tx(Supplier action) { + return transactions.execute(ignored -> action.get()); + } + + /** Uses the real owner to advance generation, fence and source event with the scalar role. */ + Account changeRoleToAdmin() { + Account current = accounts.findById(account.getId()).orElseThrow(); + current.setRole("admin"); + return accounts.save(current); + } + + void assertNoIssuance() { + assertThat(dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); + assertThat(coordinationCalls).hasValue(0); + } + + private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { + UUID request = UUID.randomUUID(), + operation = UUID.randomUUID(), + authorization = UUID.randomUUID(); + String key = "test-only-game-row-17"; + String digest = + GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + digest, + tenant, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "8".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creation, + account, + authorization, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, account, authorization, authorizationDigest)); + } + + private static void insertTestParty(DSLContext dsl, IndividualCreatorPartySource party) { + byte[] source = CreatorPartyEncoding.party(party); + dsl.execute( + "INSERT INTO account_individual_creator_party_sources" + + " (creator_party_id, account_uuid, verification_status, identity_version, policy_reference, policy_version," + + " verification_evidence_reference, verification_evidence_version, source_version, source_payload, source_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + source, + CreatorPartyEncoding.digest(source)); + } + + static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary testBoundary(String name) { + byte[] source = bytes("test-only-environment-observation/" + name); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + name, + "test-only-environment-owner", + "test-only-observation/" + name, + source, + HostedTermsEncoding.digest(source)); + } + + private static T externalFixture(Map values, UUID request) { + requireOutsideTransaction(); + return Objects.requireNonNull( + values.get(request), "Exact test-only external evidence required"); + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "External fixture observation must precede Account owner locks"); + } + } + + static PeerScope withPeer(String uri) { + var attached = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + return new PeerScope(attached.attach(), attached); + } + + record PeerScope(Context previous, Context attached) implements AutoCloseable { + @Override + public void close() { + attached.detach(previous); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String hash(String value) { + char[] secret = value.toCharArray(); + var argon = Argon2Factory.create(); + try { + return argon.hash(2, 4096, 1, secret); + } finally { + argon.wipeArray(secret); + } + } + + /** Applies only the remaining real migrations, without rewriting retained fixture rows. */ + void upgradeToCurrent() { + migrationConfiguration().load().migrate(); + } + + private org.flywaydb.core.api.configuration.FluentConfiguration migrationConfiguration() { + return Flyway.configure() + .dataSource(migrationSource) + .schemas(migrationSchema) + .defaultSchema(migrationSchema) + .placeholders(Map.of("serviceSchema", migrationSchema)) + .locations( + "filesystem:" + accountMigrations(), + "filesystem:" + + accountMigrations() + .resolve("../../../../../../common-saga/src/main/resources/db/migration/saga") + .normalize()); + } + + private static Path accountMigrations() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + Path migrations = current.resolve("services/account-service/src/main/resources/db/migration"); + if (java.nio.file.Files.isDirectory(migrations)) return migrations; + current = current.getParent(); + } + throw new IllegalStateException("Exact Account migration directory is required"); + } +} 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 88e992d793..3d7bc17286 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 @@ -193,3 +193,102 @@ ClientHandle create( var client = new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } + case SOURCE_READ -> { + var client = new GrpcSelectedOwnerIntakeSourceReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case AUTOMATION_TERMINAL -> { + var client = new AutomationSelectedSourceIntakeTerminalReadClient(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); + } + case WORLD_INVENTORY -> { + var client = new WorldSelectedOwnerInventoryGrpcClient(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); + } + } +} From 4701e8aee6b4669b118f8869895c6060f136500e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:49:15 +1300 Subject: [PATCH 06/27] Carry shared terminal proof fixture to its first consumer --- ...tSelectedOwnerIntakeSourceReadService.java | 4 + ...ectedSourceIntakeTerminalReadFixtures.java | 562 ++++++++++++++++++ 2 files changed, 566 insertions(+) create mode 100644 services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java 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 da3fc6945c..d0dbbdf384 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,5 +1,6 @@ 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; @@ -21,6 +22,9 @@ public final class AccountSelectedOwnerIntakeSourceReadService { private final TransactionTemplate transaction; private final String namespace; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected owner repository is intentionally shared across owner operations") public AccountSelectedOwnerIntakeSourceReadService( AccountSelectedOwnerIntakeSourceReservationRepository repository, AccountControlUiCoordination registry, diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java new file mode 100644 index 0000000000..c352de61a5 --- /dev/null +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java @@ -0,0 +1,562 @@ +package net.firedevops.firemud.testsupport.entity; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +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.DraftAuthorizationFenceBinding.SourceKind; +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.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; + +/** + * Synthetic input values for canonical codec and loopback-mTLS tests only. + * + *

The all-zero Entity family rows are deliberately fabricated constructor inputs. They do not + * prove an Entity provider census, physical persistence, fresh-empty admission, or retained + * production receipt. + */ +public final class EntitySelectedSourceIntakeTerminalReadFixtures { + 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 ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final String NAMESPACE = "test"; + + private EntitySelectedSourceIntakeTerminalReadFixtures() {} + + public static Fixture create() { + OwnerFixture entity = ownerFixture(Owner.ENTITY_MANAGEMENT); + OwnerFixture automation = ownerFixture(Owner.AUTOMATION_SCRIPTING); + var binding = entity.authorization(); + var inputs = entity.inputs(); + String requestDigest = + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, binding, inputs.worldInventoryReadEvidence().request().freezeEvidence()); + var receipt = + EntityEmptySelectedSourceIntakeReceipt.create( + inputs, + id("88888888-8888-4888-8888-888888888888"), + 9001L, + 9002L, + requestDigest, + syntheticZeroFamilyRows(), + OffsetDateTime.parse("2026-10-01T00:00:00Z")); + return new Fixture(binding, automation.authorization(), inputs, receipt); + } + + private static OwnerFixture ownerFixture(Owner owner) { + DraftCommitBinding selected = selected(); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + id("55555555-5555-4555-8555-555555555555"), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + ACTOR, + selected); + var sourceContent = sourceContent(scope, templateSnapshot(selected)); + var authorization = + new SelectedOwnerIntakeAuthorizationBinding(sourceContent, accountSources()); + var freezeEvidence = freezeEvidence(selected); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freezeEvidence); + var worldInventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freezeEvidence, publicInventory(freezeEvidence)); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, worldInventory); + return new OwnerFixture( + authorization, new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot(DraftCommitBinding selected) { + var payloads = new ArrayList(); + for (Owner owner : + List.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).stream().sorted().toList()) { + if (owner == Owner.AUTOMATION_SCRIPTING) { + payloads.add( + TemplateConfigSourceValues.ownerInventoryPayload( + owner, + net.firedevops.firemud.common.automation + .AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()))); + } else { + payloads.add( + TemplateConfigSourceValues.ownerInventoryPayload( + owner, EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()))); + } + } + DraftCommitBinding authored = authoredBinding(payloads); + var mutations = TemplateConfigSourceValues.mutations(authored); + var declarations = + mutations.stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .sorted(java.util.Comparator.comparing(declaration -> declaration.owner().name())) + .toList(); + return new TemplateConfigSourceSnapshot( + selected, + "1", + authored.commitId(), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + List.of(), + declarations); + } + + private static DraftCommitBinding authoredBinding(List payloads) { + List revisions = new ArrayList<>(); + for (int index = 0; index < payloads.size(); index++) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(index))); + } + return DraftCommitBinding.create( + target(), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope, TemplateConfigSourceSnapshot templateSnapshot) { + var out = new java.io.ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + return new net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource( + net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.explicitEmpty() + .canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + return switch (family) { + case "COMMAND" -> + new CommandSnapshot(selected, "0", null, "sha256:" + "a".repeat(64), List.of()) + .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(); + default -> throw new IllegalArgumentException("Unsupported synthetic source family"); + }; + } + + private static List accountSources() { + return List.of( + new SourceEvidence( + SourceKind.TENANT, + TENANT.toString(), + null, + "1", + null, + null, + syntheticLargeSourceBytes()), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); + } + + private static byte[] syntheticLargeSourceBytes() { + byte[] bytes = new byte[4 * 1024 * 1024 + 1024]; + java.util.Arrays.fill(bytes, (byte) 'S'); + return bytes; + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected() { + return DraftCommitBinding.create( + target(), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static DraftCommitBinding.TargetProof target() { + return new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + DraftCommitBinding selected) { + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + "9", + "synthetic selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "synthetic-publication"))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + TENANT, + VERSION, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 0), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + emptyInboundClosure()); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + new PublicOwnerScope( + request.targetNamespace(), + TENANT, + VERSION, + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)), + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static List + syntheticZeroFamilyRows() { + List families = + List.of( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS", + "BODY_LAYOUT_ROOTS", + "CRAFTING_INGREDIENT_BINDINGS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_RECIPE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "EQUIPMENT_SLOT_GROUPS", + "EQUIPMENT_SLOT_ROOTS", + "INBOUND_LOOT_BINDINGS", + "ITEM_TEMPLATE_ROOTS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS"); + return families.stream() + .map( + family -> + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + family, + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + v1CensusFamily(family) + ? EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS + : EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind + .EMPTY_ONLY_OWNER_PROVIDER, + 0, + 0, + 0, + 0, + 0)) + .toList(); + } + + private static boolean v1CensusFamily(String family) { + return List.of( + "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS") + .contains(family); + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private static void frame(java.io.ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(java.io.ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + public record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerIntakeAuthorizationBinding wrongOwnerAuthorization, + SelectedOwnerEmptySourceInputs inputs, + EntityEmptySelectedSourceIntakeReceipt receipt) {} + + private record OwnerFixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerEmptySourceInputs inputs) {} +} From d2e5a37bae08b94ced069ea43f20e12e784cc2b8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:49:28 +1300 Subject: [PATCH 07/27] Apply canonical selected intake formatting --- ...eAuthorizationPostgresIntegrationTest.java | 169 +++++++++++++----- .../AccountControlUiOwnerSourcesFixture.java | 6 +- ...electedSourceIntakeTerminalReadClient.java | 5 +- ...electedOwnerIntakeClientLifecycleTest.java | 13 +- ...ourceIntakeTerminalReadClientMtlsTest.java | 13 +- 5 files changed, 142 insertions(+), 64 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 696b0f34d7..20920fbed8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -11,8 +11,8 @@ import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Comparator; -import java.util.List; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; @@ -102,7 +102,8 @@ class AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest { private static final Network NETWORK = Network.newNetwork(); @Container - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer redis = @@ -817,22 +818,38 @@ void upgradesCombinedV1007ParentThroughFinalAuthorizationAndBothTerminalOwnersWi throws Exception { try (var fixture = new AccountControlUiOriginalOrderFixture( - postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), - redis.getHost(), redis.getMappedPort(6379), temporary, UUID.randomUUID(), - Clock.systemUTC(), "1007")) { + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + Clock.systemUTC(), + "1007")) { var issued = fixture.issueCreator(); var f = issued.sources(); - assertThat(f.dsl.fetch("SELECT version FROM flyway_schema_history WHERE success") - .getValues(0, String.class)) + assertThat( + f.dsl + .fetch("SELECT version FROM flyway_schema_history WHERE success") + .getValues(0, String.class)) .contains("1000", "1001", "1002", "1005", "1006", "1007") .doesNotContain("1008", "1009", "1010"); var selected = selectedForSettlement(f.tenant); settleOriginal(issued, selected); var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); - var reservations = new AccountSelectedOwnerIntakeSourceReservationService( - issued.actors(), f.fences, repository, f.manager, "test"); - var scope = asGameDesign(() -> reservations.reserveSourceRead( - issued.compact(), UUID.randomUUID(), Owner.ENTITY_MANAGEMENT, selected, issued.environment())); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var scope = + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); seedRetainedCombinedParentRows(f.dsl); var retainedRows = retainedCombinedParentRows(f.dsl); assertThat(retainedRows.values()).allSatisfy(rows -> assertThat(rows).isNotEmpty()); @@ -843,19 +860,28 @@ void upgradesCombinedV1007ParentThroughFinalAuthorizationAndBothTerminalOwnersWi var retainedHistory = f.dsl.fetch(historyQuery).getValues(0, String.class); var inheritedGuards = retainedInheritedGuardDefinitions(f.dsl); assertThat(inheritedGuards.get("account_ss_activation_settlement_insert_guard()")) - .contains("terminal->>'activationResultSha256' IS DISTINCT FROM 'sha256:' || encode(sha256(result_bytes), 'hex')"); + .contains( + "terminal->>'activationResultSha256' IS DISTINCT FROM 'sha256:' || encode(sha256(result_bytes), 'hex')"); Flyway upgrade = intakeMigration(f, "1010"); assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(3); upgrade.validate(); assertThat(f.dsl.fetch(historyQuery).getValues(0, String.class)).isEqualTo(retainedHistory); assertThat(retainedCombinedParentRows(f.dsl)).isEqualTo(retainedRows); assertThat(retainedInheritedGuardDefinitions(f.dsl)).isEqualTo(inheritedGuards); - for (String table : List.of("account_selected_owner_intake_authorizations", - "account_selected_owner_intake_sources", "account_selected_owner_intake_settlements")) { + for (String table : + List.of( + "account_selected_owner_intake_authorizations", + "account_selected_owner_intake_sources", + "account_selected_owner_intake_settlements")) { assertThat(f.dsl.fetchCount(org.jooq.impl.DSL.table(table))).isZero(); } - assertThat(f.dsl.fetchSingle("SELECT account_selected_owner_intake_source_read_is_pending(?)", - scope.operationId()).get(0, Boolean.class)).isTrue(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + scope.operationId()) + .get(0, Boolean.class)) + .isTrue(); } } @@ -2214,67 +2240,112 @@ private static void awaitSourceLockWait(DSLContext dsl, int writerBackendPid) private static Flyway intakeMigration(AccountControlUiOwnerSourcesFixture f, String target) { String schema = f.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); Path root = Path.of("").toAbsolutePath(); - while (root != null && !java.nio.file.Files.isDirectory( - root.resolve("services/account-service/src/main/resources/db/migration"))) { + while (root != null + && !java.nio.file.Files.isDirectory( + root.resolve("services/account-service/src/main/resources/db/migration"))) { root = root.getParent(); } Path repositoryRoot = Objects.requireNonNull(root, "Account migrations must be available"); return Flyway.configure() .dataSource(Objects.requireNonNull(f.manager.getDataSource())) - .schemas(schema).defaultSchema(schema).placeholders(Map.of("serviceSchema", schema)) - .locations("filesystem:" + repositoryRoot.resolve("services/account-service/src/main/resources/db/migration"), - "filesystem:" + repositoryRoot.resolve("services/common-saga/src/main/resources/db/migration/saga")) - .target(target).load(); + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + repositoryRoot.resolve( + "services/account-service/src/main/resources/db/migration"), + "filesystem:" + + repositoryRoot.resolve( + "services/common-saga/src/main/resources/db/migration/saga")) + .target(target) + .load(); } private static void seedRetainedCombinedParentRows(DSLContext dsl) { - Long sagaId = dsl.fetchSingle( - "INSERT INTO saga_instance(saga_name, state) VALUES (?, ?) RETURNING id", - "retained-final-intake-upgrade", "PENDING").get(0, Long.class); - dsl.execute("INSERT INTO saga_step(instance_id, name, status, attempt) VALUES (?, ?, ?, ?)", - sagaId, "retained-step", "PENDING", 3); + Long sagaId = + dsl.fetchSingle( + "INSERT INTO saga_instance(saga_name, state) VALUES (?, ?) RETURNING id", + "retained-final-intake-upgrade", + "PENDING") + .get(0, Long.class); + dsl.execute( + "INSERT INTO saga_step(instance_id, name, status, attempt) VALUES (?, ?, ?, ?)", + sagaId, + "retained-step", + "PENDING", + 3); dsl.execute( "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(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(StandardCharsets.UTF_8)); } private static Map> retainedCombinedParentRows(DSLContext dsl) { Map> rows = new LinkedHashMap<>(); - for (String table : List.of("accounts", "account_authority_source_records", - "account_initial_gameplay_login_disposals", "saga_instance", "saga_step", - "account_selected_owner_intake_source_read_reservations", - "account_selected_owner_intake_source_read_sources")) { - rows.put(table, dsl.fetch( - "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " - + table + " t ORDER BY to_jsonb(t)::TEXT").getValues(0, String.class)); + for (String table : + List.of( + "accounts", + "account_authority_source_records", + "account_initial_gameplay_login_disposals", + "saga_instance", + "saga_step", + "account_selected_owner_intake_source_read_reservations", + "account_selected_owner_intake_source_read_sources")) { + rows.put( + table, + dsl.fetch( + "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + + table + + " t ORDER BY to_jsonb(t)::TEXT") + .getValues(0, String.class)); } return rows; } private static Map retainedInheritedGuardDefinitions(DSLContext dsl) { Map definitions = new LinkedHashMap<>(); - for (String signature : List.of("account_ss_admission_assert_no_pending(text[])", - "account_ss_activation_insert_guard()", "account_ss_activation_settlement_insert_guard()", - "account_initial_gameplay_login_disposal_immutable()", "account_initial_gameplay_login_writer_guard()", - "account_control_ui_hold_required_sources(text[])", "account_draft_authorization_source_change_guard()", - "account_hosted_terms_disclosure_handoff_guard()")) { - definitions.put(signature, - dsl.fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature).get(0, String.class)); + for (String signature : + List.of( + "account_ss_admission_assert_no_pending(text[])", + "account_ss_activation_insert_guard()", + "account_ss_activation_settlement_insert_guard()", + "account_initial_gameplay_login_disposal_immutable()", + "account_initial_gameplay_login_writer_guard()", + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()")) { + definitions.put( + signature, + dsl.fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)); } return definitions; } private static Map> retainedSelectedOwnerRows(DSLContext dsl) { Map> rows = new LinkedHashMap<>(); - for (String table : List.of("account_selected_owner_intake_source_read_reservations", - "account_selected_owner_intake_source_read_sources", "account_selected_owner_intake_source_read_aborts", - "account_selected_owner_intake_authorizations", "account_selected_owner_intake_sources", - "account_selected_owner_intake_settlements")) { - rows.put(table, dsl.fetch("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " - + table + " t ORDER BY to_jsonb(t)::TEXT").getValues(0, String.class)); + for (String table : + List.of( + "account_selected_owner_intake_source_read_reservations", + "account_selected_owner_intake_source_read_sources", + "account_selected_owner_intake_source_read_aborts", + "account_selected_owner_intake_authorizations", + "account_selected_owner_intake_sources", + "account_selected_owner_intake_settlements")) { + rows.put( + table, + dsl.fetch( + "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + + table + + " t ORDER BY to_jsonb(t)::TEXT") + .getValues(0, 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 eb94669b74..94bcb6acc7 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,11 @@ final class AccountControlUiOwnerSourcesFixture { UUID tenant, String migrationTarget) throws Exception { - if (migrationTarget != null && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) && !"1007".equals(migrationTarget) && !"1009".equals(migrationTarget)) { + if (migrationTarget != null + && !"160.1".equals(migrationTarget) + && !"1006".equals(migrationTarget) + && !"1007".equals(migrationTarget) + && !"1009".equals(migrationTarget)) { throw new IllegalArgumentException( "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, or 1009 selected-owner predecessor is supported"); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java index ddaa70d439..141f86ce77 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java @@ -7,7 +7,6 @@ import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; -import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -15,6 +14,7 @@ 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.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; import org.springframework.transaction.support.TransactionSynchronizationManager; /** File-backed mTLS client for Entity's exact original selected-source terminal read. */ @@ -99,8 +99,7 @@ protected String defaultTarget() { String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service"; return EntitySelectedSourceIntakeTerminalReadServiceGrpc.newBlockingStub(channel) - .withMaxInboundMessageSize( - EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES) + .withMaxInboundMessageSize(EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES) .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); 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 3d7bc17286..962f6c4262 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 @@ -24,11 +24,11 @@ import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; -import net.firedevops.firemud.common.publication.WorldSelectedOwnerInventoryGrpcClient; 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.WorldSelectedOwnerInventoryGrpcClient; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.parallel.ResourceLock; @@ -186,11 +186,15 @@ ClientHandle create( GrpcChannelFactory factory) { return switch (this) { case AUTHORIZATION -> { - var client = new AccountSelectedOwnerIntakeAuthorizationGrpcClient(endpoints, tls, factory, "test"); + var client = + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } case WORLD_CLOSURE_AUTHORIZATION -> { - var client = new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient(endpoints, tls, factory, "test"); + var client = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } case SOURCE_READ -> { @@ -198,7 +202,8 @@ ClientHandle create( yield new ClientHandle(client, client::init); } case AUTOMATION_TERMINAL -> { - var client = new AutomationSelectedSourceIntakeTerminalReadClient(endpoints, tls, factory, "test"); + var client = + new AutomationSelectedSourceIntakeTerminalReadClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } case GAME_DESIGN_SOURCE -> { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java index d2ff343574..ca3ae70881 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -19,16 +19,16 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; -import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; -import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; -import net.firedevops.firemud.common.entity.sourceintake.GrpcEntitySelectedSourceIntakeTerminalReadClient; -import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.GrpcEntitySelectedSourceIntakeTerminalReadClient; 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.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -38,8 +38,7 @@ class GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest { private static final String NAMESPACE = "test"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; - private static final String ENTITY_URI = - "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; @TempDir static Path tempDirectory; From 268d63153e487796bed2b10bf3821bb750a334c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:57:27 +1300 Subject: [PATCH 08/27] Run successor disclosure proof on current Account schema --- .../AccountSelectedOwnerIntakeSourceReadService.java | 3 ++- ...ctedOwnerSourceDisclosurePostgresIntegrationTest.java | 9 +++++---- 2 files changed, 7 insertions(+), 5 deletions(-) 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 d0dbbdf384..59f97e0136 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 @@ -24,7 +24,8 @@ public final class AccountSelectedOwnerIntakeSourceReadService { @SuppressFBWarnings( value = "EI_EXPOSE_REP2", - justification = "The injected owner repository is intentionally shared across owner operations") + justification = + "The injected owner repository is intentionally shared across owner operations") public AccountSelectedOwnerIntakeSourceReadService( AccountSelectedOwnerIntakeSourceReservationRepository repository, AccountControlUiCoordination registry, 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..ab82f0965f 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 @@ -133,7 +133,7 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu temporary.resolve("account"), local.binding().target().canonicalTenantId(), Clock.systemUTC(), - "1007")) { + null)) { var issued = fixture.preparedOriginalCreator(); var f = issued.sources(); assertThat( @@ -141,7 +141,7 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu .fetchSingle( "SELECT count(*) FROM flyway_schema_history WHERE version IN ('1008','1009','1010')") .get(0, Integer.class)) - .isZero(); + .isEqualTo(3); retainControlledSelectedAuthorAdmission(issued, local.binding()); var reservations = new AccountSelectedOwnerIntakeSourceReservationService( @@ -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 3a23503515b149899228856c2c6d7910a9539a4e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:57:52 +1300 Subject: [PATCH 09/27] Record selected recipient owner and migration proof --- .../microservices/account-service/runtime-and-data.md | 2 +- .../implementation-tracking/player-access-and-session.md | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9b310ec31d..105c4507f7 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 intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. The preceding source-disclosure upgrade and composition pass focused PostgreSQL proof; full-native qualification remains held on inherited PostgreSQL/Redis failures. PostgreSQL upgrade and final-owner proofs for authorization and terminal settlement have not run. These components remain unregistered and unqualified; 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 intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. The preceding source-disclosure upgrade and composition pass focused PostgreSQL proof; full-native qualification remains held on inherited PostgreSQL/Redis failures. Focused PostgreSQL upgrade and owner-storage proof for authorization and terminal settlement passes; authenticated cross-owner composition and full-native qualification remain limited as recorded in the tracker. These components remain unregistered and unqualified; 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 9713ba9df8..0b0826af75 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,11 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected recipient source intake preparation +R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. The successor disclosure composition still requires its focused recheck after advancing its fixture from the earlier V1007-only schema to the actual V1008–V1010 repository frontier. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. + 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. Prepared forward Account V1008–V1010 final authorization and terminal settlement follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. The prepared combined-V1007 upgrade proof compares complete prior Flyway metadata and xmin, populated Account/source/disposal/Saga rows and preliminary reservation bytes, and inherited protection, alignment and source-exclusion guards. The separate V1009-to-V1010 proof retains Automation terminal bytes and pending Entity participation. These successor proofs have not run; the preceding V1007 source upgrade and exact Account-permission-to-Game-Design disclosure composition pass focused R28 PostgreSQL proof. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. Qualification and publication are pending; no selected-full attestation 4 or genuine Gameplay handoff is complete, 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. Prepared forward Account V1008–V1010 final authorization and terminal settlement follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. The prepared combined-V1007 upgrade proof compares complete prior Flyway metadata and xmin, populated Account/source/disposal/Saga rows and preliminary reservation bytes, and inherited protection, alignment and source-exclusion guards. The separate V1009-to-V1010 proof retains Automation terminal bytes and pending Entity participation. These successor owner and upgrade cases pass in R31; the preceding V1007 source upgrade and exact Account-permission-to-Game-Design disclosure composition pass focused R28 PostgreSQL proof. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. Qualification and publication are pending; no selected-full attestation 4 or genuine Gameplay handoff is complete, 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 From 82f246ab141c84af8f7382f9f5f62e998f1ec535 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 02:11:57 +1300 Subject: [PATCH 10/27] Record passing current-frontier selected disclosure composition --- .../implementation-tracking/player-access-and-session.md | 4 ++-- 1 file changed, 2 insertions(+), 2 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 0b0826af75..51c15d655a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,11 +8,11 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected recipient source intake preparation -R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. The successor disclosure composition still requires its focused recheck after advancing its fixture from the earlier V1007-only schema to the actual V1008–V1010 repository frontier. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. +R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R33 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. Prepared forward Account V1008–V1010 final authorization and terminal settlement follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. The prepared combined-V1007 upgrade proof compares complete prior Flyway metadata and xmin, populated Account/source/disposal/Saga rows and preliminary reservation bytes, and inherited protection, alignment and source-exclusion guards. The separate V1009-to-V1010 proof retains Automation terminal bytes and pending Entity participation. These successor owner and upgrade cases pass in R31; the preceding V1007 source upgrade and exact Account-permission-to-Game-Design disclosure composition pass focused R28 PostgreSQL proof. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. Qualification and publication are pending; no selected-full attestation 4 or genuine Gameplay handoff is complete, 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. Prepared forward Account V1008–V1010 final authorization and terminal settlement follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. The prepared combined-V1007 upgrade proof compares complete prior Flyway metadata and xmin, populated Account/source/disposal/Saga rows and preliminary reservation bytes, and inherited protection, alignment and source-exclusion guards. The separate V1009-to-V1010 proof retains Automation terminal bytes and pending Entity participation. These successor owner and upgrade cases pass in R31; the preceding V1007 source upgrade and exact Account-permission-to-Game-Design disclosure composition pass focused R28 PostgreSQL proof. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. The coherent owner stage is published as [draft #3249](https://github.com/benhook1013/FireMUD/pull/3249); full-native qualification remains held, no selected-full attestation 4 or genuine Gameplay handoff is complete, 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 From fe70c190ca01873d87141d785bcf2c6d1003bc1c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 21:07:55 +1300 Subject: [PATCH 11/27] test(entity): retain complete terminal receipt socket proof --- ...ourceIntakeTerminalReadClientMtlsTest.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java index ca3ae70881..816985ea7f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -103,6 +103,75 @@ void authenticatesAccountClientAndPinsSameNamespaceEntityServer() throws Excepti assertThat(calls).hasValue(1); } + @Test + void loopbackMtlsAcceptsCompleteLargeCanonicalReceipt() throws Exception { + // Codec/transport values only: this fixture supplies no genuine Account/World/Entity authority. + var fixture = + net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures + .create(); + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, fixture.authorization()); + byte[] expectedReceipt = fixture.receipt().canonicalBytes(); + var wire = + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())); + assertThat(wire.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(wire.getSerializedSize()) + .isLessThanOrEqualTo( + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES); + var service = + new EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceImplBase() { + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest original, + StreamObserver observer) { + calls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var decoded = + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(original); + assertThat(decoded).isEqualTo(request); + assertThat(decoded.binding().canonicalBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + observer.onNext( + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence( + decoded, fixture.receipt()))); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + entityServer.privateKey(), entityServer.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + client = newClient(accountClient); + client.init(); + + var actual = client.read(request); + + assertThat(actual.request()).isEqualTo(request); + assertThat(actual.receipt().canonicalBytes()).isEqualTo(expectedReceipt); + assertThat(actual.receipt().authorizationBindingBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat(calls).hasValue(1); + } + private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { startServer(identity, 0); From 3b66ba80ef3da84f406de1af3cee6d1026e11d0d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 06:53:13 +1300 Subject: [PATCH 12/27] Use canonical shared PKI for selected-owner terminal transport tests --- ...ourceIntakeTerminalReadClientMtlsTest.java | 34 ++++++++--------- ...ourceIntakeTerminalReadClientMtlsTest.java | 38 +++++++++---------- 2 files changed, 32 insertions(+), 40 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java index d20a72cca2..8fbc6f2eef 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -43,9 +43,7 @@ class AutomationSelectedSourceIntakeTerminalReadClientMtlsTest { @TempDir static Path tempDirectory; - private static GameLogicIntakeSourceReadTransportTest.TestPki pki; - private static GameLogicIntakeSourceReadTransportTest.TestIdentity automationServer; - private static GameLogicIntakeSourceReadTransportTest.TestIdentity accountClient; + private static IntakeTestPki pki; private Server server; private AutomationSelectedSourceIntakeTerminalReadClient client; @@ -53,15 +51,15 @@ class AutomationSelectedSourceIntakeTerminalReadClientMtlsTest { @BeforeAll static void certificates() throws Exception { - pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); - Path caStore = tempDirectory.resolve("terminal-test-ca.p12"); - Path caFile = tempDirectory.resolve("terminal-test-ca.crt"); - automationServer = - GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( - tempDirectory, caStore, caFile, "automation-terminal-server", AUTOMATION_URI, true); - accountClient = - GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( - tempDirectory, caStore, caFile, "account-terminal-client", ACCOUNT_URI, false); + pki = + IntakeTestPki.create( + tempDirectory, + "terminal", + "FireMUD terminal-read test CA", + IntakeTestPki.IdentitySpec.server("automation-terminal-server", AUTOMATION_URI), + IntakeTestPki.IdentitySpec.server( + "wrong-server", "spiffe://firemud/ns/test/sa/game-logic-service"), + IntakeTestPki.IdentitySpec.client("account-terminal-client", ACCOUNT_URI)); } @AfterEach @@ -79,9 +77,9 @@ void closeTransport() throws Exception { @Test void authenticatesAccountClientAndPinsSameNamespaceAutomationServer() throws Exception { - startServer(automationServer); + startServer(pki.server()); final int serverPort = server.getPort(); - client = newClient(accountClient); + client = newClient(pki.client()); client.init(); assertThatThrownBy(() -> client.read(request())) @@ -104,13 +102,11 @@ void authenticatesAccountClientAndPinsSameNamespaceAutomationServer() throws Exc assertThat(calls).hasValue(1); } - private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) - throws Exception { + private void startServer(IntakeTestPki.Identity identity) throws Exception { startServer(identity, 0); } - private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity, int port) - throws Exception { + private void startServer(IntakeTestPki.Identity identity, int port) throws Exception { var service = new AutomationSelectedSourceIntakeTerminalReadServiceGrpc .AutomationSelectedSourceIntakeTerminalReadServiceImplBase() { @@ -140,7 +136,7 @@ public void readSelectedSourceIntakeTerminal( } private AutomationSelectedSourceIntakeTerminalReadClient newClient( - GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + IntakeTestPki.Identity identity) throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setAutomationScriptingService("localhost:" + server.getPort()); return new AutomationSelectedSourceIntakeTerminalReadClient( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java index 816985ea7f..b9c7b1c0e3 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -42,9 +42,7 @@ class GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest { @TempDir static Path tempDirectory; - private static GameLogicIntakeSourceReadTransportTest.TestPki pki; - private static GameLogicIntakeSourceReadTransportTest.TestIdentity entityServer; - private static GameLogicIntakeSourceReadTransportTest.TestIdentity accountClient; + private static IntakeTestPki pki; private Server server; private GrpcEntitySelectedSourceIntakeTerminalReadClient client; @@ -52,15 +50,15 @@ class GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest { @BeforeAll static void certificates() throws Exception { - pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); - Path caStore = tempDirectory.resolve("terminal-test-ca.p12"); - Path caFile = tempDirectory.resolve("terminal-test-ca.crt"); - entityServer = - GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( - tempDirectory, caStore, caFile, "entity-terminal-server", ENTITY_URI, true); - accountClient = - GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( - tempDirectory, caStore, caFile, "account-terminal-client", ACCOUNT_URI, false); + pki = + IntakeTestPki.create( + tempDirectory, + "terminal", + "FireMUD terminal-read test CA", + IntakeTestPki.IdentitySpec.server("entity-terminal-server", ENTITY_URI), + IntakeTestPki.IdentitySpec.server( + "wrong-server", "spiffe://firemud/ns/test/sa/game-logic-service"), + IntakeTestPki.IdentitySpec.client("account-terminal-client", ACCOUNT_URI)); } @AfterEach @@ -78,9 +76,9 @@ void closeTransport() throws Exception { @Test void authenticatesAccountClientAndPinsSameNamespaceEntityServer() throws Exception { - startServer(entityServer); + startServer(pki.server()); final int serverPort = server.getPort(); - client = newClient(accountClient); + client = newClient(pki.client()); client.init(); assertThatThrownBy(() -> client.read(request())) @@ -153,14 +151,14 @@ public void readSelectedSourceIntakeTerminal( .sslContext( GrpcSslContexts.configure( SslContextBuilder.forServer( - entityServer.privateKey(), entityServer.certificate())) + pki.server().privateKey(), pki.server().certificate())) .trustManager(pki.caCertificate()) .clientAuth(ClientAuth.REQUIRE) .build()) .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) .build() .start(); - client = newClient(accountClient); + client = newClient(pki.client()); client.init(); var actual = client.read(request); @@ -172,13 +170,11 @@ public void readSelectedSourceIntakeTerminal( assertThat(calls).hasValue(1); } - private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) - throws Exception { + private void startServer(IntakeTestPki.Identity identity) throws Exception { startServer(identity, 0); } - private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity, int port) - throws Exception { + private void startServer(IntakeTestPki.Identity identity, int port) throws Exception { var service = new EntitySelectedSourceIntakeTerminalReadServiceGrpc .EntitySelectedSourceIntakeTerminalReadServiceImplBase() { @@ -208,7 +204,7 @@ public void readSelectedSourceIntakeTerminal( } private GrpcEntitySelectedSourceIntakeTerminalReadClient newClient( - GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + IntakeTestPki.Identity identity) throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setEntityManagementService("localhost:" + server.getPort()); return new GrpcEntitySelectedSourceIntakeTerminalReadClient( From ae71bdbc48db537ab8ffba13260e71cbdf8b3519 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:25:48 +1300 Subject: [PATCH 13/27] Append the recipient validation-allowance recurrence without editing prior notes --- design/project-management/ai-observations.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 28be17fb5c..a13d0212fb 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -194,7 +194,6 @@ Entry format: - Context: A historical-test receiving helper ran `git diff --check` despite an explicit validation allowance of NONE. - Observation: It reported the extra check; no runtime tests or source edits resulted from it. The handoff also said no validation ran, which obscured the distinction. - Expected pattern: Treat standalone whitespace checks as validation under the closed allowance. Report the actual check and its outcome, and wait for the orchestrator’s named gate. Main gave that bounded correction and selected receiving proof separately; the extra check earns no test credit. - - Recurrence (`2026-10-18`, #3249): a parent-carry helper again ran a scoped `git diff --cached --check` under an explicit validation allowance of NONE. The check exited zero and grants no proof credit. Main corrected the contradictory no-validation claim and retained ownership of the named integration gate. - 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. @@ -231,3 +230,5 @@ Entry format: - 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`: Recurrence (#3249): a parent-carry helper again ran a scoped `git diff --cached --check` under an explicit validation allowance of NONE. The check exited zero and grants no proof credit. Main corrected the contradictory no-validation claim and retained ownership of the named integration gate. From 361125c05facbdac08236cd694d75d23e6b5f530 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:31:45 +1300 Subject: [PATCH 14/27] Address selected-owner transport and binding review findings --- design/project-management/ai-observations.md | 5 +- .../player-access-and-session.md | 2 +- ...osureAuthorizationReadGrpcServiceTest.java | 22 +- ...tedOwnerIntakeAuthorizationGrpcClient.java | 82 +---- ...keWorldClosureAuthorizationGrpcClient.java | 82 +---- ...lectedOwnerIntakeAuthorizationBinding.java | 64 +++- ...electedSourceIntakeTerminalReadClient.java | 82 +---- ...electedSourceIntakeTerminalReadClient.java | 81 +---- ...WorldSelectedOwnerInventoryGrpcClient.java | 72 +--- ...edOwnerIntakeAuthorizationBindingTest.java | 14 + ...erIntakeAuthorizationReadEvidenceTest.java | 66 +--- ...wnerWorldInventoryRecipientFieldsTest.java | 65 +--- ...SelectedOwnerIntakeSourceTestFixtures.java | 32 ++ ...SelectedOwnerInventoryReadGrpcService.java | 9 +- ...ctedOwnerInventoryReadGrpcServiceTest.java | 325 ++++++++++++++++++ 15 files changed, 490 insertions(+), 513 deletions(-) create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a13d0212fb..f7b7bf67e7 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -231,4 +231,7 @@ Entry format: - 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`: Recurrence (#3249): a parent-carry helper again ran a scoped `git diff --cached --check` under an explicit validation allowance of NONE. The check exited zero and grants no proof credit. Main corrected the contradictory no-validation claim and retained ownership of the named integration gate. +- `2026-10-18`: Validation allowance NONE recurred in #3249 + - Context: A parent-carry helper again ran a scoped `git diff --cached --check` under an explicit validation allowance of NONE, repeating the [2026-10-17: A validation allowance of NONE includes whitespace checks](#ai-observations) finding. + - Observation: The check exited zero and grants no proof credit. Main corrected the contradictory no-validation claim and retained ownership of the named integration gate. + - Expected pattern: Honor NONE as excluding every check, including scoped Git whitespace checks. If a check runs anyway, report it accurately, give it no proof credit, and retain the orchestrator's ownership of the named integration gate. 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 2cf027b3ea..49248a84b8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,7 +16,7 @@ R31 freshly passes all eight Account final-authorization, exact Entity/Automatio 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. Prepared forward Account V1008–V1010 final authorization and terminal settlement follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. The prepared combined-V1007 upgrade proof compares complete prior Flyway metadata and xmin, populated Account/source/disposal/Saga rows and preliminary reservation bytes, and inherited protection, alignment and source-exclusion guards. The separate V1009-to-V1010 proof retains Automation terminal bytes and pending Entity participation. These successor owner and upgrade cases pass in R31; the preceding V1007 source upgrade and exact Account-permission-to-Game-Design disclosure composition pass focused R28 PostgreSQL proof. Shared typed transports and Game Design six-family/World recipient reads are being reconciled in the same preparation. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. The coherent owner stage is published as [draft #3249](https://github.com/benhook1013/FireMUD/pull/3249); full-native qualification remains held, no selected-full attestation 4 or genuine Gameplay handoff is complete, 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 preparation adds distinct Account reservations, current authorization, exact recovery, authenticated source/World-closure reads and terminal settlement for selected Entity and Automation intake. Prepared forward Account V1008–V1010 final authorization and terminal settlement follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. The prepared combined-V1007 upgrade proof compares complete prior Flyway metadata and xmin, populated Account/source/disposal/Saga rows and preliminary reservation bytes, and inherited protection, alignment and source-exclusion guards. The separate V1009-to-V1010 proof retains Automation terminal bytes and pending Entity participation. These successor owner and upgrade cases pass in R31; the preceding V1007 source upgrade and exact Account-permission-to-Game-Design disclosure composition pass focused R28 PostgreSQL proof. Shared typed transports and Game Design six-family/World recipient reads are prepared as unregistered source; full qualification remains pending. These owners remain unregistered, and controlled issuer, environment, source and terminal test inputs establish no genuine authority. The coherent owner stage is published as [draft #3249](https://github.com/benhook1013/FireMUD/pull/3249); full-native qualification remains held, no selected-full attestation 4 or genuine Gameplay handoff is complete, 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/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java index 7f031371b8..85ebabb83d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; /** Synthetic handler tests only; they do not establish mTLS or PostgreSQL owner proof. */ class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest { @@ -90,11 +91,14 @@ void returnsExactEchoForEntityAndAutomationButRejectsSubstitutedPurposeOrReader( var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); var service = new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + var expectedRequests = + new java.util.ArrayList(); for (Owner domain : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(domain); var request = SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + expectedRequests.add(request); var wire = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest(request); var result = new Collector(); peer("test", "world-management-service") @@ -118,7 +122,23 @@ void returnsExactEchoForEntityAndAutomationButRejectsSubstitutedPurposeOrReader( assertThat(denied.response).isNull(); } } - verify(owner, times(2)).requireHeld(any()); + var requests = + ArgumentCaptor.forClass( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.class); + verify(owner, times(2)).requireHeld(requests.capture()); + assertThat(requests.getAllValues()).hasSize(2); + for (int index = 0; index < expectedRequests.size(); index++) { + var expected = expectedRequests.get(index); + var actual = requests.getAllValues().get(index); + assertThat(actual.schemaVersion()).isEqualTo(expected.schemaVersion()); + assertThat(actual.targetNamespace()).isEqualTo(expected.targetNamespace()); + assertThat(actual.readRequestId()).isEqualTo(expected.readRequestId()); + assertThat(actual.intendedReader()).isEqualTo(expected.intendedReader()); + assertThat(actual.closureReadPurpose()).isEqualTo(expected.closureReadPurpose()); + assertThat(actual.binding().canonicalBytes()) + .containsExactly(expected.binding().canonicalBytes()); + assertThat(actual.binding().owner()).isEqualTo(expected.binding().owner()); + } } @Test diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java index 3d042ce3b6..73f6b14b74 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -11,11 +9,11 @@ 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.FileBackedMtls; 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; /** File-backed mTLS client for Account's distinct selected-owner HELD read. */ public final class AccountSelectedOwnerIntakeAuthorizationGrpcClient @@ -26,8 +24,6 @@ public final class AccountSelectedOwnerIntakeAuthorizationGrpcClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public AccountSelectedOwnerIntakeAuthorizationGrpcClient( ServiceEndpointsProperties endpoints, @@ -36,7 +32,7 @@ public AccountSelectedOwnerIntakeAuthorizationGrpcClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Account selected-owner authorization read"), channelFactory, AccountSelectedOwnerIntakeAuthorizationGrpcClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) @@ -44,31 +40,24 @@ public AccountSelectedOwnerIntakeAuthorizationGrpcClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) - throw new IllegalStateException("Account selected-owner authorization client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Account selected-owner authorization stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account selected-owner authorization client is closed", + "Account selected-owner authorization stub unavailable"); } /** Returns only Account's exact echoed HELD result, outside ambient SQL and synchronization. */ @Override public SelectedOwnerIntakeAuthorizationReadEvidence read( SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException( - "Account selected-owner authorization read must run outside SQL"); - } + requireNoAmbientSql("Account selected-owner authorization read must run outside SQL"); Objects.requireNonNull(request, "authorization-read request is required"); if (!workloadNamespace.equals(request.targetNamespace())) throw new IllegalArgumentException( "Account selected-owner authorization read must use the configured namespace"); var response = - requireStub() + requireInitializedStub( + "Account selected-owner authorization client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readHeldSelectedOwnerIntakeAuthorization( SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest(request)); @@ -101,57 +90,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc - .AccountSelectedOwnerIntakeAuthorizationReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) - throw new IllegalStateException( - "Account selected-owner authorization 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 authorization 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 authorization read requires file-backed certificate, key, and CA material"); - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) - throw new IllegalArgumentException( - "Account selected-owner authorization 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 authorization read " + label + " must be a file-backed path", - invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) - throw new IllegalArgumentException( - "Account selected-owner authorization read " - + label - + " must be an existing readable file"); - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java index 59c7eedd4f..c1f6d7b11b 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -11,11 +9,11 @@ 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.FileBackedMtls; 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; /** File-backed mTLS client for Account's distinct World closure HELD read. */ public final class AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient @@ -26,8 +24,6 @@ public final class AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( ServiceEndpointsProperties endpoints, @@ -36,7 +32,7 @@ public AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Account World closure authorization read"), channelFactory, AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) @@ -44,31 +40,24 @@ public AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) - throw new IllegalStateException("Account World closure authorization client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Account World closure authorization stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account World closure authorization client is closed", + "Account World closure authorization stub unavailable"); } /** Returns only Account's exact echoed HELD result, outside ambient SQL and synchronization. */ @Override public SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence readHeld( SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException( - "Account World closure authorization read must run outside SQL"); - } + requireNoAmbientSql("Account World closure authorization read must run outside SQL"); Objects.requireNonNull(request, "World closure authorization-read request is required"); if (!workloadNamespace.equals(request.targetNamespace())) throw new IllegalArgumentException( "Account World closure authorization read must use the configured namespace"); var response = - requireStub() + requireInitializedStub( + "Account World closure authorization client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readHeldSelectedOwnerWorldClosureAuthorization( SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest(request)); @@ -104,57 +93,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc - .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) - throw new IllegalStateException( - "Account World closure authorization client is not initialized and available"); - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) - throw new IllegalArgumentException( - "Account World closure authorization 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 World closure authorization read requires file-backed certificate, key, and CA material"); - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) - throw new IllegalArgumentException( - "Account World closure authorization read requires file-backed certificate, key, and CA material"); - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Account World closure authorization read " + label + " must be a file-backed path", - invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) - throw new IllegalArgumentException( - "Account World closure authorization read " - + label - + " must be an existing readable file"); - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java index a70bc98e1c..f7912b6ca1 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java @@ -19,31 +19,47 @@ * not authenticate Account, establish HELD/current authority, prove a complete source census, or * create an owner receipt. */ -public record SelectedOwnerIntakeAuthorizationBinding( - SelectedOwnerIntakeSourceContent content, List sources) { +public final class SelectedOwnerIntakeAuthorizationBinding { public static final int MAX_BYTES = 16 * 1024 * 1024; - public SelectedOwnerIntakeAuthorizationBinding { - Objects.requireNonNull(content, "content"); - SelectedOwnerIntakeSourceReadScope scope = content.scope(); + private final SelectedOwnerIntakeSourceContent content; + private final List sources; + private final byte[] canonicalBytes; + private final String digest; + private final int hashCode; + + public SelectedOwnerIntakeAuthorizationBinding( + SelectedOwnerIntakeSourceContent content, List sources) { + SelectedOwnerIntakeSourceContent validatedContent = Objects.requireNonNull(content, "content"); + SelectedOwnerIntakeSourceReadScope scope = validatedContent.scope(); schemaFor(scope.owner()); - sources = + List sortedSources = List.copyOf(Objects.requireNonNull(sources, "sources")).stream() .sorted(Comparator.comparing(SourceEvidence::key)) .toList(); - if (sources.isEmpty() - || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + if (sortedSources.isEmpty() + || sortedSources.stream().map(SourceEvidence::key).distinct().count() + != sortedSources.size()) { throw new IllegalArgumentException("Complete distinct Account sources required"); } - for (SourceEvidence source : sources) requireActorTenantScope(source, scope); - canonicalBytes( - content, - sources, - intendedReader(scope.owner(), scope.targetNamespace()), - purposeFor(scope.owner())); + for (SourceEvidence source : sortedSources) requireActorTenantScope(source, scope); + + this.content = validatedContent; + this.sources = sortedSources; + this.canonicalBytes = + canonicalBytes( + validatedContent, + sortedSources, + intendedReader(scope.owner(), scope.targetNamespace()), + purposeFor(scope.owner())); + this.digest = DraftAuthorizationFenceBinding.digest(this.canonicalBytes); + this.hashCode = Arrays.hashCode(this.canonicalBytes); + } + + public SelectedOwnerIntakeSourceContent content() { + return content; } - @Override public List sources() { return List.copyOf(sources); } @@ -97,11 +113,23 @@ public String intendedReader() { } public byte[] canonicalBytes() { - return canonicalBytes(content, sources, intendedReader(), purpose()); + return canonicalBytes.clone(); } public String digest() { - return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + return digest; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof SelectedOwnerIntakeAuthorizationBinding binding + && Arrays.equals(canonicalBytes, binding.canonicalBytes)); + } + + @Override + public int hashCode() { + return hashCode; } /** @@ -152,7 +180,7 @@ public static SelectedOwnerIntakeAuthorizationBinding fromStored(byte[] bytes) { if (!schema.equals(result.schema()) || !recipientReader.equals(result.intendedReader()) || !purpose.equals(result.purpose()) - || !Arrays.equals(stored, result.canonicalBytes())) { + || !Arrays.equals(stored, result.canonicalBytes)) { throw new IllegalArgumentException("Noncanonical selected owner intake authorization"); } return result; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java index 0386f11faa..ac16d2f26d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -11,11 +9,11 @@ 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.FileBackedMtls; 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; /** File-backed mTLS client for Automation's exact original selected-source terminal read. */ public final class AutomationSelectedSourceIntakeTerminalReadClient @@ -25,8 +23,6 @@ public final class AutomationSelectedSourceIntakeTerminalReadClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public AutomationSelectedSourceIntakeTerminalReadClient( ServiceEndpointsProperties endpoints, @@ -35,7 +31,7 @@ public AutomationSelectedSourceIntakeTerminalReadClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Automation terminal read"), channelFactory, AutomationSelectedSourceIntakeTerminalReadClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -44,32 +40,22 @@ public AutomationSelectedSourceIntakeTerminalReadClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) { - throw new IllegalStateException("Automation terminal-read client is closed"); - } - if (initialized) return; - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("Automation terminal-read stub unavailable"); - } - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Automation terminal-read client is closed", "Automation terminal-read stub unavailable"); } /** Returns only an exact original COMMITTED_EMPTY receipt, outside owner SQL. */ public AutomationSelectedSourceIntakeTerminalReadEvidence read( AutomationSelectedSourceIntakeTerminalReadEvidence.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException("Automation terminal read must run outside owner SQL"); - } + requireNoAmbientSql("Automation terminal read must run outside owner SQL"); Objects.requireNonNull(request, "terminal-read request is required"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Automation terminal read must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub("Automation terminal-read client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readSelectedSourceIntakeTerminal( AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); @@ -103,58 +89,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private AutomationSelectedSourceIntakeTerminalReadServiceGrpc - .AutomationSelectedSourceIntakeTerminalReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Automation terminal-read client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("Automation terminal read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Automation terminal read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Automation terminal read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Automation terminal read " + label + " must be a file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Automation terminal read " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java index 141f86ce77..ca28ee24c8 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java @@ -2,20 +2,18 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; 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.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** File-backed mTLS client for Entity's exact original selected-source terminal read. */ public final class GrpcEntitySelectedSourceIntakeTerminalReadClient @@ -26,8 +24,6 @@ public final class GrpcEntitySelectedSourceIntakeTerminalReadClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GrpcEntitySelectedSourceIntakeTerminalReadClient( ServiceEndpointsProperties endpoints, @@ -36,7 +32,7 @@ public GrpcEntitySelectedSourceIntakeTerminalReadClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Entity terminal read"), channelFactory, GrpcEntitySelectedSourceIntakeTerminalReadClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -45,33 +41,22 @@ public GrpcEntitySelectedSourceIntakeTerminalReadClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) { - throw new IllegalStateException("Entity terminal-read client is closed"); - } - if (initialized) return; - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("Entity terminal-read stub unavailable"); - } - initialized = true; + public void init() throws SSLException, IOException { + initOnce("Entity terminal-read client is closed", "Entity terminal-read stub unavailable"); } /** Returns only an exact original COMMITTED_EMPTY receipt, outside owner SQL. */ @Override public EntitySelectedSourceIntakeTerminalReadEvidence read( EntitySelectedSourceIntakeTerminalReadEvidence.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException("Entity terminal read must run outside owner SQL"); - } + requireNoAmbientSql("Entity terminal read must run outside owner SQL"); Objects.requireNonNull(request, "terminal-read request is required"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Entity terminal read must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub("Entity terminal-read client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readSelectedSourceIntakeTerminal( EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); @@ -104,58 +89,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private EntitySelectedSourceIntakeTerminalReadServiceGrpc - .EntitySelectedSourceIntakeTerminalReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Entity terminal-read client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("Entity terminal read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Entity terminal read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Entity terminal read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Entity terminal read " + label + " must be a file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Entity terminal read " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java index 8210b16b0d..ac237e0d13 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java @@ -2,20 +2,18 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.worldmanagement.v1.WorldSelectedOwnerInventoryReadServiceGrpc; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** File-backed mTLS client for the recipient-specific retained World inventory read. */ public final class WorldSelectedOwnerInventoryGrpcClient @@ -26,8 +24,6 @@ public final class WorldSelectedOwnerInventoryGrpcClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public WorldSelectedOwnerInventoryGrpcClient( ServiceEndpointsProperties endpoints, @@ -36,7 +32,7 @@ public WorldSelectedOwnerInventoryGrpcClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "World owner inventory read"), channelFactory, WorldSelectedOwnerInventoryGrpcClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -45,29 +41,20 @@ public WorldSelectedOwnerInventoryGrpcClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("World owner inventory client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("World owner inventory stub unavailable"); - } - initialized = true; + public void init() throws SSLException, IOException { + initOnce("World owner inventory client is closed", "World owner inventory stub unavailable"); } @Override public SelectedOwnerWorldInventoryReadEvidence read( SelectedOwnerWorldInventoryReadEvidence.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException("World owner inventory read requires no ambient SQL"); - } + requireNoAmbientSql("World owner inventory read requires no ambient SQL"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException("World owner inventory namespace differs from client"); } var response = - requireStub() + requireInitializedStub("World owner inventory client is not initialized") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readSelectedOwnerWorldInventory( SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(request)); @@ -100,51 +87,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private WorldSelectedOwnerInventoryReadServiceGrpc - .WorldSelectedOwnerInventoryReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException("World owner inventory client is not initialized"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("World owner inventory read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "World owner inventory read requires file-backed TLS files"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "World owner inventory read requires file-backed TLS files"); - } - Path path = Path.of(pathText); - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "World owner inventory read " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java index ae65cb4f3b..f761a805df 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java @@ -77,12 +77,24 @@ void roundTripsBothClosedOwnerDomainsWithExactCanonicalFrameAndCompleteContent() } } + @Test + void equalityUsesCanonicalBytesForEquivalentConstructionAndStoredReadback() { + var content = content(Owner.ENTITY_MANAGEMENT, ACTOR); + var original = new SelectedOwnerIntakeAuthorizationBinding(content, unsortedSources(ACTOR)); + var equivalent = new SelectedOwnerIntakeAuthorizationBinding(content, unsortedSources(ACTOR)); + var restored = SelectedOwnerIntakeAuthorizationBinding.fromStored(original.canonicalBytes()); + + assertThat(equivalent).isEqualTo(original).hasSameHashCodeAs(original); + assertThat(restored).isEqualTo(original).hasSameHashCodeAs(original); + } + @Test void preservesDefensiveCopiesOfSourceListAndCanonicalContent() { var content = content(Owner.ENTITY_MANAGEMENT, ACTOR); var input = new ArrayList<>(unsortedSources(ACTOR)); var binding = new SelectedOwnerIntakeAuthorizationBinding(content, input); byte[] expected = binding.canonicalBytes(); + String expectedDigest = binding.digest(); byte[] exposed = binding.canonicalBytes(); exposed[0] ^= 0x7f; input.clear(); @@ -92,6 +104,7 @@ void preservesDefensiveCopiesOfSourceListAndCanonicalContent() { exposedContent[0] ^= 0x7f; assertThat(binding.canonicalBytes()).isEqualTo(expected); + assertThat(binding.digest()).isEqualTo(expectedDigest); assertThat(binding.content().canonicalBytes()).isNotEqualTo(exposedContent); assertThat(binding.sources()).hasSize(3); assertThat(binding.sources().getFirst().evidence()).isNotEqualTo(exposedEvidence); @@ -264,6 +277,7 @@ void changedValidSourceEvidenceChangesDigestAndReadsBackExactly() { var changed = new SelectedOwnerIntakeAuthorizationBinding(content, changedSources); assertThat(changed.digest()).isNotEqualTo(original.digest()); + assertThat(changed).isNotEqualTo(original); assertThat( SelectedOwnerIntakeAuthorizationBinding.fromStored(changed.canonicalBytes()) .canonicalBytes()) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java index 17196be056..beaae2085a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java @@ -3,23 +3,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence.Request; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; -import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import org.junit.jupiter.api.Test; /** Synthetic lookup evidence only; Account authentication establishes the HELD result. */ @@ -73,59 +66,10 @@ static SelectedOwnerIntakeAuthorizationBinding binding(Owner owner) { var scope = new SelectedOwnerIntakeSourceReadScope( owner, "test", OPERATION, FENCE, INTAKE, actor, selected); - var content = content(scope); + var content = SelectedOwnerIntakeSourceTestFixtures.content(scope); return new SelectedOwnerIntakeAuthorizationBinding(content, sources(actor, tenant)); } - private static SelectedOwnerIntakeSourceContent content( - SelectedOwnerIntakeSourceReadScope scope) { - var out = new ByteArrayOutputStream(); - frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - frame(out, scope.canonicalBytes()); - frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = snapshot(family, scope.selected()); - frame(out, family); - frame(out, snapshot); - frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); - } - - private static byte[] snapshot(String family, DraftCommitBinding selected) { - if ("GAMEPLAY_RULE".equals(family)) { - 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", - "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", - "manifestJson", - GameplayRuleManifest.explicitEmpty().canonicalJson(), - "entries", - List.of()))) - .canonicalBytes(); - } - if ("TEMPLATE_CONFIG".equals(family)) - return new TemplateConfigSourceSnapshot( - selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) - .canonicalBytes(); - return SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); - } - private static List sources(UUID actor, UUID tenant) { var values = new ArrayList(); values.add(evidence(SourceKind.TENANT, tenant.toString(), "tenant")); @@ -163,14 +107,6 @@ private static DraftCommitBinding selected(UUID tenant) { "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); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java index 3fe96e7796..913e902ee8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java @@ -8,7 +8,6 @@ import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.util.List; -import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; @@ -18,11 +17,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; -import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; @@ -215,7 +210,7 @@ private static Fixture fixture(Owner owner) { selected); var authorization = new SelectedOwnerIntakeAuthorizationBinding( - sourceContent(sourceScope), + SelectedOwnerIntakeSourceTestFixtures.content(sourceScope), List.of( source(SourceKind.TENANT, tenant.toString(), "tenant"), source(SourceKind.ACCOUNT, actor.toString(), "account"), @@ -279,56 +274,6 @@ private static Fixture fixture(Owner owner) { return new Fixture(authorization, freezeEvidence, request, inventory); } - private static SelectedOwnerIntakeSourceContent sourceContent( - SelectedOwnerIntakeSourceReadScope scope) { - var out = new java.io.ByteArrayOutputStream(); - frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - frame(out, scope.canonicalBytes()); - frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = sourceSnapshot(family, scope.selected()); - frame(out, family); - frame(out, snapshot); - frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); - } - - private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { - if ("GAMEPLAY_RULE".equals(family)) { - 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", - "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", - "manifestJson", - GameplayRuleManifest.explicitEmpty().canonicalJson(), - "entries", - List.of()))) - .canonicalBytes(); - } - if ("TEMPLATE_CONFIG".equals(family)) { - return new TemplateConfigSourceSnapshot( - selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) - .canonicalBytes(); - } - return SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); - } - private static PublicEvidence publicInventory( WorldSelectedDraftPublicationFreezeEvidence freeze, DraftCommitBinding selected, @@ -466,14 +411,6 @@ private static SourceEvidence source(SourceKind kind, String scope, String marke kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); } - private static void frame(java.io.ByteArrayOutputStream out, String value) { - DraftAuthorizationFenceBinding.frame(out, value); - } - - private static void frame(java.io.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 index 63f6e6ff59..1ec8a8ab1d 100644 --- 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 @@ -1,8 +1,12 @@ package net.firedevops.firemud.common.gamedesign; +import java.io.ByteArrayOutputStream; 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.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; @@ -11,6 +15,8 @@ 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 static final List CONTENT_FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); private SelectedOwnerIntakeSourceTestFixtures() {} @@ -18,6 +24,24 @@ public static byte[] snapshot(String family, DraftCommitBinding selected) { return snapshot(family, selected, 0); } + /** Builds canonical six-family content for a selected-owner intake scope. */ + public static SelectedOwnerIntakeSourceContent content(SelectedOwnerIntakeSourceReadScope scope) { + Objects.requireNonNull(scope, "scope"); + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : CONTENT_FAMILIES) { + byte[] sourceSnapshot = snapshot(family, scope.selected()); + frame(out, family); + frame(out, sourceSnapshot); + frame(out, DraftAuthorizationFenceBinding.digest(sourceSnapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + /** Canonical delete of a synthetic command for otherwise inert selected-source bindings. */ public static String selectedRevisionPayload() { return CommandSource.deletePayload("synthetic-fixture-command"); @@ -81,4 +105,12 @@ private static GameplayRuleSelectedSource gameplay(DraftCommitBinding selected) "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), "entries", List.of()))); } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java index 27402243de..81987e802b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java @@ -68,7 +68,14 @@ public void readSelectedOwnerWorldInventory( var evidence = readService.read(decoded); response = SelectedOwnerWorldInventoryReadGrpcCodec.toResponse(decoded, evidence.inventory()); } catch (StatusRuntimeException failure) { - responseObserver.onError(failure); + Status status = + failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION + ? Status.FAILED_PRECONDITION + : Status.UNAVAILABLE; + fail( + responseObserver, + status, + "Account did not confirm the exact selected-owner World closure read"); return; } catch (SecurityException denied) { fail( diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java new file mode 100644 index 0000000000..961a90529d --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java @@ -0,0 +1,325 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.when; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +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.DraftAuthorizationFenceBinding.SourceKind; +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.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic receiver status tests; they do not establish mTLS or owner-storage proof. */ +class WorldSelectedOwnerInventoryReadGrpcServiceTest { + private static final String NAMESPACE = "firemud"; + private static final String ACCOUNT_FAILURE_DESCRIPTION = + "Account did not confirm the exact selected-owner World closure read"; + + @AfterEach + void clearRequestContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void boundsDownstreamStatusesForBothAuthenticatedOwners() { + var statuses = + List.of( + Status.FAILED_PRECONDITION, + Status.UNAUTHENTICATED, + Status.PERMISSION_DENIED, + Status.DEADLINE_EXCEEDED, + Status.INTERNAL); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var request = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture(owner).request()); + for (Status downstreamStatus : statuses) { + var readService = mock(WorldSelectedOwnerInventoryReadService.class); + var trailers = new Metadata(); + trailers.put( + Metadata.Key.of("x-secret-detail", Metadata.ASCII_STRING_MARSHALLER), + "secret trailer value"); + var downstream = + downstreamStatus + .withDescription("secret downstream detail") + .withCause(new IllegalStateException("secret downstream cause")) + .augmentDescription(" secret suffix") + .asRuntimeException(trailers); + when(readService.read(any())).thenThrow(downstream); + var receiver = new WorldSelectedOwnerInventoryReadGrpcService(NAMESPACE, readService); + var observer = new RecordingObserver(); + + withPeer( + peer(NAMESPACE, serviceName(owner)), + () -> receiver.readSelectedOwnerWorldInventory(request, observer)); + + Status mapped = Status.fromThrowable(observer.error); + assertThat(mapped.getCode()) + .isEqualTo( + downstreamStatus.getCode() == Status.Code.FAILED_PRECONDITION + ? Status.Code.FAILED_PRECONDITION + : Status.Code.UNAVAILABLE); + assertThat(mapped.getDescription()).isEqualTo(ACCOUNT_FAILURE_DESCRIPTION); + assertThat(mapped.getCause()).isNull(); + assertThat(((StatusRuntimeException) observer.error).getTrailers()).isNull(); + assertThat(observer.error).isNotSameAs(downstream); + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + } + } + } + + private static Fixture fixture(Owner owner) { + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID version = id("22222222-2222-4222-8222-222222222222"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + var selected = + DraftCommitBinding.create( + new TargetProof(tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("synthetic-fixture-command"))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + version.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + id("55555555-5555-4555-8555-555555555555"), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + actor, + selected); + var sourceContent = sourceContent(scope); + var binding = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent, + List.of( + source(SourceKind.TENANT, tenant.toString(), "tenant"), + source(SourceKind.ACCOUNT, actor.toString(), "account"), + source(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "9", + "source-intake test", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var publicationBinding = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1}))); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + tenant, + version, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + publicationBinding); + var acknowledgement = + new Acknowledgement( + freezeRequest, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 3); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + return new Fixture( + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, binding, freezeEvidence)); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = sourceSnapshot(family, scope.selected()); + DraftAuthorizationFenceBinding.frame(out, family); + DraftAuthorizationFenceBinding.frame(out, snapshot); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + return switch (family) { + case "COMMAND" -> + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest( + "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + 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()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "TEMPLATE_CONFIG" -> + new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); + }; + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static String serviceName(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private record Fixture(SelectedOwnerWorldInventoryReadEvidence.Request request) {} + + private static final class RecordingObserver + implements StreamObserver { + private ReadSelectedOwnerWorldInventoryResponse response; + private Throwable error; + private boolean completed; + + @Override + public void onNext(ReadSelectedOwnerWorldInventoryResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 9d93aa9c6fdb2a97519efbc416c2d2f2e384c658 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:37:00 +1300 Subject: [PATCH 15/27] Document original throwable retention in transport test collector --- .../WorldSelectedOwnerInventoryReadGrpcServiceTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java index 961a90529d..54b41d10e8 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Context; import io.grpc.Metadata; import io.grpc.Status; @@ -313,6 +314,10 @@ public void onNext(ReadSelectedOwnerWorldInventoryResponse value) { } @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The test collector retains the original throwable for identity and status assertions.") public void onError(Throwable failure) { error = failure; } From 9c249d4c90eb034d49df0bca41b3e52f33bcca16 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:38:35 +1300 Subject: [PATCH 16/27] Record completed CLI capture persistence gap and bounded recovery --- 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 f7b7bf67e7..1f8daadf44 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -235,3 +235,9 @@ Entry format: - Context: A parent-carry helper again ran a scoped `git diff --cached --check` under an explicit validation allowance of NONE, repeating the [2026-10-17: A validation allowance of NONE includes whitespace checks](#ai-observations) finding. - Observation: The check exited zero and grants no proof credit. Main corrected the contradictory no-validation claim and retained ownership of the named integration gate. - Expected pattern: Honor NONE as excluding every check, including scoped Git whitespace checks. If a check runs anyway, report it accurately, give it no proof credit, and retain the orchestrator's ownership of the named integration gate. + +- `2026-10-19`: Preserve completed CLI evidence when review-record saving fails + - Context: #3248's CLI review `run.42bffcfb0b4c4402b50518add5f4ca48` completed with two findings after 212 seconds under the installed Controller runtime. + - Observation: The wrapper returned success but warned only that the SQLite review record was not saved. The durable capture contained the result while the canonical attempt remained started, so provider completion did not establish recorded review credit. The warning hid the underlying exception and referred to a recovery heading that was absent from the lifecycle guide; the existing migration command was broader than the required one-capture recovery. + - Expected pattern: Preserve the immutable capture and original attempt identity, report the recording gap, and use an explicitly bounded canonical recovery before adjudication and finalization. Do not rerun a completed review, invent credit, or use an unrelated schema migration to repair its record. + - Status and reconsideration: Overseer owns bounded recovery in #3271; no live recovery or migration is authorized yet. The exact persistence cause remains unconfirmed. Revisit after that maintenance change is qualified and promoted and the original capture is recovered through its exact native command. From a95429e2ddd82fa8532cc90a5baa848055771bf6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 03:21:08 +1300 Subject: [PATCH 17/27] Normalize selected-owner dependency errors and reject malformed empty receipts --- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 2 +- ...lectedOwnerIntakeAuthorizationService.java | 15 +++- ...tSelectedOwnerIntakeSettlementService.java | 18 ++++- ...edOwnerIntakeAuthorizationServiceTest.java | 70 +++++++++++++++++++ ...ectedOwnerIntakeSettlementServiceTest.java | 61 ++++++++++++++++ ...ationEmptySelectedSourceIntakeReceipt.java | 18 ++--- .../SelectedOwnerEmptySourceInputsTest.java | 51 ++++++++++++++ 8 files changed, 223 insertions(+), 14 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 7a3272721b..468dbf0372 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 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. +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) provides preliminary selected-owner reservation and source-writer storage; forward V1008–V1010 prepare finalized owner authorization/recovery and exact terminal settlement, with focused owner-storage and upgrade proof. Authenticated cross-owner composition, full-native qualification and registration remain open as recorded in the [selected-recipient tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 49248a84b8..29d6d34725 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -68,7 +68,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. 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 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. Forward V1008–V1010 prepare finalized owner authorization/recovery and exact terminal settlement, with focused owner-storage and upgrade proof; authenticated cross-owner composition, full qualification and registration remain open as recorded in the [selected-recipient intake tracker](#selected-recipient-source-intake-preparation). AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java index 463201b390..537f734693 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.service.session; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.Optional; @@ -111,7 +112,19 @@ public SelectedOwnerIntakeAuthorizationBinding authorizeWithEnvironmentCapture( outsideSql(); // The authenticated Game Design client enforces exact request echo, wire closure, six-family // content integrity and the absence of SQL or transaction synchronization during this call. - var received = sources.read(request); + final SelectedOwnerIntakeSourceContent received; + try { + received = sources.read(request); + } catch (StatusRuntimeException failure) { + if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { + throw Status.FAILED_PRECONDITION + .withDescription("Game Design selected-owner source content is unavailable") + .asRuntimeException(); + } + throw Status.UNAVAILABLE + .withDescription("Game Design selected-owner source content is unavailable") + .asRuntimeException(); + } var content = requireExactContent(request, received); var finalizationEnvironment = requireEnvironment(environmentCapture.get()); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java index deaabc463f..baee6a50ec 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java @@ -119,7 +119,14 @@ public AccountSelectedOwnerIntakeSettlementReceipt settle( try { remote = automationClient.read(request); } catch (StatusRuntimeException failure) { - throw failure; + if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { + throw Status.FAILED_PRECONDITION + .withDescription("Automation terminal evidence is not committed") + .asRuntimeException(); + } + throw Status.UNAVAILABLE + .withDescription("Automation terminal evidence is unavailable") + .asRuntimeException(); } catch (RuntimeException unavailable) { throw Status.UNAVAILABLE .withDescription("Automation terminal evidence is unavailable") @@ -166,7 +173,14 @@ private AccountSelectedOwnerIntakeSettlementReceipt settleEntity( try { remote = entityClient.read(request); } catch (StatusRuntimeException failure) { - throw failure; + if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { + throw Status.FAILED_PRECONDITION + .withDescription("Entity terminal evidence is not committed") + .asRuntimeException(); + } + throw Status.UNAVAILABLE + .withDescription("Entity terminal evidence is unavailable") + .asRuntimeException(); } catch (RuntimeException unavailable) { throw Status.UNAVAILABLE .withDescription("Entity terminal evidence is unavailable") diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java index b1f8d51584..9c3b3630bb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java @@ -14,6 +14,7 @@ import static org.mockito.Mockito.when; import io.grpc.Context; +import io.grpc.Metadata; import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.io.ByteArrayOutputStream; @@ -426,6 +427,75 @@ void unavailableRemoteResponseLeavesTheOriginalPreliminaryReservationHeld() { verify(repository, never()).abortSourceRead(any()); } + @Test + void downstreamSourceStatusesAreSanitizedAndKeepThePreliminaryReservationHeld() { + for (Status.Code downstreamCode : + List.of( + Status.Code.PERMISSION_DENIED, + Status.Code.UNAUTHENTICATED, + Status.Code.INTERNAL, + Status.Code.DEADLINE_EXCEEDED, + Status.Code.RESOURCE_EXHAUSTED, + Status.Code.FAILED_PRECONDITION)) { + org.mockito.Mockito.reset(actors, fences, repository, sources, transactions); + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var current = current(ACTOR, TENANT); + var environment = mock(CapturedEnvironmentBoundary.class); + stubFreshReservation(selected, scope, current); + Metadata poisonTrailers = new Metadata(); + poisonTrailers.put( + Metadata.Key.of("x-downstream-poison", Metadata.ASCII_STRING_MARSHALLER), "private"); + StatusRuntimeException poisoned = + Status.fromCode(downstreamCode) + .withDescription("downstream secret detail") + .withCause(new IllegalStateException("downstream secret cause")) + .asRuntimeException(poisonTrailers); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenThrow(poisoned); + + Status.Code expectedCode = + downstreamCode == Status.Code.FAILED_PRECONDITION + ? Status.Code.FAILED_PRECONDITION + : Status.Code.UNAVAILABLE; + assertThatThrownBy( + () -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> environment))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + StatusRuntimeException statusFailure = (StatusRuntimeException) failure; + assertThat(statusFailure.getStatus().getCode()).isEqualTo(expectedCode); + assertThat(statusFailure.getStatus().getDescription()) + .isEqualTo("Game Design selected-owner source content is unavailable"); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + }); + + verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class)); + verify(repository).recoverSourceRead(scope); + verify(sources).read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class)); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + verify(repository, never()).abortSourceRead(any()); + } + } + @Test void exactGameDesignPeerAndNoEndUserContextAreCheckedBeforeInputOrStorage() { assertCode( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java index 43f0ea7d0d..4b14e82dff 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java @@ -11,7 +11,9 @@ import static org.mockito.Mockito.when; import io.grpc.Context; +import io.grpc.Metadata; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.util.ArrayList; @@ -491,6 +493,65 @@ void unavailableOrChangedEntityReadNeverCreatesAccountSettlement() { verify(unavailable.repository, never()).settleEntityCommittedEmpty(any()); } + @Test + void downstreamStatusFailuresAreSanitizedForBothSelectedOwners() { + List downstreamCodes = + List.of( + Status.Code.PERMISSION_DENIED, + Status.Code.UNAUTHENTICATED, + Status.Code.INTERNAL, + Status.Code.DEADLINE_EXCEEDED, + Status.Code.RESOURCE_EXHAUSTED, + Status.Code.FAILED_PRECONDITION); + for (Owner owner : List.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT)) { + for (Status.Code downstreamCode : downstreamCodes) { + SelectedOwnerIntakeAuthorizationBinding binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(owner); + Harness harness = new Harness(NAMESPACE, owner == Owner.ENTITY_MANAGEMENT); + when(harness.repository.findSettlement(binding)).thenReturn(Optional.empty()); + Metadata poisonTrailers = new Metadata(); + poisonTrailers.put( + Metadata.Key.of("x-downstream-poison", Metadata.ASCII_STRING_MARSHALLER), "private"); + StatusRuntimeException poisoned = + Status.fromCode(downstreamCode) + .withDescription("downstream secret detail") + .withCause(new IllegalStateException("downstream secret cause")) + .asRuntimeException(poisonTrailers); + if (owner == Owner.AUTOMATION_SCRIPTING) { + when(harness.automationClient.read(any())).thenThrow(poisoned); + } else { + when(harness.entityClient.read(any())).thenThrow(poisoned); + } + + Status.Code expectedCode = + downstreamCode == Status.Code.FAILED_PRECONDITION + ? Status.Code.FAILED_PRECONDITION + : Status.Code.UNAVAILABLE; + String expectedDescription = + owner == Owner.AUTOMATION_SCRIPTING + ? downstreamCode == Status.Code.FAILED_PRECONDITION + ? "Automation terminal evidence is not committed" + : "Automation terminal evidence is unavailable" + : downstreamCode == Status.Code.FAILED_PRECONDITION + ? "Entity terminal evidence is not committed" + : "Entity terminal evidence is unavailable"; + assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + StatusRuntimeException statusFailure = (StatusRuntimeException) failure; + assertThat(statusFailure.getStatus().getCode()).isEqualTo(expectedCode); + assertThat(statusFailure.getStatus().getDescription()) + .isEqualTo(expectedDescription); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + }); + verify(harness.repository, never()).settleCommittedEmpty(any()); + verify(harness.repository, never()).settleEntityCommittedEmpty(any()); + } + } + } + private static EntityEmptySelectedSourceIntakeReceipt entityReceipt( SelectedOwnerIntakeAuthorizationBinding binding) { var receipt = Mockito.mock(EntityEmptySelectedSourceIntakeReceipt.class); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java index e36fac3be8..b321d3418f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java @@ -156,14 +156,6 @@ private AutomationEmptySelectedSourceIntakeReceipt( this.selectedScopePatchBaseBindingsRowCount = nonnegative( selectedScopePatchBaseBindingsRowCount, "selectedScopePatchBaseBindingsRowCount"); - if (Math.addExact(unqualifiedScriptsRowCount, emptyAssociatedScriptsRowCount) != scriptsRowCount - || Math.addExact(unqualifiedEventBindingsRowCount, emptyAssociatedEventBindingsRowCount) - != eventBindingsRowCount - || Math.addExact( - unqualifiedPatchBaseBindingsRowCount, emptyAssociatedPatchBaseBindingsRowCount) - != patchBaseBindingsRowCount) { - throw new IllegalArgumentException("Automation source census partitions do not add up"); - } if (unqualifiedScriptsRowCount != 0L || unqualifiedEventBindingsRowCount != 0L || unqualifiedPatchBaseBindingsRowCount != 0L @@ -176,6 +168,14 @@ private AutomationEmptySelectedSourceIntakeReceipt( throw new IllegalArgumentException( "Fresh empty Automation intake requires a zero unqualified and selected-scope census"); } + if (Math.addExact(unqualifiedScriptsRowCount, emptyAssociatedScriptsRowCount) != scriptsRowCount + || Math.addExact(unqualifiedEventBindingsRowCount, emptyAssociatedEventBindingsRowCount) + != eventBindingsRowCount + || Math.addExact( + unqualifiedPatchBaseBindingsRowCount, emptyAssociatedPatchBaseBindingsRowCount) + != patchBaseBindingsRowCount) { + throw new IllegalArgumentException("Automation source census partitions do not add up"); + } this.retainedAt = Objects.requireNonNull(retainedAt, "retainedAt"); if (retainedAt.getOffset().getTotalSeconds() != 0) { throw new IllegalArgumentException("Receipt timestamp must use UTC"); @@ -532,7 +532,7 @@ private void requireAuthorizationIdentity() { "Automation receipt differs from its original Account binding"); } var declaration = - new SelectedOwnerEmptySourceInputs(authorizationBinding, decodeWorldEvidence()) + new SelectedOwnerEmptySourceInputs(authorizationBinding, worldInventoryReadEvidence) .ownerSourceInventoryDeclaration(); if (declaration.owner() != Owner.AUTOMATION_SCRIPTING || !declaration.revisionId().equals(sourceRevisionId) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java index bb486bd891..04d5a3f65a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java @@ -4,7 +4,9 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.ByteString; +import java.io.ByteArrayOutputStream; import java.math.BigInteger; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.util.ArrayList; @@ -183,6 +185,55 @@ void automationTerminalReadEchoesExactBindingAndRequiresCommittedEmptyReceipt() .isInstanceOf(IllegalArgumentException.class); } + @Test + void rejectsOverflowingCanonicalEmptyCensusThroughStoredReceiptBoundary() { + Fixture fixture = fixture(Owner.AUTOMATION_SCRIPTING, Options.defaults()); + var binding = fixture.authorization(); + var receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + new SelectedOwnerEmptySourceInputs(binding, fixture.worldInventoryReadEvidence()), + 9001L, + 9002L, + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + "test", binding, fixture.worldInventoryReadEvidence().request().freezeEvidence()), + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + OffsetDateTime.parse("2026-10-10T00:00:00Z")); + byte[] malformed = receipt.canonicalBytes(); + malformed = replaceFrame(malformed, 24, Long.toString(Long.MAX_VALUE)); + malformed = replaceFrame(malformed, 27, "1"); + byte[] storedMalformed = malformed; + + assertThatThrownBy(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(storedMalformed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("zero unqualified and selected-scope census"); + } + + private static byte[] replaceFrame(byte[] encoded, int frameIndex, String replacement) { + byte[] replacementBytes = replacement.getBytes(StandardCharsets.UTF_8); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ByteBuffer input = ByteBuffer.wrap(encoded); + for (int index = 0; input.hasRemaining(); index++) { + int length = input.getInt(); + byte[] value = new byte[length]; + input.get(value); + byte[] frameValue = index == frameIndex ? replacementBytes : value; + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(frameValue.length).array()); + output.writeBytes(frameValue); + } + return output.toByteArray(); + } + @Test void retainsTheExactEmptyInputsAndOriginalDeclarationForBothOwners() { for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { From b83b37f6507f3453fd8a13cdc8e8ca7ef868e219 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 04:39:12 +1300 Subject: [PATCH 18/27] Reuse canonical binding identity in settlement requests --- ...SelectedOwnerIntakeSettlementEvidence.java | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java index a7835eb75a..e5b1ea0e00 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java @@ -43,17 +43,6 @@ public record Request( || transportRequestId.equals(authorizationBinding.intakeRequestId())) { throw invalid("Independent settlement transport correlation required"); } - byte[] bytes = authorizationBinding.canonicalBytes(); - if (bytes.length == 0 - || bytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES - || !DraftAuthorizationFenceBinding.digest(bytes).equals(authorizationBinding.digest())) { - throw invalid("Canonical original authorization is required"); - } - var decoded = SelectedOwnerIntakeAuthorizationBinding.fromStored(bytes); - if (!Arrays.equals(bytes, decoded.canonicalBytes()) - || !authorizationBinding.digest().equals(decoded.digest())) { - throw invalid("Canonical original authorization is required"); - } } public static Request create( @@ -82,16 +71,12 @@ public boolean equals(Object value) { && schemaVersion == other.schemaVersion && targetNamespace.equals(other.targetNamespace) && transportRequestId.equals(other.transportRequestId) - && Arrays.equals(authorizationBindingBytes(), other.authorizationBindingBytes()); + && authorizationBinding.equals(other.authorizationBinding); } @Override public int hashCode() { - return Objects.hash( - schemaVersion, - targetNamespace, - transportRequestId, - Arrays.hashCode(authorizationBindingBytes())); + return Objects.hash(schemaVersion, targetNamespace, transportRequestId, authorizationBinding); } } From 19907273a7509fbc6d59ea4b4aada9188364f045 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 05:52:12 +1300 Subject: [PATCH 19/27] Preserve terminal settlement status codes without downstream details --- ...tSelectedOwnerIntakeSettlementService.java | 12 ++++ ...ectedOwnerIntakeSettlementServiceTest.java | 68 ++++++++++++------- 2 files changed, 56 insertions(+), 24 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java index baee6a50ec..cac71e9fb5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java @@ -124,6 +124,12 @@ public AccountSelectedOwnerIntakeSettlementReceipt settle( .withDescription("Automation terminal evidence is not committed") .asRuntimeException(); } + Status.Code code = failure.getStatus().getCode(); + if (code == Status.Code.NOT_FOUND + || code == Status.Code.ALREADY_EXISTS + || code == Status.Code.DATA_LOSS) { + throw Status.fromCode(code).asRuntimeException(); + } throw Status.UNAVAILABLE .withDescription("Automation terminal evidence is unavailable") .asRuntimeException(); @@ -178,6 +184,12 @@ private AccountSelectedOwnerIntakeSettlementReceipt settleEntity( .withDescription("Entity terminal evidence is not committed") .asRuntimeException(); } + Status.Code code = failure.getStatus().getCode(); + if (code == Status.Code.NOT_FOUND + || code == Status.Code.ALREADY_EXISTS + || code == Status.Code.DATA_LOSS) { + throw Status.fromCode(code).asRuntimeException(); + } throw Status.UNAVAILABLE .withDescription("Entity terminal evidence is unavailable") .asRuntimeException(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java index 4b14e82dff..82d8cdab2b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java @@ -494,14 +494,18 @@ void unavailableOrChangedEntityReadNeverCreatesAccountSettlement() { } @Test - void downstreamStatusFailuresAreSanitizedForBothSelectedOwners() { + void downstreamStatusFailuresPreserveTerminalStatusesAndSanitizeOthersForBothOwners() { List downstreamCodes = List.of( + Status.Code.NOT_FOUND, + Status.Code.ALREADY_EXISTS, + Status.Code.DATA_LOSS, Status.Code.PERMISSION_DENIED, Status.Code.UNAUTHENTICATED, Status.Code.INTERNAL, Status.Code.DEADLINE_EXCEEDED, Status.Code.RESOURCE_EXHAUSTED, + Status.Code.UNAVAILABLE, Status.Code.FAILED_PRECONDITION); for (Owner owner : List.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT)) { for (Status.Code downstreamCode : downstreamCodes) { @@ -523,31 +527,47 @@ void downstreamStatusFailuresAreSanitizedForBothSelectedOwners() { when(harness.entityClient.read(any())).thenThrow(poisoned); } - Status.Code expectedCode = - downstreamCode == Status.Code.FAILED_PRECONDITION - ? Status.Code.FAILED_PRECONDITION - : Status.Code.UNAVAILABLE; - String expectedDescription = - owner == Owner.AUTOMATION_SCRIPTING - ? downstreamCode == Status.Code.FAILED_PRECONDITION - ? "Automation terminal evidence is not committed" - : "Automation terminal evidence is unavailable" - : downstreamCode == Status.Code.FAILED_PRECONDITION - ? "Entity terminal evidence is not committed" - : "Entity terminal evidence is unavailable"; - assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(binding))) - .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - StatusRuntimeException statusFailure = (StatusRuntimeException) failure; - assertThat(statusFailure.getStatus().getCode()).isEqualTo(expectedCode); - assertThat(statusFailure.getStatus().getDescription()) - .isEqualTo(expectedDescription); - assertThat(statusFailure.getCause()).isNull(); - assertThat(statusFailure.getTrailers()).isNull(); - }); + if (downstreamCode == Status.Code.NOT_FOUND + || downstreamCode == Status.Code.ALREADY_EXISTS + || downstreamCode == Status.Code.DATA_LOSS) { + assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + StatusRuntimeException statusFailure = (StatusRuntimeException) failure; + assertThat(statusFailure.getStatus().getCode()).isEqualTo(downstreamCode); + assertThat(statusFailure.getStatus().getDescription()).isNull(); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + }); + } else { + Status.Code expectedCode = + downstreamCode == Status.Code.FAILED_PRECONDITION + ? Status.Code.FAILED_PRECONDITION + : Status.Code.UNAVAILABLE; + String expectedDescription = + owner == Owner.AUTOMATION_SCRIPTING + ? downstreamCode == Status.Code.FAILED_PRECONDITION + ? "Automation terminal evidence is not committed" + : "Automation terminal evidence is unavailable" + : downstreamCode == Status.Code.FAILED_PRECONDITION + ? "Entity terminal evidence is not committed" + : "Entity terminal evidence is unavailable"; + assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + StatusRuntimeException statusFailure = (StatusRuntimeException) failure; + assertThat(statusFailure.getStatus().getCode()).isEqualTo(expectedCode); + assertThat(statusFailure.getStatus().getDescription()) + .isEqualTo(expectedDescription); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + }); + } verify(harness.repository, never()).settleCommittedEmpty(any()); verify(harness.repository, never()).settleEntityCommittedEmpty(any()); + verify(harness.repository, times(1)).findSettlement(binding); } } } From 46cee89794d09249c08e8967fadf1451fbda0717 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 08:12:33 +1300 Subject: [PATCH 20/27] refactor: consolidate selected-owner settlement and inventory fixtures --- .../account-service/runtime-and-data.md | 2 +- ...wnerIntakeSourceReservationRepository.java | 60 ++--- ...ctedOwnerInventoryReadGrpcServiceTest.java | 205 +---------------- ...SelectedOwnerInventoryReadServiceTest.java | 212 +---------------- ...rldSelectedOwnerInventoryTestFixtures.java | 217 ++++++++++++++++++ 5 files changed, 245 insertions(+), 451 deletions(-) create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 468dbf0372..2738a109b0 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 intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. The preceding source-disclosure upgrade and composition pass focused PostgreSQL proof; full-native qualification remains held on inherited PostgreSQL/Redis failures. Focused PostgreSQL upgrade and owner-storage proof for authorization and terminal settlement passes; authenticated cross-owner composition and full-native qualification remain limited as recorded in the tracker. These components remain unregistered and unqualified; 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 intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. These components remain unregistered and unqualified; the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof, qualification limits 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/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 index ec50e5e71b..00f57bc7ca 100644 --- 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 @@ -10,6 +10,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; @@ -369,41 +370,11 @@ AccountSelectedOwnerIntakeSettlementReceipt settleCommittedEmpty( || !"COMMITTED_EMPTY".equals(evidence.receipt().outcome())) { throw new IllegalArgumentException("Exact Automation COMMITTED_EMPTY evidence required"); } - SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); - lockReservedSources(scope); - requireReservation(reservation(scope), scope); - Record order = authorization(requested.operationId()); - requireAuthorization(order, requested); - if (aborted(scope)) - throw new IllegalArgumentException("Finalized owner authorization was aborted"); - - Record prior = settlement(requested.operationId()); - if (prior != null) return exactSettlement(prior, requested, evidence); - - AccountSelectedOwnerIntakeSettlementReceipt receipt = - AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); - dsl.execute( - "INSERT INTO " - + SETTLEMENTS - + " (operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " - + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " - + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - receipt.operationId(), - requested.fenceId(), - requested.intakeRequestId(), - requested.owner().name(), - requested.targetNamespace(), - requested.tenantId(), - requested.versionId(), - requested.canonicalBytes(), - requested.digest(), + return settleCommittedEmpty( + requested, evidence.request().readRequestId(), - receipt.ownerReceiptBytes(), - receipt.ownerReceiptDigest(), - receipt.canonicalBytes(), - receipt.digest()); - return exactSettlement(settlement(requested.operationId()), requested, evidence); + () -> AccountSelectedOwnerIntakeSettlementReceipt.create(evidence), + evidence); } AccountSelectedOwnerIntakeSettlementReceipt settleEntityCommittedEmpty( @@ -415,6 +386,18 @@ AccountSelectedOwnerIntakeSettlementReceipt settleEntityCommittedEmpty( || !"COMMITTED_EMPTY".equals(evidence.receipt().outcome())) { throw new IllegalArgumentException("Exact Entity COMMITTED_EMPTY evidence required"); } + return settleCommittedEmpty( + requested, + evidence.request().readRequestId(), + () -> AccountSelectedOwnerIntakeSettlementReceipt.create(evidence), + evidence); + } + + private AccountSelectedOwnerIntakeSettlementReceipt settleCommittedEmpty( + SelectedOwnerIntakeAuthorizationBinding requested, + UUID readRequestId, + Supplier receiptFactory, + Object retryEvidence) { SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); lockReservedSources(scope); requireReservation(reservation(scope), scope); @@ -424,10 +407,9 @@ AccountSelectedOwnerIntakeSettlementReceipt settleEntityCommittedEmpty( throw new IllegalArgumentException("Finalized owner authorization was aborted"); Record prior = settlement(requested.operationId()); - if (prior != null) return exactSettlement(prior, requested, evidence); + if (prior != null) return exactSettlement(prior, requested, retryEvidence); - AccountSelectedOwnerIntakeSettlementReceipt receipt = - AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + AccountSelectedOwnerIntakeSettlementReceipt receipt = receiptFactory.get(); dsl.execute( "INSERT INTO " + SETTLEMENTS @@ -444,12 +426,12 @@ AccountSelectedOwnerIntakeSettlementReceipt settleEntityCommittedEmpty( requested.versionId(), requested.canonicalBytes(), requested.digest(), - evidence.request().readRequestId(), + readRequestId, receipt.ownerReceiptBytes(), receipt.ownerReceiptDigest(), receipt.canonicalBytes(), receipt.digest()); - return exactSettlement(settlement(requested.operationId()), requested, evidence); + return exactSettlement(settlement(requested.operationId()), requested, retryEvidence); } private AccountSelectedOwnerIntakeSettlementReceipt exactSettlement( diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java index 54b41d10e8..9abf0c9969 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java @@ -11,41 +11,10 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; import java.util.List; -import java.util.Map; -import java.util.UUID; -import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; -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.DraftAuthorizationFenceBinding.SourceKind; -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.AssetSnapshot; -import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSource; -import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; -import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; -import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; import org.junit.jupiter.api.AfterEach; @@ -74,7 +43,9 @@ void boundsDownstreamStatusesForBothAuthenticatedOwners() { Status.DEADLINE_EXCEEDED, Status.INTERNAL); for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { - var request = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture(owner).request()); + var request = + SelectedOwnerWorldInventoryReadGrpcCodec.toRequest( + WorldSelectedOwnerInventoryTestFixtures.fixture(owner).request()); for (Status downstreamStatus : statuses) { var readService = mock(WorldSelectedOwnerInventoryReadService.class); var trailers = new Metadata(); @@ -111,180 +82,12 @@ void boundsDownstreamStatusesForBothAuthenticatedOwners() { } } - private static Fixture fixture(Owner owner) { - UUID tenant = id("11111111-1111-4111-8111-111111111111"); - UUID version = id("22222222-2222-4222-8222-222222222222"); - UUID actor = id("99999999-9999-4999-8999-999999999999"); - var selected = - DraftCommitBinding.create( - new TargetProof(tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), - id("33333333-3333-4333-8333-333333333333"), - id("44444444-4444-4444-8444-444444444444"), - "base-commit-0", - List.of( - new RevisionPayload( - "0", - id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), - Owner.GAME_DESIGN_CONTROL_PLANE, - CommandSource.deletePayload("synthetic-fixture-command"))), - List.of( - new DraftCommitBinding.AffectedUnit( - Owner.GAME_DESIGN_CONTROL_PLANE, - "TEMPLATE_CONFIG", - version.toString(), - "TEMPLATE_CONFIG", - "ALL", - "0"))); - var scope = - new SelectedOwnerIntakeSourceReadScope( - owner, - NAMESPACE, - id("55555555-5555-4555-8555-555555555555"), - id("66666666-6666-4666-8666-666666666666"), - id("77777777-7777-4777-8777-777777777777"), - actor, - selected); - var sourceContent = sourceContent(scope); - var binding = - new SelectedOwnerIntakeAuthorizationBinding( - sourceContent, - List.of( - source(SourceKind.TENANT, tenant.toString(), "tenant"), - source(SourceKind.ACCOUNT, actor.toString(), "account"), - source(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership"))); - var selection = - AuthoredDraftPublishSelectionBinding.capture( - new PublishIntent( - tenant, - version, - "publication-request", - "9", - "source-intake test", - selected.requestId(), - selected.commitId(), - selected.digest()), - selected.target(), - selected, - new VisibilityFence( - selected.target(), - selected.requestId(), - selected.commitId(), - selected.digest(), - "[]", - OffsetDateTime.parse("2026-10-01T00:00:00Z"))); - var publicationBinding = - new AccountPublicationAuthorizationBinding( - id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), - id("ffffffff-ffff-4fff-8fff-ffffffffffff"), - new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), - List.of( - new SourceEvidence( - SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1}))); - var freezeRequest = - WorldSelectedDraftPublicationFreezeEvidence.Request.create( - NAMESPACE, - tenant, - version, - selection.intent().publishRequestId(), - 9, - selection.digest().substring("sha256:".length()), - publicationBinding); - var acknowledgement = - new Acknowledgement( - freezeRequest, - id("12121212-1212-4212-8212-121212121212"), - 9, - id("13131313-1313-4313-8313-131313131313"), - OwnerFreezePhase.FROZEN, - selected.commitId().toString(), - "a".repeat(64), - 3); - var freezeEvidence = - WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( - freezeRequest, - WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); - return new Fixture( - SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, binding, freezeEvidence)); - } - - private static SelectedOwnerIntakeSourceContent sourceContent( - SelectedOwnerIntakeSourceReadScope scope) { - var out = new ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); - DraftAuthorizationFenceBinding.frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = sourceSnapshot(family, scope.selected()); - DraftAuthorizationFenceBinding.frame(out, family); - DraftAuthorizationFenceBinding.frame(out, snapshot); - DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); - } - - private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { - UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - return switch (family) { - case "COMMAND" -> - new CommandSnapshot( - selected, - "0", - null, - DraftAuthorizationFenceBinding.digest( - "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), - List.of()) - .canonicalBytes(); - case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); - case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); - case "GAMEPLAY_RULE" -> - 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()))) - .canonicalBytes(); - case "BRANDING" -> - new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); - case "TEMPLATE_CONFIG" -> - new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) - .canonicalBytes(); - default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); - }; - } - - private static SourceEvidence source(SourceKind kind, String scope, String marker) { - return new SourceEvidence( - kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); - } - private static String serviceName(Owner owner) { return owner == Owner.ENTITY_MANAGEMENT ? "entity-management-service" : "automation-scripting-service"; } - private static UUID id(String value) { - return UUID.fromString(value); - } - private static GrpcPeerIdentity peer(String namespace, String service) { return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) .orElseThrow(); @@ -300,8 +103,6 @@ private static void withPeer(GrpcPeerIdentity peer, Runnable action) { } } - private record Fixture(SelectedOwnerWorldInventoryReadEvidence.Request request) {} - private static final class RecordingObserver implements StreamObserver { private ReadSelectedOwnerWorldInventoryResponse response; diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java index 5fbdea3f93..dd26cd8f05 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java @@ -13,43 +13,13 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.UUID; -import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; -import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadClient; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; -import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; -import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; -import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.gamedesign.AssetSnapshot; -import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSource; -import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; -import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; -import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; @@ -130,7 +100,7 @@ void authenticatesOwnerWorkloadBeforeParsingAndRequiresIndependentRead() { @Test void accountConfirmationPrecedesTheExactRetainedReadForBothOwners() { for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { - var fixture = fixture(owner); + var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(owner); var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); var retainedInventory = mock(WorldSelectedPublicationArtifactInventoryEvidence.class); @@ -183,7 +153,7 @@ void accountConfirmationPrecedesTheExactRetainedReadForBothOwners() { @Test void absentOrChangedAccountEchoNeverReadsWorldStorage() { for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { - var fixture = fixture(owner); + var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(owner); for (boolean absent : List.of(true, false)) { var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); @@ -219,7 +189,7 @@ void absentOrChangedAccountEchoNeverReadsWorldStorage() { @Test void domainServiceRejectsWrongRecipientEndUserAndAmbientSqlBeforeAccountCall() { for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { - var fixture = fixture(owner); + var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(owner); var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); @@ -256,188 +226,12 @@ void domainServiceRejectsWrongRecipientEndUserAndAmbientSqlBeforeAccountCall() { } } - private static Fixture fixture(Owner owner) { - UUID tenant = id("11111111-1111-4111-8111-111111111111"); - UUID version = id("22222222-2222-4222-8222-222222222222"); - UUID actor = id("99999999-9999-4999-8999-999999999999"); - var selected = - DraftCommitBinding.create( - new TargetProof(tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), - id("33333333-3333-4333-8333-333333333333"), - id("44444444-4444-4444-8444-444444444444"), - "base-commit-0", - List.of( - new RevisionPayload( - "0", - id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), - Owner.GAME_DESIGN_CONTROL_PLANE, - CommandSource.deletePayload("synthetic-fixture-command"))), - List.of( - new DraftCommitBinding.AffectedUnit( - Owner.GAME_DESIGN_CONTROL_PLANE, - "TEMPLATE_CONFIG", - version.toString(), - "TEMPLATE_CONFIG", - "ALL", - "0"))); - var scope = - new SelectedOwnerIntakeSourceReadScope( - owner, - NAMESPACE, - id("55555555-5555-4555-8555-555555555555"), - id("66666666-6666-4666-8666-666666666666"), - id("77777777-7777-4777-8777-777777777777"), - actor, - selected); - var content = sourceContent(scope); - var binding = - new SelectedOwnerIntakeAuthorizationBinding( - content, - List.of( - source(SourceKind.TENANT, tenant.toString(), "tenant"), - source(SourceKind.ACCOUNT, actor.toString(), "account"), - source(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership"))); - - var selection = - AuthoredDraftPublishSelectionBinding.capture( - new PublishIntent( - tenant, - version, - "publication-request", - "9", - "source-intake test", - selected.requestId(), - selected.commitId(), - selected.digest()), - selected.target(), - selected, - new VisibilityFence( - selected.target(), - selected.requestId(), - selected.commitId(), - selected.digest(), - "[]", - OffsetDateTime.parse("2026-10-01T00:00:00Z"))); - var publicationBinding = - new AccountPublicationAuthorizationBinding( - id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), - id("ffffffff-ffff-4fff-8fff-ffffffffffff"), - new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), - List.of( - new SourceEvidence( - SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1}))); - var freezeRequest = - WorldSelectedDraftPublicationFreezeEvidence.Request.create( - NAMESPACE, - tenant, - version, - selection.intent().publishRequestId(), - 9, - selection.digest().substring("sha256:".length()), - publicationBinding); - var acknowledgement = - new Acknowledgement( - freezeRequest, - id("12121212-1212-4212-8212-121212121212"), - 9, - id("13131313-1313-4313-8313-131313131313"), - OwnerFreezePhase.FROZEN, - selected.commitId().toString(), - "a".repeat(64), - 3); - var freezeEvidence = - WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( - freezeRequest, - WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); - return new Fixture( - binding, - freezeEvidence, - SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, binding, freezeEvidence)); - } - - private static SelectedOwnerIntakeSourceContent sourceContent( - SelectedOwnerIntakeSourceReadScope scope) { - var out = new ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); - DraftAuthorizationFenceBinding.frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = sourceSnapshot(family, scope.selected()); - DraftAuthorizationFenceBinding.frame(out, family); - DraftAuthorizationFenceBinding.frame(out, snapshot); - DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); - } - - private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { - UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - return switch (family) { - case "COMMAND" -> - new CommandSnapshot( - selected, - "0", - null, - DraftAuthorizationFenceBinding.digest( - "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), - List.of()) - .canonicalBytes(); - case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); - case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); - case "GAMEPLAY_RULE" -> - 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()))) - .canonicalBytes(); - case "BRANDING" -> - new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); - case "TEMPLATE_CONFIG" -> - new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) - .canonicalBytes(); - default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); - }; - } - - private static SourceEvidence source(SourceKind kind, String scope, String marker) { - return new SourceEvidence( - kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); - } - private static String serviceName(Owner owner) { return owner == Owner.ENTITY_MANAGEMENT ? "entity-management-service" : "automation-scripting-service"; } - private static UUID id(String value) { - return UUID.fromString(value); - } - - private record Fixture( - SelectedOwnerIntakeAuthorizationBinding binding, - WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, - SelectedOwnerWorldInventoryReadEvidence.Request request) {} - private static void assertDenied(RecordingObserver observer, Status.Code code) { assertThat(Status.fromThrowable(observer.error).getCode()).isEqualTo(code); assertThat(observer.response).isNull(); diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java new file mode 100644 index 0000000000..5e0437cf7f --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java @@ -0,0 +1,217 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +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.DraftAuthorizationFenceBinding.SourceKind; +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.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; + +/** Shared synthetic source and freeze evidence for selected-owner World inventory tests. */ +final class WorldSelectedOwnerInventoryTestFixtures { + private static final String NAMESPACE = "firemud"; + + private WorldSelectedOwnerInventoryTestFixtures() {} + + static Fixture fixture(Owner owner) { + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID version = id("22222222-2222-4222-8222-222222222222"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + var selected = + DraftCommitBinding.create( + new TargetProof(tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("synthetic-fixture-command"))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + version.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + id("55555555-5555-4555-8555-555555555555"), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + actor, + selected); + var content = sourceContent(scope); + var binding = + new SelectedOwnerIntakeAuthorizationBinding( + content, + List.of( + source(SourceKind.TENANT, tenant.toString(), "tenant"), + source(SourceKind.ACCOUNT, actor.toString(), "account"), + source(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "9", + "source-intake test", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var publicationBinding = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1}))); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + tenant, + version, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + publicationBinding); + var acknowledgement = + new Acknowledgement( + freezeRequest, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 3); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + return new Fixture( + binding, + freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, binding, freezeEvidence)); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = sourceSnapshot(family, scope.selected()); + DraftAuthorizationFenceBinding.frame(out, family); + DraftAuthorizationFenceBinding.frame(out, snapshot); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + return switch (family) { + case "COMMAND" -> + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest( + "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + 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()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "TEMPLATE_CONFIG" -> + new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); + }; + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + record Fixture( + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence.Request request) {} +} From 5da0ac48a3c196e908b03d48a96bb3f3d71c72ce Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 08:37:16 +1300 Subject: [PATCH 21/27] fix: attribute selected-owner read failures to their source --- ...ected_owner_intake_terminal_settlement.sql | 14 +- ...SelectedOwnerInventoryReadGrpcService.java | 24 +++- ...orldSelectedOwnerInventoryReadService.java | 98 ++++++++++++-- ...ctedOwnerInventoryReadGrpcServiceTest.java | 122 +++++++++++++++++- ...SelectedOwnerInventoryReadServiceTest.java | 10 +- 5 files changed, 240 insertions(+), 28 deletions(-) diff --git a/services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql index ae4f64334f..07f6e22bcc 100644 --- a/services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql +++ b/services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql @@ -1,5 +1,5 @@ -- Add Entity's authenticated closed COMMITTED_EMPTY receipt to the existing immutable family. --- V1008 Automation rows and receipt bytes are retained exactly; no pending predicate changes. +-- V1009 Automation rows and receipt bytes are retained exactly; no pending predicate changes. -- [jooq ignore start] DO $migration$ DECLARE @@ -21,14 +21,14 @@ BEGIN expected_limit := CASE check_row.attname WHEN 'owner' THEN 'AUTOMATION_SCRIPTING' WHEN 'terminal_receipt_bytes' THEN '58736640' ELSE '92356608' END; IF position(expected_limit IN check_row.definition) = 0 THEN - RAISE EXCEPTION 'Unexpected retained V1008 settlement constraint: %', check_row.conname; + RAISE EXCEPTION 'Unexpected retained V1009 settlement constraint: %', check_row.conname; END IF; EXECUTE format('ALTER TABLE account_selected_owner_intake_settlements DROP CONSTRAINT %I', check_row.conname); changed_count := changed_count + 1; END LOOP; IF changed_count <> 3 THEN - RAISE EXCEPTION 'Expected all three retained V1008 settlement constraints'; + RAISE EXCEPTION 'Expected all three retained V1009 settlement constraints'; END IF; END; $migration$; @@ -130,7 +130,7 @@ BEGIN OR NEW.binding_digest IS DISTINCT FROM original.binding_digest OR original.binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(original.binding_bytes), 'hex') THEN - RAISE EXCEPTION 'Settlement must bind one exact active Automation authorization' + RAISE EXCEPTION 'Settlement must bind one exact active selected-owner authorization' USING ERRCODE = '23514'; END IF; @@ -139,7 +139,7 @@ BEGIN SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(original.binding_bytes, p); IF convert_from(parsed, 'UTF8') IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'account-automation-intake-authorization/v1' ELSE 'account-entity-intake-authorization/v1' END) THEN - RAISE EXCEPTION 'Settlement original binding is not Automation authorization' + RAISE EXCEPTION 'Settlement original binding is not selected-owner authorization' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO content_bytes, p @@ -301,7 +301,7 @@ BEGIN IF NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') OR NEW.terminal_receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_receipt_bytes), 'hex') THEN - RAISE EXCEPTION 'Settlement or Automation receipt digest differs' USING ERRCODE = '23514'; + RAISE EXCEPTION 'Settlement or owner terminal receipt digest differs' USING ERRCODE = '23514'; END IF; p := 1; SELECT frame_value, next_position INTO parsed, p @@ -368,7 +368,7 @@ BEGIN IF owner_receipt IS DISTINCT FROM NEW.terminal_receipt_bytes OR marker IS DISTINCT FROM NEW.terminal_receipt_digest OR p <> octet_length(NEW.receipt_bytes) + 1 THEN - RAISE EXCEPTION 'Settlement receipt differs from exact Automation terminal bytes' + RAISE EXCEPTION 'Settlement receipt differs from exact owner terminal bytes' USING ERRCODE = '23514'; END IF; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java index 81987e802b..35742e650a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java @@ -67,6 +67,9 @@ public void readSelectedOwnerWorldInventory( try { var evidence = readService.read(decoded); response = SelectedOwnerWorldInventoryReadGrpcCodec.toResponse(decoded, evidence.inventory()); + } catch (WorldSelectedOwnerInventoryReadService.ReadFailure failure) { + fail(responseObserver, Status.fromCode(failure.statusCode()), failure.description()); + return; } catch (StatusRuntimeException failure) { Status status = failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION @@ -75,13 +78,15 @@ public void readSelectedOwnerWorldInventory( fail( responseObserver, status, - "Account did not confirm the exact selected-owner World closure read"); + status.getCode() == Status.Code.FAILED_PRECONDITION + ? "Exact retained World artifact inventory is unavailable" + : "World selected inventory owner storage is unavailable"); return; } catch (SecurityException denied) { fail( responseObserver, Status.PERMISSION_DENIED, - "Account did not confirm the exact selected-owner World closure read"); + "Exact same-namespace selected-owner workload is required"); return; } catch (WorldDesignPublicationFenceRepository.ConflictException | IllegalArgumentException inconsistent) { @@ -136,11 +141,16 @@ private boolean isExpectedPeer(GrpcPeerIdentity peer, String service) { private boolean peerMatchesOwner(Owner owner) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - String expectedService = - owner == Owner.ENTITY_MANAGEMENT - ? "entity-management-service" - : "automation-scripting-service"; - return peer != null && isExpectedPeer(peer, expectedService); + String expectedService = ownerService(owner); + return expectedService != null && peer != null && isExpectedPeer(peer, expectedService); + } + + private static String ownerService(Owner owner) { + return switch (owner) { + case ENTITY_MANAGEMENT -> "entity-management-service"; + case AUTOMATION_SCRIPTING -> "automation-scripting-service"; + default -> null; + }; } private static void fail(StreamObserver observer, Status status, String description) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java index e3c170b6fa..fbf3e9ee0f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.worldmanagement.tenant; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.util.Arrays; import java.util.Objects; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadClient; @@ -48,22 +50,67 @@ SelectedOwnerWorldInventoryReadEvidence read( SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( trustedNamespace, request.authorizationBinding()); } - var accountEvidence = accountReadClient.readHeld(accountRequest); + final SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence accountEvidence; + try { + accountEvidence = accountReadClient.readHeld(accountRequest); + } catch (StatusRuntimeException failure) { + throw new ReadFailure( + statusFor(failure), + "Account did not confirm the exact selected-owner World closure read"); + } catch (SecurityException denied) { + throw new ReadFailure( + Status.Code.PERMISSION_DENIED, + "Account did not confirm the exact selected-owner World closure read"); + } catch (IllegalArgumentException invalid) { + throw new ReadFailure( + Status.Code.FAILED_PRECONDITION, + "Account did not confirm the exact selected-owner World closure read"); + } catch (RuntimeException unavailable) { + throw new ReadFailure( + Status.Code.UNAVAILABLE, + "Account did not confirm the exact selected-owner World closure read"); + } if (accountEvidence == null || !sameAccountRequest(accountRequest, accountEvidence.request())) { - throw new SecurityException("Account changed the exact World closure authorization read"); + throw new ReadFailure( + Status.Code.PERMISSION_DENIED, + "Account did not confirm the exact selected-owner World closure read"); } - var inventory = inventoryReadService.readRetained(request.freezeEvidence()); - return new SelectedOwnerWorldInventoryReadEvidence(request, inventory); + try { + var inventory = inventoryReadService.readRetained(request.freezeEvidence()); + return new SelectedOwnerWorldInventoryReadEvidence(request, inventory); + } catch (StatusRuntimeException failure) { + Status.Code status = statusFor(failure); + throw new ReadFailure( + status, + status == Status.Code.FAILED_PRECONDITION + ? "Exact retained World artifact inventory is unavailable" + : "World selected inventory owner storage is unavailable"); + } catch (SecurityException denied) { + throw new ReadFailure( + Status.Code.PERMISSION_DENIED, "Exact retained World artifact inventory is unavailable"); + } catch (WorldDesignPublicationFenceRepository.ConflictException + | IllegalArgumentException inconsistent) { + throw new ReadFailure( + Status.Code.FAILED_PRECONDITION, + "Exact retained World artifact inventory is unavailable"); + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + throw new ReadFailure( + Status.Code.UNAVAILABLE, "World selected inventory owner storage is unavailable"); + } catch (RuntimeException unavailable) { + throw new ReadFailure( + Status.Code.UNAVAILABLE, "World selected-owner authorization or inventory read failed"); + } } private void requireAuthenticatedRecipient( SelectedOwnerWorldInventoryReadEvidence.Request request) { var binding = request.authorizationBinding(); - String service = - binding.owner() == Owner.ENTITY_MANAGEMENT - ? "entity-management-service" - : "automation-scripting-service"; + String service = ownerService(binding.owner()); + if (service == null) { + throw new SecurityException("Unsupported selected-owner World inventory recipient"); + } String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/" + service; GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (!expected.equals(binding.intendedReader()) @@ -76,6 +123,41 @@ private void requireAuthenticatedRecipient( } } + private static String ownerService(Owner owner) { + return switch (owner) { + case ENTITY_MANAGEMENT -> "entity-management-service"; + case AUTOMATION_SCRIPTING -> "automation-scripting-service"; + default -> null; + }; + } + + private static Status.Code statusFor(StatusRuntimeException failure) { + return failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION + ? Status.Code.FAILED_PRECONDITION + : Status.Code.UNAVAILABLE; + } + + static final class ReadFailure extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final Status.Code statusCode; + private final String description; + + private ReadFailure(Status.Code statusCode, String description) { + super(description); + this.statusCode = statusCode; + this.description = description; + } + + Status.Code statusCode() { + return statusCode; + } + + String description() { + return description; + } + } + private static boolean sameAccountRequest( SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request expected, SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request actual) { diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java index 9abf0c9969..1d74b3318e 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java @@ -12,6 +12,8 @@ import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import java.util.List; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; @@ -19,6 +21,7 @@ import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Synthetic receiver status tests; they do not establish mTLS or owner-storage proof. */ @@ -43,11 +46,11 @@ void boundsDownstreamStatusesForBothAuthenticatedOwners() { Status.DEADLINE_EXCEEDED, Status.INTERNAL); for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { - var request = - SelectedOwnerWorldInventoryReadGrpcCodec.toRequest( - WorldSelectedOwnerInventoryTestFixtures.fixture(owner).request()); + var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(owner); + var request = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); for (Status downstreamStatus : statuses) { - var readService = mock(WorldSelectedOwnerInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryReadService.class); var trailers = new Metadata(); trailers.put( Metadata.Key.of("x-secret-detail", Metadata.ASCII_STRING_MARSHALLER), @@ -58,7 +61,8 @@ void boundsDownstreamStatusesForBothAuthenticatedOwners() { .withCause(new IllegalStateException("secret downstream cause")) .augmentDescription(" secret suffix") .asRuntimeException(trailers); - when(readService.read(any())).thenThrow(downstream); + when(account.readHeld(any())).thenThrow(downstream); + var readService = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventory, account); var receiver = new WorldSelectedOwnerInventoryReadGrpcService(NAMESPACE, readService); var observer = new RecordingObserver(); @@ -78,10 +82,118 @@ void boundsDownstreamStatusesForBothAuthenticatedOwners() { assertThat(observer.error).isNotSameAs(downstream); assertThat(observer.response).isNull(); assertThat(observer.completed).isFalse(); + org.mockito.Mockito.verifyNoInteractions(inventory); } } } + @Test + void attributesMalformedAccountEvidenceToAccountWithoutLeakingDetails() { + var malformedResponses = + List.of( + new IllegalArgumentException("secret Account codec detail"), + new IllegalStateException( + "Account returned invalid selected-owner World closure HELD evidence", + new IllegalArgumentException("secret Account codec detail"))); + for (RuntimeException malformedResponse : malformedResponses) { + var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(Owner.ENTITY_MANAGEMENT); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + when(account.readHeld(any())).thenThrow(malformedResponse); + var inventory = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var readService = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventory, account); + var receiver = new WorldSelectedOwnerInventoryReadGrpcService(NAMESPACE, readService); + var request = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var observer = new RecordingObserver(); + + withPeer( + peer(NAMESPACE, "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(request, observer)); + + assertSanitizedFailure( + observer, + malformedResponse instanceof IllegalArgumentException + ? Status.Code.FAILED_PRECONDITION + : Status.Code.UNAVAILABLE, + ACCOUNT_FAILURE_DESCRIPTION); + org.mockito.Mockito.verifyNoInteractions(inventory); + } + } + + @Test + void attributesWorldStatusAndStorageFailuresToWorldWithoutLeakingDetails() { + var statuses = List.of(Status.FAILED_PRECONDITION, Status.INTERNAL); + for (Status worldStatus : statuses) { + var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(Owner.ENTITY_MANAGEMENT); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + when(account.readHeld(any())) + .thenAnswer( + invocation -> + new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence( + invocation.getArgument(0))); + var inventory = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var trailers = new Metadata(); + trailers.put( + Metadata.Key.of("x-secret-detail", Metadata.ASCII_STRING_MARSHALLER), + "secret trailer value"); + var downstream = + worldStatus + .withDescription("secret World status detail") + .withCause(new IllegalStateException("secret World status cause")) + .asRuntimeException(trailers); + when(inventory.readRetained(any())).thenThrow(downstream); + var readService = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventory, account); + var receiver = new WorldSelectedOwnerInventoryReadGrpcService(NAMESPACE, readService); + var request = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var observer = new RecordingObserver(); + + withPeer( + peer(NAMESPACE, "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(request, observer)); + + assertSanitizedFailure( + observer, + worldStatus.getCode() == Status.Code.FAILED_PRECONDITION + ? Status.Code.FAILED_PRECONDITION + : Status.Code.UNAVAILABLE, + worldStatus.getCode() == Status.Code.FAILED_PRECONDITION + ? "Exact retained World artifact inventory is unavailable" + : "World selected inventory owner storage is unavailable"); + } + + var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(Owner.ENTITY_MANAGEMENT); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + when(account.readHeld(any())) + .thenAnswer( + invocation -> + new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence( + invocation.getArgument(0))); + var inventory = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + when(inventory.readRetained(any())) + .thenThrow(new DataAccessResourceFailureException("secret World storage detail")); + var readService = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventory, account); + var receiver = new WorldSelectedOwnerInventoryReadGrpcService(NAMESPACE, readService); + var request = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var observer = new RecordingObserver(); + + withPeer( + peer(NAMESPACE, "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(request, observer)); + + assertSanitizedFailure( + observer, Status.Code.UNAVAILABLE, "World selected inventory owner storage is unavailable"); + } + + private static void assertSanitizedFailure( + RecordingObserver observer, Status.Code expectedCode, String expectedDescription) { + Status mapped = Status.fromThrowable(observer.error); + assertThat(mapped.getCode()).isEqualTo(expectedCode); + assertThat(mapped.getDescription()).isEqualTo(expectedDescription); + assertThat(mapped.getCause()).isNull(); + assertThat(((StatusRuntimeException) observer.error).getTrailers()).isNull(); + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + } + private static String serviceName(Owner owner) { return owner == Owner.ENTITY_MANAGEMENT ? "entity-management-service" diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java index dd26cd8f05..947877a200 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java @@ -180,7 +180,15 @@ void absentOrChangedAccountEchoNeverReadsWorldStorage() { () -> withPeer( peer(NAMESPACE, serviceName(owner)), () -> service.read(fixture.request()))) - .isInstanceOf(SecurityException.class); + .isInstanceOfSatisfying( + WorldSelectedOwnerInventoryReadService.ReadFailure.class, + failure -> { + assertThat(failure.statusCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(failure.description()) + .isEqualTo( + "Account did not confirm the exact selected-owner World closure read"); + assertThat(failure.getCause()).isNull(); + }); verify(inventoryRead, never()).readRetained(any()); } } From 588a5969ea0fb165979eee1527195f71ffe7d386 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 09:24:51 +1300 Subject: [PATCH 22/27] fix: remove duplicated World read error mapping and correct proof attribution --- .../player-access-and-session.md | 2 +- ...SelectedOwnerInventoryReadGrpcService.java | 23 +------------------ 2 files changed, 2 insertions(+), 23 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 29d6d34725..d88d72529e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ This preparation is owned by [AA-1.3](#capability-status), which remains `partia 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. -R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R33 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. +R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R28 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. 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. diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java index 35742e650a..a431fbd300 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.worldmanagement.tenant; import io.grpc.Status; -import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import java.util.Objects; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -70,38 +69,18 @@ public void readSelectedOwnerWorldInventory( } catch (WorldSelectedOwnerInventoryReadService.ReadFailure failure) { fail(responseObserver, Status.fromCode(failure.statusCode()), failure.description()); return; - } catch (StatusRuntimeException failure) { - Status status = - failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION - ? Status.FAILED_PRECONDITION - : Status.UNAVAILABLE; - fail( - responseObserver, - status, - status.getCode() == Status.Code.FAILED_PRECONDITION - ? "Exact retained World artifact inventory is unavailable" - : "World selected inventory owner storage is unavailable"); - return; } catch (SecurityException denied) { fail( responseObserver, Status.PERMISSION_DENIED, "Exact same-namespace selected-owner workload is required"); return; - } catch (WorldDesignPublicationFenceRepository.ConflictException - | IllegalArgumentException inconsistent) { + } catch (IllegalArgumentException inconsistent) { fail( responseObserver, Status.FAILED_PRECONDITION, "Exact retained World artifact inventory is unavailable"); return; - } catch (org.springframework.dao.DataAccessException - | org.jooq.exception.DataAccessException unavailable) { - fail( - responseObserver, - Status.UNAVAILABLE, - "World selected inventory owner storage is unavailable"); - return; } catch (RuntimeException failure) { fail( responseObserver, From 7a9e97d2924dac836ed2e390ccaee72b33e20818 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:21:45 +1300 Subject: [PATCH 23/27] fix: require canonical selected-owner inventory requests --- ...ectedOwnerWorldInventoryReadGrpcCodec.java | 17 +++++--- ...wnerWorldInventoryRecipientFieldsTest.java | 43 +++++++++++++++++++ 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java index 44b36cf560..69b7d666aa 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java @@ -82,12 +82,17 @@ public static Request fromRequest(ReadSelectedOwnerWorldInventoryRequest request var freezeEvidence = WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( freezeRequest, request.getFreezeAcknowledgement()); - return new Request( - request.getSchemaVersion(), - request.getTargetNamespace(), - readRequestId, - binding, - freezeEvidence); + Request decoded = + new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + readRequestId, + binding, + freezeEvidence); + if (!toRequest(decoded).equals(request)) { + throw invalid("Selected-owner World inventory read request is noncanonical"); + } + return decoded; } public static ReadSelectedOwnerWorldInventoryResponse toResponse( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java index 913e902ee8..4efc30ebba 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; @@ -162,6 +163,48 @@ void rejectsChangedCompleteRequestEchoAndInventoryDigest() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void rejectsUnknownAndNoncanonicalNestedFreezeInputs() { + var fixture = fixture(Owner.ENTITY_MANAGEMENT); + var requestWire = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var unknownFields = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var unknownFreezeRequest = + requestWire.toBuilder() + .setFreezeRequest( + requestWire.getFreezeRequest().toBuilder().setUnknownFields(unknownFields)) + .build(); + var unknownFreezeAcknowledgement = + requestWire.toBuilder() + .setFreezeAcknowledgement( + requestWire.getFreezeAcknowledgement().toBuilder().setUnknownFields(unknownFields)) + .build(); + var noncanonicalFreezeRequest = + requestWire.toBuilder() + .setFreezeRequest( + requestWire.getFreezeRequest().toBuilder() + .setCanonicalTenantId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA")) + .build(); + var noncanonicalFreezeAcknowledgement = + requestWire.toBuilder() + .setFreezeAcknowledgement( + requestWire.getFreezeAcknowledgement().toBuilder() + .setPublicationFence("BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB")) + .build(); + + for (var tampered : + List.of( + unknownFreezeRequest, + unknownFreezeAcknowledgement, + noncanonicalFreezeRequest, + noncanonicalFreezeAcknowledgement)) { + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(tampered)) + .isInstanceOf(IllegalArgumentException.class); + } + } + @Test void rejectsInventoryBoundToDifferentFreezeAcknowledgement() { var fixture = fixture(Owner.ENTITY_MANAGEMENT); From cb6899b02ecc5386ef3fcbb86724d5ac4f1d5e96 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:21:43 +1300 Subject: [PATCH 24/27] fix(common): classify invalid owner terminal responses --- ...electedSourceIntakeTerminalReadClient.java | 6 ++- ...electedSourceIntakeTerminalReadClient.java | 6 ++- ...ourceIntakeTerminalReadClientMtlsTest.java | 52 +++++++++++++++++++ ...ourceIntakeTerminalReadClientMtlsTest.java | 52 +++++++++++++++++++ 4 files changed, 114 insertions(+), 2 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java index ac16d2f26d..117aea1a7d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.automation.sourceintake; import io.grpc.ManagedChannel; +import io.grpc.Status; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -62,7 +63,10 @@ public AutomationSelectedSourceIntakeTerminalReadEvidence read( try { return AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); } catch (IllegalArgumentException invalid) { - throw new IllegalStateException("Automation returned invalid terminal evidence", invalid); + throw Status.FAILED_PRECONDITION + .withDescription("Automation returned invalid terminal evidence") + .withCause(invalid) + .asRuntimeException(); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java index ca28ee24c8..eb22eb8cca 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.entity.sourceintake; import io.grpc.ManagedChannel; +import io.grpc.Status; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -63,7 +64,10 @@ public EntitySelectedSourceIntakeTerminalReadEvidence read( try { return EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); } catch (IllegalArgumentException invalid) { - throw new IllegalStateException("Entity returned invalid terminal evidence", invalid); + throw Status.FAILED_PRECONDITION + .withDescription("Entity returned invalid terminal evidence") + .withCause(invalid) + .asRuntimeException(); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java index 8fbc6f2eef..242a40197b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -102,6 +102,28 @@ void authenticatesAccountClientAndPinsSameNamespaceAutomationServer() throws Exc assertThat(calls).hasValue(1); } + @Test + void authenticatedMalformedResponseIsFailedPrecondition() throws Exception { + startMalformedResponseServer(pki.server()); + client = newClient(pki.client()); + + assertThatThrownBy(() -> client.read(request())).isInstanceOf(IllegalStateException.class); + assertThat(calls).hasValue(0); + + client.init(); + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> { + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(error).getDescription()) + .isEqualTo("Automation returned invalid terminal evidence"); + assertThat(error.getCause()).isInstanceOf(IllegalArgumentException.class); + }); + assertThat(calls).hasValue(1); + } + private void startServer(IntakeTestPki.Identity identity) throws Exception { startServer(identity, 0); } @@ -135,6 +157,36 @@ public void readSelectedSourceIntakeTerminal( .start(); } + private void startMalformedResponseServer(IntakeTestPki.Identity identity) throws Exception { + var service = + new AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceImplBase() { + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + observer.onNext(ReadSelectedSourceIntakeTerminalResponse.getDefaultInstance()); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + net.firedevops.firemud.common.automation.sourceintake + .AutomationSelectedSourceIntakeTerminalReadGrpcCodec.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 AutomationSelectedSourceIntakeTerminalReadClient newClient( IntakeTestPki.Identity identity) throws Exception { var endpoints = new ServiceEndpointsProperties(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java index b9c7b1c0e3..0b2a518885 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -101,6 +101,28 @@ void authenticatesAccountClientAndPinsSameNamespaceEntityServer() throws Excepti assertThat(calls).hasValue(1); } + @Test + void authenticatedMalformedResponseIsFailedPrecondition() throws Exception { + startMalformedResponseServer(pki.server()); + client = newClient(pki.client()); + + assertThatThrownBy(() -> client.read(request())).isInstanceOf(IllegalStateException.class); + assertThat(calls).hasValue(0); + + client.init(); + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> { + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(error).getDescription()) + .isEqualTo("Entity returned invalid terminal evidence"); + assertThat(error.getCause()).isInstanceOf(IllegalArgumentException.class); + }); + assertThat(calls).hasValue(1); + } + @Test void loopbackMtlsAcceptsCompleteLargeCanonicalReceipt() throws Exception { // Codec/transport values only: this fixture supplies no genuine Account/World/Entity authority. @@ -203,6 +225,36 @@ public void readSelectedSourceIntakeTerminal( .start(); } + private void startMalformedResponseServer(IntakeTestPki.Identity identity) throws Exception { + var service = + new EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceImplBase() { + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + observer.onNext(ReadSelectedSourceIntakeTerminalResponse.getDefaultInstance()); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.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 GrpcEntitySelectedSourceIntakeTerminalReadClient newClient( IntakeTestPki.Identity identity) throws Exception { var endpoints = new ServiceEndpointsProperties(); From 12dec8a80c23d1b513c8b60e23ff8d94002dece3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:35:57 +1300 Subject: [PATCH 25/27] refactor(account): share owner terminal settlement sequence --- ...tSelectedOwnerIntakeSettlementService.java | 145 ++++++++---------- 1 file changed, 61 insertions(+), 84 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java index cac71e9fb5..ffc0dacc05 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.Objects; import java.util.Optional; +import java.util.function.Supplier; import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -114,91 +115,21 @@ public AccountSelectedOwnerIntakeSettlementReceipt settle( AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(namespace, original); - requireNoAmbientTransaction(); - AutomationSelectedSourceIntakeTerminalReadEvidence remote; - try { - remote = automationClient.read(request); - } catch (StatusRuntimeException failure) { - if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { - throw Status.FAILED_PRECONDITION - .withDescription("Automation terminal evidence is not committed") - .asRuntimeException(); - } - Status.Code code = failure.getStatus().getCode(); - if (code == Status.Code.NOT_FOUND - || code == Status.Code.ALREADY_EXISTS - || code == Status.Code.DATA_LOSS) { - throw Status.fromCode(code).asRuntimeException(); - } - throw Status.UNAVAILABLE - .withDescription("Automation terminal evidence is unavailable") - .asRuntimeException(); - } catch (RuntimeException unavailable) { - throw Status.UNAVAILABLE - .withDescription("Automation terminal evidence is unavailable") - .withCause(unavailable) - .asRuntimeException(); - } + AutomationSelectedSourceIntakeTerminalReadEvidence remote = + readOwnerTerminal("Automation", () -> automationClient.read(request)); AutomationSelectedSourceIntakeTerminalReadEvidence exactEvidence = requireExactTerminal(request, original, remote); - requireNoAmbientTransaction(); - AccountSelectedOwnerIntakeSettlementReceipt committed = - ownerTransaction.execute(ignored -> repository.settleCommittedEmpty(exactEvidence)); - requireSettlement(committed, original, exactEvidence); - - // This independent lookup is deliberately lookup-only. An unknown first commit remains - // unresolved; replaying settleCommittedEmpty here could conceal its outcome. - requireNoAmbientTransaction(); - AccountSelectedOwnerIntakeSettlementReceipt readback = - ownerTransaction.execute( - ignored -> - Objects.requireNonNull( - repository.findSettlement(original), - "Account settlement readback returned no result") - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Committed Account settlement is not readable") - .asRuntimeException())); - requireSettlement(readback, original, exactEvidence); - if (!sameSettlement(committed, readback)) { - throw Status.FAILED_PRECONDITION - .withDescription("Committed Account settlement readback differs") - .asRuntimeException(); - } - return readback; + return commitAndReadBack( + original, exactEvidence, () -> repository.settleCommittedEmpty(exactEvidence)); } private AccountSelectedOwnerIntakeSettlementReceipt settleEntity( SelectedOwnerIntakeAuthorizationBinding original) { var request = EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(namespace, original); - requireNoAmbientTransaction(); - final EntitySelectedSourceIntakeTerminalReadEvidence remote; - try { - remote = entityClient.read(request); - } catch (StatusRuntimeException failure) { - if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { - throw Status.FAILED_PRECONDITION - .withDescription("Entity terminal evidence is not committed") - .asRuntimeException(); - } - Status.Code code = failure.getStatus().getCode(); - if (code == Status.Code.NOT_FOUND - || code == Status.Code.ALREADY_EXISTS - || code == Status.Code.DATA_LOSS) { - throw Status.fromCode(code).asRuntimeException(); - } - throw Status.UNAVAILABLE - .withDescription("Entity terminal evidence is unavailable") - .asRuntimeException(); - } catch (RuntimeException unavailable) { - throw Status.UNAVAILABLE - .withDescription("Entity terminal evidence is unavailable") - .withCause(unavailable) - .asRuntimeException(); - } + final EntitySelectedSourceIntakeTerminalReadEvidence remote = + readOwnerTerminal("Entity", () -> entityClient.read(request)); final EntitySelectedSourceIntakeTerminalReadEvidence exact; try { if (remote == null @@ -236,26 +167,72 @@ private AccountSelectedOwnerIntakeSettlementReceipt settleEntity( .withCause(invalid) .asRuntimeException(); } + return commitAndReadBack(original, exact, () -> repository.settleEntityCommittedEmpty(exact)); + } + + private R readOwnerTerminal(String ownerLabel, Supplier read) { + requireNoAmbientTransaction(); + try { + return read.get(); + } catch (StatusRuntimeException failure) { + if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { + throw Status.FAILED_PRECONDITION + .withDescription(ownerLabel + " terminal evidence is not committed") + .asRuntimeException(); + } + Status.Code code = failure.getStatus().getCode(); + if (code == Status.Code.NOT_FOUND + || code == Status.Code.ALREADY_EXISTS + || code == Status.Code.DATA_LOSS) { + throw Status.fromCode(code).asRuntimeException(); + } + throw Status.UNAVAILABLE + .withDescription(ownerLabel + " terminal evidence is unavailable") + .asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription(ownerLabel + " terminal evidence is unavailable") + .withCause(unavailable) + .asRuntimeException(); + } + } + + private AccountSelectedOwnerIntakeSettlementReceipt commitAndReadBack( + SelectedOwnerIntakeAuthorizationBinding original, + Object exactOwnerTerminal, + Supplier commit) { requireNoAmbientTransaction(); - var committed = - ownerTransaction.execute(ignored -> repository.settleEntityCommittedEmpty(exact)); - requireSettlement(committed, original, exact); + AccountSelectedOwnerIntakeSettlementReceipt committed = + ownerTransaction.execute(ignored -> commit.get()); + requireSettlement(committed, original, exactOwnerTerminal); + + // This independent lookup is deliberately lookup-only. An unknown first commit remains + // unresolved; replaying settleCommittedEmpty here could conceal its outcome. requireNoAmbientTransaction(); - var readback = + boolean entityOwner = original.owner() == Owner.ENTITY_MANAGEMENT; + AccountSelectedOwnerIntakeSettlementReceipt readback = ownerTransaction.execute( ignored -> Objects.requireNonNull( - repository.findSettlement(original), "Account lookup returned no result") + repository.findSettlement(original), + entityOwner + ? "Account lookup returned no result" + : "Account settlement readback returned no result") .orElseThrow( () -> Status.FAILED_PRECONDITION .withDescription( - "Committed Account Entity settlement is not readable") + entityOwner + ? "Committed Account Entity settlement is not readable" + : "Committed Account settlement is not readable") .asRuntimeException())); - requireSettlement(readback, original, exact); + requireSettlement(readback, original, exactOwnerTerminal); if (!sameSettlement(committed, readback)) { throw Status.FAILED_PRECONDITION - .withDescription("Committed Account Entity readback differs") + .withDescription( + entityOwner + ? "Committed Account Entity readback differs" + : "Committed Account settlement readback differs") .asRuntimeException(); } return readback; From 9c54ce2551572d4bc6552dff5143d409b8a08db0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 02:32:28 +1300 Subject: [PATCH 26/27] fix: address selected-owner authorization review findings --- ...lectedOwnerIntakeAuthorizationService.java | 56 +++++-------- ...ntakeAuthorizationReadGrpcServiceTest.java | 26 +++++- ...nerIntakeAuthorizationReadServiceTest.java | 82 ++----------------- ...edOwnerIntakeAuthorizationServiceTest.java | 65 ++------------- ...IntakeSourceReservationRepositoryTest.java | 3 + ...ectedSourceIntakeTerminalReadEvidence.java | 5 +- ...ectedSourceIntakeTerminalReadEvidence.java | 5 +- ...electedOwnerIntakeClientLifecycleTest.java | 7 ++ ...SelectedOwnerIntakeSourceTestFixtures.java | 46 ++++++++--- ...rldSelectedOwnerInventoryTestFixtures.java | 82 ++----------------- 10 files changed, 115 insertions(+), 262 deletions(-) rename services/common-platform-core/src/{test => testFixtures}/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java (74%) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java index 537f734693..238be12848 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java @@ -73,42 +73,28 @@ public SelectedOwnerIntakeAuthorizationBinding authorizeWithEnvironmentCapture( Objects.requireNonNull(selected, "selected Draft binding is required"); Objects.requireNonNull(environmentCapture, "current Account environment capture is required"); - Optional retained = - findScope(originalCreatorCredential, intakeRequestId, owner, selected); - SelectedOwnerIntakeSourceReadScope scope = null; - if (retained.isPresent()) { - scope = retained.orElseThrow(); - var recovery = recover(scope); - if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) - throw denied("Original selected-owner intake reservation was aborted"); - if (recovery.state() - == AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED) { - var original = - findFinalAuthorization(scope) - .orElseThrow( - () -> denied("Finalized selected-owner intake authorization is unavailable")); - return readFinalAuthorization(original); - } - } else { - var initialEnvironment = requireEnvironment(environmentCapture.get()); - scope = - reserveSourceRead( - originalCreatorCredential, intakeRequestId, owner, selected, initialEnvironment); - var recovery = recover(scope); - if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) - throw denied("Original selected-owner intake reservation was aborted"); - if (recovery.state() - == AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED) { - var original = - findFinalAuthorization(scope) - .orElseThrow( - () -> denied("Finalized selected-owner intake authorization is unavailable")); - return readFinalAuthorization(original); - } + SelectedOwnerIntakeSourceReadScope scope = + findScope(originalCreatorCredential, intakeRequestId, owner, selected) + .orElseGet( + () -> + reserveSourceRead( + originalCreatorCredential, + intakeRequestId, + owner, + selected, + requireEnvironment(environmentCapture.get()))); + var recovery = recover(scope); + if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) + throw denied("Original selected-owner intake reservation was aborted"); + if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED) { + var original = + findFinalAuthorization(scope) + .orElseThrow( + () -> denied("Finalized selected-owner intake authorization is unavailable")); + return readFinalAuthorization(original); } var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(namespace, scope); - SelectedOwnerIntakeSourceReadScope reservationScope = scope; outsideSql(); // The authenticated Game Design client enforces exact request echo, wire closure, six-family // content integrity and the absence of SQL or transaction synchronization during this call. @@ -137,7 +123,7 @@ public SelectedOwnerIntakeAuthorizationBinding authorizeWithEnvironmentCapture( finalizationEnvironment, current -> repository.finalizeSourceRead( - reservationScope, + scope, content, current, () -> @@ -148,7 +134,7 @@ public SelectedOwnerIntakeAuthorizationBinding authorizeWithEnvironmentCapture( // only the exact same content and operation; never allocate a replacement scope or fence. Optional committed; try { - committed = findFinalAuthorization(reservationScope); + committed = findFinalAuthorization(scope); } catch (RuntimeException readFailure) { if (readFailure != finalizationFailure) finalizationFailure.addSuppressed(readFailure); throw finalizationFailure; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java index 9603c2eaf1..15b3c5c4e7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; /** Synthetic handler tests only; they do not establish mTLS or PostgreSQL owner proof. */ class AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest { @@ -84,10 +85,13 @@ void authenticatesOwnerAndRejectsEndUserBeforeParsingOrOwnerAccess() { void returnsExactEchoOnlyForMatchingEntityAndAutomationReader() { var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + var expectedRequests = + new java.util.ArrayList(); for (Owner domain : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(domain); var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + expectedRequests.add(request); var wire = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest(request); var result = new Collector(); peerFromUri(binding.intendedReader()) @@ -98,7 +102,27 @@ void returnsExactEchoOnlyForMatchingEntityAndAutomationReader() { assertThat(result.response.getRequest()).isEqualTo(wire); assertThat(result.response.getHeld()).isTrue(); } - verify(owner, times(2)).requireHeld(any()); + ArgumentCaptor captured = + ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationReadEvidence.Request.class); + verify(owner, times(2)).requireHeld(captured.capture()); + assertThat(captured.getAllValues()).hasSize(2); + assertThat(captured.getAllValues()).containsExactlyElementsOf(expectedRequests); + for (int index = 0; index < captured.getAllValues().size(); index++) { + var actual = captured.getAllValues().get(index); + var expectedBinding = expectedRequests.get(index).binding(); + assertThat(actual.schemaVersion()) + .isEqualTo(SelectedOwnerIntakeAuthorizationReadEvidence.SCHEMA_VERSION); + assertThat(actual.targetNamespace()).isEqualTo("test"); + assertThat(actual.readRequestId()) + .isNotIn( + actual.binding().operationId(), + actual.binding().fenceId(), + actual.binding().intakeRequestId()); + assertThat(actual.intendedReader()).isEqualTo(expectedBinding.intendedReader()); + assertThat(actual.retentionPurpose()).isEqualTo(expectedBinding.purpose()); + assertThat(actual.binding().canonicalBytes()) + .containsExactly(expectedBinding.canonicalBytes()); + } } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java index bd9dbc2025..4fece0788e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java @@ -12,7 +12,6 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.StatusRuntimeException; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; @@ -25,15 +24,9 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; -import net.firedevops.firemud.common.gamedesign.AssetSnapshot; -import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSnapshot; import net.firedevops.firemud.common.gamedesign.CommandSource; -import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; @@ -163,65 +156,12 @@ static SelectedOwnerIntakeAuthorizationBinding binding(Owner owner) { private static SelectedOwnerIntakeSourceContent content( SelectedOwnerIntakeSourceReadScope scope) { - var out = new ByteArrayOutputStream(); - frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - frame(out, scope.canonicalBytes()); - frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = snapshot(family, scope.selected()); - frame(out, family); - frame(out, snapshot); - frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); - } - - private static byte[] snapshot(String family, DraftCommitBinding selected) { - UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - return switch (family) { - case "COMMAND" -> - new CommandSnapshot( - selected, - "0", - null, - DraftAuthorizationFenceBinding.digest( - "synthetic-read-fixture".getBytes(StandardCharsets.UTF_8)), - List.of()) - .canonicalBytes(); - case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); - case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); - case "GAMEPLAY_RULE" -> - 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()))) - .canonicalBytes(); - case "BRANDING" -> - new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); - case "TEMPLATE_CONFIG" -> - new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) - .canonicalBytes(); - default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); - }; + return SelectedOwnerIntakeSourceTestFixtures.content( + scope, + DraftAuthorizationFenceBinding.digest( + "synthetic-read-fixture".getBytes(StandardCharsets.UTF_8)), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "0"); } private static List sources(UUID actor, UUID tenant) { @@ -260,14 +200,6 @@ private static DraftCommitBinding selected(UUID tenant) { "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); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java index 9c3b3630bb..84eb44c9ba 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java @@ -17,7 +17,6 @@ import io.grpc.Metadata; import io.grpc.Status; import io.grpc.StatusRuntimeException; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.util.List; @@ -38,16 +37,10 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; -import net.firedevops.firemud.common.gamedesign.AssetSnapshot; -import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSnapshot; import net.firedevops.firemud.common.gamedesign.CommandSource; -import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import org.jooq.Record; @@ -656,59 +649,13 @@ private static SelectedOwnerIntakeSourceReadScope scope( private static SelectedOwnerIntakeSourceContent content( SelectedOwnerIntakeSourceReadScope scope, String marker) { - var selected = scope.selected(); UUID markerGenesis = UUID.nameUUIDFromBytes(marker.getBytes(StandardCharsets.UTF_8)); String markerEpoch = Integer.toUnsignedString(marker.hashCode()); - 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", markerGenesis.toString(), - "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), - "entries", List.of()))); - var template = new TemplateConfigSourceSnapshot(selected, "0", null, markerGenesis, List.of()); - Map snapshots = - Map.of( - "COMMAND", - new CommandSnapshot( - selected, - "0", - null, - DraftAuthorizationFenceBinding.digest(marker.getBytes(StandardCharsets.UTF_8)), - List.of()) - .canonicalBytes(), - "REALM_POLICY", - new RealmPolicySnapshot(selected, markerEpoch, List.of()).canonicalBytes(), - "ASSET", - new AssetSnapshot(selected, "0", null, markerGenesis, List.of()).canonicalBytes(), - "BRANDING", - new BrandingSourceSnapshot(selected, "0", null, markerGenesis, List.of()) - .canonicalBytes()); - var out = new ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); - DraftAuthorizationFenceBinding.frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = - switch (family) { - case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); - case "TEMPLATE_CONFIG" -> template.canonicalBytes(); - default -> snapshots.get(family); - }; - DraftAuthorizationFenceBinding.frame(out, family); - DraftAuthorizationFenceBinding.frame(out, snapshot); - DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + return SelectedOwnerIntakeSourceTestFixtures.content( + scope, + DraftAuthorizationFenceBinding.digest(marker.getBytes(StandardCharsets.UTF_8)), + markerGenesis, + markerEpoch); } private static String tokenHash(String value) { 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 index 194de5fc55..0e8c71be86 100644 --- 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 @@ -45,6 +45,9 @@ void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction() assertThatThrownBy(() -> repository.settleCommittedEmpty(null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.settleEntityCommittedEmpty(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); verifyNoInteractions(dsl); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java index 65c66ca538..cfc1657998 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java @@ -72,13 +72,12 @@ public boolean equals(Object value) { && schemaVersion == other.schemaVersion && targetNamespace.equals(other.targetNamespace) && readRequestId.equals(other.readRequestId) - && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + && binding.equals(other.binding); } @Override public int hashCode() { - return Objects.hash( - schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + return Objects.hash(schemaVersion, targetNamespace, readRequestId, binding); } private static boolean collides( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java index 826c228781..c7e695a630 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java @@ -72,13 +72,12 @@ public boolean equals(Object value) { && schemaVersion == other.schemaVersion && targetNamespace.equals(other.targetNamespace) && readRequestId.equals(other.readRequestId) - && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + && binding.equals(other.binding); } @Override public int hashCode() { - return Objects.hash( - schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + return Objects.hash(schemaVersion, targetNamespace, readRequestId, binding); } private static boolean collides( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java index 72a84eced9..c90ecfe7f7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -25,6 +25,7 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.GrpcEntitySelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -177,6 +178,7 @@ private enum ClientKind { AUTHORIZATION, WORLD_CLOSURE_AUTHORIZATION, SOURCE_READ, + ENTITY_TERMINAL, AUTOMATION_TERMINAL, GAME_DESIGN_SOURCE, WORLD_INVENTORY; @@ -202,6 +204,11 @@ ClientHandle create( var client = new GrpcSelectedOwnerIntakeSourceReadClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } + case ENTITY_TERMINAL -> { + var client = + new GrpcEntitySelectedSourceIntakeTerminalReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } case AUTOMATION_TERMINAL -> { var client = new AutomationSelectedSourceIntakeTerminalReadClient(endpoints, tls, factory, "test"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java similarity index 74% rename from services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java rename to services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java index 1ec8a8ab1d..abfea50d5f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java @@ -21,18 +21,28 @@ public final class SelectedOwnerIntakeSourceTestFixtures { private SelectedOwnerIntakeSourceTestFixtures() {} public static byte[] snapshot(String family, DraftCommitBinding selected) { - return snapshot(family, selected, 0); + return snapshot(family, selected, GENESIS_DIGEST, GENESIS, "0", 0); } /** Builds canonical six-family content for a selected-owner intake scope. */ public static SelectedOwnerIntakeSourceContent content(SelectedOwnerIntakeSourceReadScope scope) { + return content(scope, GENESIS_DIGEST, GENESIS, "0"); + } + + /** Builds canonical six-family content with explicit synthetic source marker values. */ + public static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, + String commandDigest, + UUID genesis, + String realmPolicyEpoch) { Objects.requireNonNull(scope, "scope"); var out = new ByteArrayOutputStream(); frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); frame(out, scope.canonicalBytes()); frame(out, scope.digest()); for (String family : CONTENT_FAMILIES) { - byte[] sourceSnapshot = snapshot(family, scope.selected()); + byte[] sourceSnapshot = + snapshot(family, scope.selected(), commandDigest, genesis, realmPolicyEpoch, 0); frame(out, family); frame(out, sourceSnapshot); frame(out, DraftAuthorizationFenceBinding.digest(sourceSnapshot)); @@ -50,21 +60,33 @@ public static String selectedRevisionPayload() { /** 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 snapshot(family, selected, GENESIS_DIGEST, GENESIS, "0", largeCommandFieldSize); + } + + private static byte[] snapshot( + String family, + DraftCommitBinding selected, + String commandDigest, + UUID genesis, + String realmPolicyEpoch, + 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 "COMMAND" -> command(selected, commandDigest, largeCommandFieldSize).canonicalBytes(); + case "REALM_POLICY" -> + new RealmPolicySnapshot(selected, realmPolicyEpoch, 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(); + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> gameplay(selected, genesis).canonicalBytes(); case "TEMPLATE_CONFIG" -> - new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()) + 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) { + private static CommandSnapshot command( + DraftCommitBinding selected, String commandDigest, int largeCommandFieldSize) { if (largeCommandFieldSize < 0) throw new IllegalArgumentException("Command field size must be nonnegative"); List definitions = @@ -89,10 +111,10 @@ private static CommandSnapshot command(DraftCommitBinding selected, int largeCom selected.commitId(), selected.revisions().getFirst().revisionId(), selected.revisions().getFirst().revisionOrder())); - return new CommandSnapshot(selected, "0", null, GENESIS_DIGEST, definitions); + return new CommandSnapshot(selected, "0", null, commandDigest, definitions); } - private static GameplayRuleSelectedSource gameplay(DraftCommitBinding selected) { + private static GameplayRuleSelectedSource gameplay(DraftCommitBinding selected, UUID genesis) { return new GameplayRuleSelectedSource( GameplayRuleManifest.canonical( Map.of( @@ -101,7 +123,7 @@ private static GameplayRuleSelectedSource gameplay(DraftCommitBinding selected) "bindingDigest", selected.digest(), "sourceEpoch", "0", "inheritedCommitId", "", - "genesisReceiptId", GENESIS.toString(), + "genesisReceiptId", genesis.toString(), "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), "entries", List.of()))); } diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java index 5e0437cf7f..56fa6f9878 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java @@ -1,10 +1,8 @@ package net.firedevops.firemud.worldmanagement.tenant; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.util.List; -import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; @@ -15,15 +13,8 @@ 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.AssetSnapshot; -import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSnapshot; import net.firedevops.firemud.common.gamedesign.CommandSource; -import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; -import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; @@ -73,7 +64,13 @@ static Fixture fixture(Owner owner) { id("77777777-7777-4777-8777-777777777777"), actor, selected); - var content = sourceContent(scope); + var content = + SelectedOwnerIntakeSourceTestFixtures.content( + scope, + DraftAuthorizationFenceBinding.digest( + "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "0"); var binding = new SelectedOwnerIntakeAuthorizationBinding( content, @@ -138,69 +135,6 @@ static Fixture fixture(Owner owner) { SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, binding, freezeEvidence)); } - private static SelectedOwnerIntakeSourceContent sourceContent( - SelectedOwnerIntakeSourceReadScope scope) { - var out = new ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); - DraftAuthorizationFenceBinding.frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = sourceSnapshot(family, scope.selected()); - DraftAuthorizationFenceBinding.frame(out, family); - DraftAuthorizationFenceBinding.frame(out, snapshot); - DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); - } - - private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { - UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - return switch (family) { - case "COMMAND" -> - new CommandSnapshot( - selected, - "0", - null, - DraftAuthorizationFenceBinding.digest( - "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), - List.of()) - .canonicalBytes(); - case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); - case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); - case "GAMEPLAY_RULE" -> - 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()))) - .canonicalBytes(); - case "BRANDING" -> - new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); - case "TEMPLATE_CONFIG" -> - new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) - .canonicalBytes(); - default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); - }; - } - private static SourceEvidence source(SourceKind kind, String scope, String marker) { return new SourceEvidence( kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); From 707b4f5891e05af17fac9d2b94a8c74fd047064c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:52:18 +1300 Subject: [PATCH 27/27] docs: complete selected-owner capability proof anchors --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index d88d72529e..5f732c4deb 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -222,7 +222,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); [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.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); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.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); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.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. |