diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 0c5dddb7f6..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 source-disclosure preparation adds distinct Entity/Automation preliminary reservations, retained source-writer exclusion and exact authenticated source permission in forward V1007. It follows the actual V1006 activation-alignment parent plus Saga V1000–V1002 and preserves prior protection/disposal guards. Focused PostgreSQL upgrade and source-disclosure proof passes; full-native qualification remains held on inherited PostgreSQL/Redis failures. These components remain unregistered and unqualified; finalization and terminal settlement are separate unfinished dependencies. The [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof and remaining dependencies. +The 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). @@ -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/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 3c7932ded9..9f649d4498 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 complete published-spawn response has a 4 MiB serialized Protobuf limit, matching the existing gRPC inbound ceiling. Its owner encoder, client stub and response decoder enforce the same limit; the decoder checks size before recursively validating or constructing evidence. Oversized evidence is refused rather than truncated or partially accepted. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 70d3d56ae3..c846b4b6d7 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -231,6 +231,17 @@ 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`: 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. + +- `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. + - `2026-10-19`: Independent maintenance temporarily becomes the product queue's parent - Context: Controller recovery maintenance PR #3271 was inserted before the existing product front to obtain the next admissible shared review slot. - Observation: the current controller queue is strictly linear and has no independent maintenance root. Inserting an open maintenance PR before the product front changes the product front's effective parent even though the patches are independent, creating an integration fence until maintenance merges. 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 92a4edaca8..5f732c4deb 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,9 +12,11 @@ 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 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. -The isolated source-disclosure preparation adds distinct Account preliminary reservations, exact recovery/abort and authenticated permission for selected Entity and Automation source reads. New forward Account V1007 follows the actual V1006 activation-alignment parent plus Saga V1000–V1002; existing publication, World participation, protection and disposal history remains unchanged. Prepared upgrade proof compares all prior Flyway row metadata and xmin, populated Account/source baselines, disposal and Saga rows, and exact protection, alignment and disposal guards, and passes in R28. Game Design retains real branding and all six source families, with command parsing converged on the shared contract. The actual Account-permission-to-Game-Design disclosure composition passes with controlled upstream inputs; controlled upstream creator, environment and selected-source provenance establish no genuine authority. Finalized recipient authorization, World closure, exact owner terminal settlement and selected-full attestation 4 remain unfinished. These owners remain unregistered and unqualified, all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and [gameplay tracker](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) retain their respective authority and dependency roles. +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 @@ -66,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). @@ -220,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. | 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..238be12848 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java @@ -0,0 +1,295 @@ +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; +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"); + + 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); + 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. + 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()); + SelectedOwnerIntakeAuthorizationBinding finalized; + try { + finalized = + actors.withCurrent( + originalCreatorCredential, + selected.target().canonicalTenantId(), + finalizationEnvironment, + current -> + repository.finalizeSourceRead( + scope, + 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(scope); + } 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..ffc0dacc05 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java @@ -0,0 +1,416 @@ +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 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; +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); + AutomationSelectedSourceIntakeTerminalReadEvidence remote = + readOwnerTerminal("Automation", () -> automationClient.read(request)); + AutomationSelectedSourceIntakeTerminalReadEvidence exactEvidence = + requireExactTerminal(request, original, remote); + + return commitAndReadBack( + original, exactEvidence, () -> repository.settleCommittedEmpty(exactEvidence)); + } + + private AccountSelectedOwnerIntakeSettlementReceipt settleEntity( + SelectedOwnerIntakeAuthorizationBinding original) { + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(namespace, original); + final EntitySelectedSourceIntakeTerminalReadEvidence remote = + readOwnerTerminal("Entity", () -> entityClient.read(request)); + 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(); + } + 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(); + 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(); + boolean entityOwner = original.owner() == Owner.ENTITY_MANAGEMENT; + AccountSelectedOwnerIntakeSettlementReceipt readback = + ownerTransaction.execute( + ignored -> + Objects.requireNonNull( + repository.findSettlement(original), + entityOwner + ? "Account lookup returned no result" + : "Account settlement readback returned no result") + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + entityOwner + ? "Committed Account Entity settlement is not readable" + : "Committed Account settlement is not readable") + .asRuntimeException())); + requireSettlement(readback, original, exactOwnerTerminal); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription( + entityOwner + ? "Committed Account Entity readback differs" + : "Committed Account settlement 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/AccountSelectedOwnerIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java index da3fc6945c..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 @@ -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,10 @@ 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/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..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,22 +10,34 @@ 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; 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 +47,7 @@ public AccountSelectedOwnerIntakeSourceReservationRepository(DSLContext dsl) { public enum State { RESERVED, + FINALIZED, ABORTED } @@ -173,7 +186,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 +200,355 @@ 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"); + } + return settleCommittedEmpty( + requested, + evidence.request().readRequestId(), + () -> AccountSelectedOwnerIntakeSettlementReceipt.create(evidence), + 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"); + } + 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); + 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, retryEvidence); + + AccountSelectedOwnerIntakeSettlementReceipt receipt = receiptFactory.get(); + 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(), + readRequestId, + receipt.ownerReceiptBytes(), + receipt.ownerReceiptDigest(), + receipt.canonicalBytes(), + receipt.digest()); + return exactSettlement(settlement(requested.operationId()), requested, retryEvidence); + } + + 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 +561,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/V1008__selected_owner_intake_final_authorizations.sql b/services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql new file mode 100644 index 0000000000..2035ae015c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1008__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/V1009__selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql new file mode 100644 index 0000000000..b437b921b8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1009__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/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 new file mode 100644 index 0000000000..07f6e22bcc --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql @@ -0,0 +1,708 @@ +-- Add Entity's authenticated closed COMMITTED_EMPTY receipt to the existing immutable family. +-- V1009 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 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 V1009 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 selected-owner 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 selected-owner 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 owner terminal 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 owner 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..20920fbed8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,2367 @@ +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.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.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 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(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + Clock.systemUTC(), + "1009")) { + 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-v1009"); + var original = + f.tx(() -> repository.settleCommittedEmpty(terminalEvidence(automation, 8801, 8802))); + var entity = + finalizeEntityBinding(issued, reservations, repository, selected, "pending-v1009-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"); + + 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); + + 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()); + 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 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", + "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..15b3c5c4e7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java @@ -0,0 +1,256 @@ +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; +import org.mockito.ArgumentCaptor; + +/** 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"); + 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()) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(wire, result)); + + assertThat(result.error).isNull(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getRequest()).isEqualTo(wire); + assertThat(result.response.getHeld()).isTrue(); + } + 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 + 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..4fece0788e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java @@ -0,0 +1,231 @@ +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.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.CommandSource; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +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; +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) { + 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) { + 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 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..84eb44c9ba --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java @@ -0,0 +1,709 @@ +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.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.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.CommandSource; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceClient; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +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; +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 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( + 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) { + UUID markerGenesis = UUID.nameUUIDFromBytes(marker.getBytes(StandardCharsets.UTF_8)); + String markerEpoch = Integer.toUnsignedString(marker.hashCode()); + return SelectedOwnerIntakeSourceTestFixtures.content( + scope, + DraftAuthorizationFenceBinding.digest(marker.getBytes(StandardCharsets.UTF_8)), + markerGenesis, + markerEpoch); + } + + 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..82d8cdab2b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java @@ -0,0 +1,731 @@ +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.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +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()); + } + + @Test + 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) { + 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); + } + + 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); + } + } + } + + 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..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 @@ -33,6 +33,22 @@ 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"); + assertThatThrownBy(() -> repository.settleEntityCommittedEmpty(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..85ebabb83d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java @@ -0,0 +1,242 @@ +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; +import org.mockito.ArgumentCaptor; + +/** 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"); + 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") + .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(); + } + } + 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 + 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 bd7304f0c0..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 @@ -137,9 +137,10 @@ final class AccountControlUiOwnerSourcesFixture { if (migrationTarget != null && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) - && !"1007".equals(migrationTarget)) { + && !"1007".equals(migrationTarget) + && !"1009".equals(migrationTarget)) { throw new IllegalArgumentException( - "Only the preserved 160.1 source-retention, 1006 parent or 1007 source-disclosure frontier 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("-", ""); 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..73f6b14b74 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.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.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; + +/** 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; + + public AccountSelectedOwnerIntakeAuthorizationGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + FileBackedMtls.require(tlsProperties, "Account selected-owner authorization read"), + channelFactory, + AccountSelectedOwnerIntakeAuthorizationGrpcClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + this.workloadNamespace = workloadNamespace; + } + + 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) { + 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 = + requireInitializedStub( + "Account selected-owner authorization client is not initialized and available") + .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"); + } +} 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..c1f6d7b11b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.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.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; + +/** 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; + + public AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + FileBackedMtls.require(tlsProperties, "Account World closure authorization read"), + channelFactory, + AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + this.workloadNamespace = workloadNamespace; + } + + 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) { + 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 = + requireInitializedStub( + "Account World closure authorization client is not initialized and available") + .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"); + } +} 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..f7912b6ca1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java @@ -0,0 +1,285 @@ +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 final class SelectedOwnerIntakeAuthorizationBinding { + public static final int MAX_BYTES = 16 * 1024 * 1024; + + 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()); + List sortedSources = + List.copyOf(Objects.requireNonNull(sources, "sources")).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sortedSources.isEmpty() + || sortedSources.stream().map(SourceEvidence::key).distinct().count() + != sortedSources.size()) { + throw new IllegalArgumentException("Complete distinct Account sources required"); + } + 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; + } + + 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.clone(); + } + + public String digest() { + 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; + } + + /** + * 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..e5b1ea0e00 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java @@ -0,0 +1,108 @@ +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"); + } + } + + 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) + && authorizationBinding.equals(other.authorizationBinding); + } + + @Override + public int hashCode() { + return Objects.hash(schemaVersion, targetNamespace, transportRequestId, authorizationBinding); + } + } + + /** 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..b321d3418f --- /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 (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"); + } + 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"); + } + + 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, worldInventoryReadEvidence) + .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..117aea1a7d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java @@ -0,0 +1,96 @@ +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; +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.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; + +/** 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; + + public AutomationSelectedSourceIntakeTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + FileBackedMtls.require(tlsProperties, "Automation terminal read"), + channelFactory, + AutomationSelectedSourceIntakeTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + 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) { + 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 = + requireInitializedStub("Automation terminal-read client is not initialized and available") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedSourceIntakeTerminal( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); + try { + return AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Automation returned invalid terminal evidence") + .withCause(invalid) + .asRuntimeException(); + } + } + + @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"); + } +} 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..cfc1657998 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java @@ -0,0 +1,94 @@ +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) + && binding.equals(other.binding); + } + + @Override + public int hashCode() { + return Objects.hash(schemaVersion, targetNamespace, readRequestId, binding); + } + + 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..c7e695a630 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java @@ -0,0 +1,94 @@ +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) + && binding.equals(other.binding); + } + + @Override + public int hashCode() { + return Objects.hash(schemaVersion, targetNamespace, readRequestId, binding); + } + + 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..eb22eb8cca --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java @@ -0,0 +1,96 @@ +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; +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; + +/** 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; + + public GrpcEntitySelectedSourceIntakeTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + FileBackedMtls.require(tlsProperties, "Entity terminal read"), + channelFactory, + GrpcEntitySelectedSourceIntakeTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + 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) { + 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 = + requireInitializedStub("Entity terminal-read client is not initialized and available") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedSourceIntakeTerminal( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); + try { + return EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Entity returned invalid terminal evidence") + .withCause(invalid) + .asRuntimeException(); + } + } + + @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"); + } +} 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..69b7d666aa --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java @@ -0,0 +1,185 @@ +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()); + 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( + 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..ac237e0d13 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.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; + +/** 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; + + public WorldSelectedOwnerInventoryGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + FileBackedMtls.require(tlsProperties, "World owner inventory read"), + channelFactory, + WorldSelectedOwnerInventoryGrpcClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + 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) { + 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 = + requireInitializedStub("World owner inventory client is not initialized") + .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"); + } +} 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..04d5a3f65a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java @@ -0,0 +1,946 @@ +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.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.ByteBuffer; +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 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)) { + 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..f761a805df --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java @@ -0,0 +1,462 @@ +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 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(); + byte[] exposedEvidence = binding.sources().getFirst().evidence(); + exposedEvidence[0] ^= 0x7f; + byte[] exposedContent = binding.content().canonicalBytes(); + 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); + 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(changed).isNotEqualTo(original); + 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..beaae2085a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java @@ -0,0 +1,113 @@ +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.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence.Request; +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.SelectedOwnerIntakeSourceTestFixtures; +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 = SelectedOwnerIntakeSourceTestFixtures.content(scope); + return new SelectedOwnerIntakeAuthorizationBinding(content, sources(actor, tenant)); + } + + 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 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 58ce702cc1..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 @@ -23,12 +23,15 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; 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; 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; @@ -172,23 +175,53 @@ private record ClientHandle( AbstractReloadingBlockingGrpcClient client, Initialize initialize) {} private enum ClientKind { + AUTHORIZATION, + WORLD_CLOSURE_AUTHORIZATION, SOURCE_READ, - GAME_DESIGN_SOURCE; + ENTITY_TERMINAL, + 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 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"); + 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..4efc30ebba --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java @@ -0,0 +1,466 @@ +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.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +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.SelectedOwnerIntakeSourceTestFixtures; +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 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); + 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( + SelectedOwnerIntakeSourceTestFixtures.content(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 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 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..242a40197b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -0,0 +1,216 @@ +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 IntakeTestPki pki; + + private Server server; + private AutomationSelectedSourceIntakeTerminalReadClient client; + private final AtomicInteger calls = new AtomicInteger(); + + @BeforeAll + static void certificates() throws Exception { + 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 + 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(pki.server()); + final int serverPort = server.getPort(); + client = newClient(pki.client()); + 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); + } + + @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); + } + + private void startServer(IntakeTestPki.Identity 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 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(); + 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..0b2a518885 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -0,0 +1,284 @@ +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.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +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; +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 IntakeTestPki pki; + + private Server server; + private GrpcEntitySelectedSourceIntakeTerminalReadClient client; + private final AtomicInteger calls = new AtomicInteger(); + + @BeforeAll + static void certificates() throws Exception { + 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 + 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(pki.server()); + final int serverPort = server.getPort(); + client = newClient(pki.client()); + 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); + } + + @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. + 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( + pki.server().privateKey(), pki.server().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + client = newClient(pki.client()); + 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(IntakeTestPki.Identity identity) throws Exception { + startServer(identity, 0); + } + + private void startServer(IntakeTestPki.Identity 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 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(); + 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/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 53% 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 63f6e6ff59..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 @@ -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,11 +15,41 @@ 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() {} 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(), commandDigest, genesis, realmPolicyEpoch, 0); + 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. */ @@ -26,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 = @@ -65,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( @@ -77,8 +123,16 @@ 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()))); } + + 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-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) {} +} 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 5aec4f2fc5..1c9cc36e40 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 @@ -141,7 +141,7 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu temporary.resolve("account"), local.binding().target().canonicalTenantId(), Clock.systemUTC(), - "1007")) { + null)) { var issued = fixture.preparedOriginalCreator(); var f = issued.sources(); assertThat( @@ -149,7 +149,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( 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..a431fbd300 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +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 (WorldSelectedOwnerInventoryReadService.ReadFailure failure) { + fail(responseObserver, Status.fromCode(failure.statusCode()), failure.description()); + return; + } catch (SecurityException denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Exact same-namespace selected-owner workload is required"); + return; + } catch (IllegalArgumentException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Exact retained World artifact inventory 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 = 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) { + 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..fbf3e9ee0f --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java @@ -0,0 +1,172 @@ +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; +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()); + } + 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 ReadFailure( + Status.Code.PERMISSION_DENIED, + "Account did not confirm the exact selected-owner World closure read"); + } + + 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 = 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()) + || 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 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) { + 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/WorldSelectedOwnerInventoryReadGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java new file mode 100644 index 0000000000..1d74b3318e --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java @@ -0,0 +1,243 @@ +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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Status; +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; +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.dao.DataAccessResourceFailureException; +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 fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(owner); + var request = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + for (Status downstreamStatus : statuses) { + 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), + "secret trailer value"); + var downstream = + downstreamStatus + .withDescription("secret downstream detail") + .withCause(new IllegalStateException("secret downstream cause")) + .augmentDescription(" secret suffix") + .asRuntimeException(trailers); + when(account.readHeld(any())).thenThrow(downstream); + var readService = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventory, account); + 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(); + 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" + : "automation-scripting-service"; + } + + 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 static final class RecordingObserver + implements StreamObserver { + private ReadSelectedOwnerWorldInventoryResponse response; + private Throwable error; + private boolean completed; + + @Override + public void onNext(ReadSelectedOwnerWorldInventoryResponse value) { + response = 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; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} 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..947877a200 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java @@ -0,0 +1,306 @@ +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.util.ArrayList; +import java.util.List; +import java.util.Map; +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.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 = WorldSelectedOwnerInventoryTestFixtures.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 = WorldSelectedOwnerInventoryTestFixtures.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()))) + .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()); + } + } + } + + @Test + void domainServiceRejectsWrongRecipientEndUserAndAmbientSqlBeforeAccountCall() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = WorldSelectedOwnerInventoryTestFixtures.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 String serviceName(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + } + + 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; + } + } +} 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..56fa6f9878 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryTestFixtures.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +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.CommandSource; +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; +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 = + SelectedOwnerIntakeSourceTestFixtures.content( + scope, + DraftAuthorizationFenceBinding.digest( + "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "0"); + 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 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) {} +}