diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index cb49906801..34b6721b1f 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,6 +54,10 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +The initial private gameplay LOGIN owner, signer, registry, and response-recovery code is present as unregistered Account source, with focused proof sources. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. This does not add or activate an API, proto method, or Spring composition; the source has no caller-selected profile or property override. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact proof scope; deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, and runtime activation remain unproved. + +Account UUID generation currently has three established provenances: `ACCOUNT_REPOSITORY_INSERT` uses `AccountRepository` and `UUID.randomUUID()`; `ACCOUNT_V29_MIGRATION` uses `gen_random_uuid()` for retained rows; and `ACCOUNT_DATABASE_INSERT` uses the `gen_random_uuid()` database default. These current producer outputs are RFC 4122 version 4 UUIDs. This records generator provenance and does not claim that database constraints reject custom UUID versions. + This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 and #2848 retain their runtime and recovery gaps. Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9074f4cc9d..863c23bf9a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. + Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3cb60a7cd6..76e233e5b5 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -102,6 +102,14 @@ Entry format: - Expected pattern: require complete immutable publication membership before completion, and recover verified older partial unfinalized runs additively without replacing dispositions or inventing another round. Retain original and supplemental evidence together. - Current status: the bounded controller repair passes focused local regression proof; trusted promotion and canonical live recovery remain separate steps, so the live missing finding is not yet confirmed recovered. +- `2026-10-11`: Concurrent CI watchers can exhaust shared GitHub API quota + - Context: six native `gh run watch` processes in the Gameplay lane encountered the same REST rate limit while waiting for one candidate's checks. + - Observation: separate low-cost-looking watchers share one credential's API budget; multiplying short-interval reads can block artifact inspection and other workers' CI evidence collection. + - Expected pattern: use one quota-aware observation owner with bounded low-frequency consolidated reads across relevant exact heads, and back off until the reported reset. One helper launching six independent pollers is still prohibited fanout, not a single observer. Stop redundant local watchers without cancelling GitHub runs; continue safe local implementation and validation. + - Current status: the six distinct workflow watchers are stopped and the correction is recorded in the SQL job brief. Exact artifact qualification and CI completion remain separate evidence, not inferred from historical green runs. + + - Reconsideration trigger: revisit after one quota-aware observer completes exact-head artifact qualification and CI without a rate-limit error, or the controller provides a shared consolidated watcher. Retain while either proof or the tooling improvement remains incomplete. + - `2026-10-12`: Retrospective evidence needs source-clock provenance - Context: a curated import of an independently completed review retained unknown review clocks but displayed generated recording timestamps as its start and finish. - Observation: a storage default can create false chronology even when the immutable evidence accurately discloses missing clocks. @@ -158,3 +166,10 @@ Entry format: - Observation: A saved head/base tuple and prior proof did not establish current mergeability. The normal merge exposed one documentation conflict; the maintenance fixture changes merged cleanly. - Expected pattern: At publication and closeout, verify the actual base branch tip and current mergeability through the bounded canonical topology/status checks. Treat a stale PR base OID or missing new-head source CI as unresolved state, and reconcile before claiming readiness. - Reconsideration trigger: Verify the next published front against its actual remote base and current required CI; retain any remaining stale-base diagnostic gap for controller maintenance. + +- `2026-10-13`: Local PostgreSQL availability can fail after container startup + - Context: Gameplay’s #3120 final-parent full gate at `42c524c` selected 105 PostgreSQL cases but 13 errors in three suites reported connection refusal on ephemeral localhost ports, after the preceding complete gate at `d0362dd` passed all 105 cases. + - Observation: Docker daemon availability and a started-container event do not prove a fixture’s JDBC endpoint remains reachable; the failure cause and responsible lifecycle are unknown. These connection errors do not establish failed product assertions. + - Expected pattern: classify connection-refused fixture failures separately from product assertions; capture live container events, PostgreSQL logs and endpoint state before fixture cleanup, and qualify the exact suites before crediting physical proof. Retained Docker events are bounded and destroyed containers lose inspect/log evidence; an exit code of 137 after an explicit cleanup kill does not establish OOM or external cleanup. + - Current status: the three affected suites passed all 13 cases in the composed #3125 run and fresh exact-parent #3120 CI (all 105 PostgreSQL cases passed). The subsequent #3155 local Account gate also failed before assertions in 24 of 218 integration cases across eight suites, leaving PostgreSQL proof partial and Redis initialization unproved. The local connection-refused cause remains unknown; retain time-correlated container and endpoint evidence without weakening fixtures or changing the environment speculatively. + - Reconsideration trigger: revisit after the affected cases execute physically against the final parent and the endpoint failure is explained or shown to be transient; retain until the cause and proof limits are recorded. 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 fd6ba3cc32..3c1df1bcef 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,20 @@ This is a non-normative implementation tracker for player access and session. Ca The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). +### Initial private gameplay LOGIN issuance source intake + +This preparation is owned by `AA-2.1` in [Capability Status](#capability-status). + +Account now contains an unregistered initial private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157.1 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation are outside this cut. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. At original source head `8df6c870801f96a902742da0223f42cd1cfe527f`, consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Its Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. At reconciled head `996959aa2477890ec901154e2c2376538da9012a`, consolidated Account formatting/fullCheck, static analysis, integration-source compilation and documentation checks passed in 1m 59s (93 tasks). Its XML reports 1,187 unit cases with four skips and 191 integration cases with 188 skips, with zero failures/errors; the skipped PostgreSQL/Redis cases remain unproved physically. Those historical local runs did not establish physical PostgreSQL/Redis proof. The later published source at `f9922f2b6c59b836c730bcb47100719c3498dbe0` passed fresh exact-head Account CI with 1,194 unit cases (four skips) and 207 PostgreSQL/Redis integration cases with zero failures, errors or skips (Validation `38247785958`, Account job `114806613509`, artifact `11747377390`); that exact-head proof includes the required V157.1 guard and physical TRUNCATE rejection coverage. This is bounded fixture proof; it does not establish caller authorization, deployed ACL/TLS or authority custody, gameplay admission, runtime activation, or end-to-end consumers. The later retained tenant/member replay proof is recorded in the later replay-proof paragraph below. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). + +At exact source head `50c22969698303ffdc6f3aab42d19dc499e47c5d`, the consolidated local full gate passed in 10m57s: 1,202 Account unit cases with four skips and 208 physical PostgreSQL/Redis integration cases with zero failures, errors, or skips, including the new 129 captured-head-loss/gap proof. This gate provides retained-source replay and fixture evidence for that exact head. It predates the subsequent projection republish/compare and bounded-page transport corrections. Their later local gate executed 1,207 unit cases with four skips and zero failures/errors, plus 208 physical PostgreSQL/Redis cases with zero skips; 206 passed, including all five delegation Redis cases for real commit-time publication and the 128+1 retained-page replay. The two `AccountAuthorityCurrentnessIntegrationTest` cases failed acquiring `localhost:53626` before Flyway migration (`SQLState 08001`, connection refused). Captured PostgreSQL logs show final TCP readiness before test startup and normal cleanup after the failures; the host-endpoint refusal cause remains unknown. The full local Account gate therefore failed despite the focused correction proof, and current published-head CI remains separate. At published source `1620a15e4a93461da5107aa940aaf41860f37cfd`, CI executed all 1,207 unit cases (four skips) and 208 physical integration cases with zero failures or errors; the Validation gate failed on a redundant-null-check static-analysis finding instead. The subsequent issuer-TTL and integer-transport corrections passed 1,210 unit cases (four skips), then a focused physical rerun passed all 21 cases across issuance persistence, response recovery and real delegation Redis, alongside Account/Common Security static, formatting and documentation checks (1m40s). That rerun was filtered; it does not claim a newer unfiltered 208-case pass. The earlier full local run of this correction batch passed 200 of 208 physical cases; the eight failures were the two Redis fixture mocks that lacked the exact issuer no-TTL stub, corrected before the focused rerun. Neither this source replay nor its fixture proof establishes deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, runtime activation, or authenticated full-owner physical composition. + +The retained-original-key rotation correction published at source `7dc4d3b7be0368c31b8a9924f34ebcc141f452cf` passed focused local proof on its matching postimages: 1,212 Account unit cases (four skips) and all five PostgreSQL/Redis cases, including retained-key acceptance and withdrawn-key denial without changing stored Redis bytes or expiry. Its [exact-head Validation run 38278570811](https://github.com/benhook1013/FireMUD/actions/runs/38278570811) passed all 208 physical Account integration cases without failures, errors or skips and 1,212 unit cases with four skips; those results belong to the named source, not to later review corrections. + +The missing-Account LOGIN path requires the supplied credential authority to perform equivalent-cost decoy verification before returning the unchanged credential denial. The source hook cannot grant authentication or create/consume challenge state. Concrete password/OTP composition and representative timing-parity proof remain absent; unit proof establishes invocation and denial only. + +The source-fence allocator intentionally locks one singleton row until the Account transaction commits. This preserves the current global source-fence contract and serializes first-time evidence capture across Accounts; signing and binding work in that transaction extend the lock duration. Representative throughput measurement and any canonical allocator redesign remain required before gameplay activation. This preparation does not change allocation semantics or claim a production throughput bound. + Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). ### Account signer/currentness storage evidence preparation @@ -107,7 +121,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [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) | [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) | [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. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [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) | [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) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller 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)). | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java new file mode 100644 index 0000000000..ee89e65b83 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java @@ -0,0 +1,809 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed canonical Account-owned {@code account-auth-evidence-bundle/v1} value for the explicitly + * non-tenant Game Session-to-Account delegation. + * + *

This codec validates shape and canonical bytes only. It does not establish that owner source + * rows, event history, cutoff applicability, or the caller are authentic/current. The DTO itself is + * never proof; the Account repository must derive and persist it only from locked owner readback. + */ +public final class AccountAuthEvidenceBundle { + public static final String SCHEMA = "account-auth-evidence-bundle/v1"; + // This profile-specific DTO cap remains 8 KiB within the generic envelope's larger bound. + public static final int MAX_CANONICAL_BYTES = 8 * 1024; + + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern UUID_TEXT = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern V4_UUID_TEXT = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]{0,18}"); + private static final Pattern POSITIVE_XID8 = Pattern.compile("[1-9][0-9]{0,19}"); + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "bundleRef", + "snapshotIdentity", + "evaluationIdentity", + "issuer", + "profile", + "audience", + "scope", + "operation", + "tokenIdentity", + "authorityTuple", + "issuanceFence", + "membershipVersion", + "authoritySourceVersions", + "accountIdentitySource", + "outboxCheckpoints"); + private static final Set BUNDLE_REF_FIELDS = + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"); + private static final Set SCOPE_FIELDS = Set.of("kind", "accountId", "tenantIds"); + private static final Set OPERATION_FIELDS = + Set.of( + "operationId", + "requestId", + "requestDigest", + "callerWorkload", + "callerContextId", + "accountId"); + private static final Set TOKEN_IDENTITY_FIELDS = + Set.of("jti", "tokenGeneration", "iat", "nbf", "exp"); + private static final Set AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set OPTIONAL_AUTHORITY_TUPLE_FIELDS = + Set.of("accountSecurityCutoff"); + private static final Set AUTHORITY_SOURCE_VERSION_FIELDS = + Set.of("issuerSourceVersion", "accountSourceVersion", "issuanceFenceSourceVersion"); + private static final Set ACCOUNT_IDENTITY_FIELDS = + Set.of("sourceRowId", "provenance", "sourceNumericId"); + private static final Set OUTBOX_CHECKPOINT_FIELDS = + Set.of("outboxStreamKey", "outboxSequence", "sourceEventId", "sourceEventDigest"); + private static final Set ZERO_OUTBOX_CHECKPOINT_FIELDS = + Set.of("outboxStreamKey", "outboxSequence"); + private static final Set ACCOUNT_SECURITY_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String PROFILE = GameSessionAccountDelegationProfile.PROFILE; + private static final String AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Map fields; + private final byte[] canonicalBytes; + + private AccountAuthEvidenceBundle(Map fields, byte[] canonicalBytes) { + this.fields = immutableMap(fields); + this.canonicalBytes = canonicalBytes.clone(); + } + + /** + * Encodes the supplied closed value. This factory is not an authenticity boundary; production + * persistence must derive the values from locked owner readback and independently compare all + * source rows and event payloads. + */ + public static AccountAuthEvidenceBundle fromOwnerEvaluation(OwnerEvaluation evaluation) { + Objects.requireNonNull(evaluation, "Account owner evaluation is required"); + Map fields = fields(evaluation); + validateFields(fields); + return canonicalValue(fields); + } + + /** Strictly parses the exact closed canonical bundle encoding. */ + public static AccountAuthEvidenceBundle parseCanonical(byte[] value) { + if (value == null || value.length == 0 || value.length > MAX_CANONICAL_BYTES) { + throw invalid("Account auth-evidence bundle is absent or exceeds its byte bound"); + } + String text = strictUtf8(value); + final Map parsed; + try { + parsed = JSON.readValue(text, new TypeReference<>() {}); + } catch (RuntimeException ex) { + throw invalid("Account auth-evidence bundle JSON is malformed"); + } + validateFields(parsed); + byte[] canonical = canonicalize(text); + if (!Arrays.equals(value, canonical)) { + throw invalid("Account auth-evidence bundle bytes are not canonical"); + } + return new AccountAuthEvidenceBundle(parsed, canonical); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** Lowercase SHA-256 digest of these exact canonical bytes. */ + public String canonicalSha256() { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(canonicalBytes)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable"); + } + } + + public Map fields() { + return immutableMap(fields); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof AccountAuthEvidenceBundle bundle + && Arrays.equals(canonicalBytes, bundle.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + @Override + public String toString() { + return "AccountAuthEvidenceBundle[redacted]"; + } + + private static Map fields(OwnerEvaluation evaluation) { + Map root = new LinkedHashMap<>(); + root.put("schema", SCHEMA); + Map ref = new LinkedHashMap<>(); + ref.put("bundleVersion", evaluation.bundleReference().bundleVersion()); + ref.put("sourceVersion", evaluation.bundleReference().sourceVersion()); + ref.put("sourceFence", evaluation.bundleReference().sourceFence()); + ref.put("linearization", evaluation.bundleReference().linearization()); + root.put("bundleRef", ref); + root.put("snapshotIdentity", evaluation.snapshotIdentity()); + root.put("evaluationIdentity", evaluation.evaluationIdentity()); + root.put("issuer", ISSUER); + root.put("profile", PROFILE); + root.put("audience", AUDIENCE); + + Map scope = new LinkedHashMap<>(); + scope.put("kind", "account"); + scope.put("accountId", evaluation.accountId().toString()); + scope.put("tenantIds", List.of()); + root.put("scope", scope); + + OperationIdentity operation = evaluation.operation(); + Map operationFields = new LinkedHashMap<>(); + operationFields.put("operationId", operation.operationId().toString()); + operationFields.put("requestId", operation.requestId().toString()); + operationFields.put("requestDigest", operation.requestDigest()); + operationFields.put("callerWorkload", operation.callerWorkload()); + operationFields.put("callerContextId", operation.callerContextId().toString()); + operationFields.put("accountId", operation.accountId().toString()); + root.put("operation", operationFields); + + TokenIdentity token = evaluation.token(); + Map tokenFields = new LinkedHashMap<>(); + tokenFields.put("jti", token.jti().toString()); + tokenFields.put("tokenGeneration", Long.toString(token.tokenGeneration())); + tokenFields.put("iat", token.issuedAtEpochSecond()); + tokenFields.put("nbf", token.notBeforeEpochSecond()); + tokenFields.put("exp", token.expiresAtEpochSecond()); + root.put("tokenIdentity", tokenFields); + + root.put("authorityTuple", deepCopyMap(evaluation.authorityTuple())); + root.put("issuanceFence", decimal(evaluation.issuanceFence())); + root.put("membershipVersion", Map.of()); + + AuthoritySourceVersions sourceVersions = evaluation.authoritySourceVersions(); + Map versions = new LinkedHashMap<>(); + versions.put("issuerSourceVersion", decimal(sourceVersions.issuerSourceVersion())); + versions.put("accountSourceVersion", decimal(sourceVersions.accountSourceVersion())); + versions.put( + "issuanceFenceSourceVersion", decimal(sourceVersions.issuanceFenceSourceVersion())); + root.put("authoritySourceVersions", versions); + + AccountIdentitySource accountSource = evaluation.accountIdentitySource(); + Map accountIdentity = new LinkedHashMap<>(); + accountIdentity.put("sourceRowId", decimal(accountSource.sourceRowId())); + accountIdentity.put("provenance", accountSource.provenance().name()); + accountIdentity.put("sourceNumericId", decimal(accountSource.sourceNumericId())); + root.put("accountIdentitySource", accountIdentity); + + List> checkpoints = new ArrayList<>(); + for (OutboxCheckpoint checkpoint : evaluation.outboxCheckpoints()) { + Map checkpointFields = new LinkedHashMap<>(); + checkpointFields.put("outboxStreamKey", checkpoint.outboxStreamKey()); + checkpointFields.put("outboxSequence", nonnegativeDecimal(checkpoint.outboxSequence())); + if (checkpoint.outboxSequence() > 0L) { + checkpointFields.put("sourceEventId", checkpoint.sourceEventId()); + checkpointFields.put("sourceEventDigest", checkpoint.sourceEventDigest()); + } + checkpoints.add(checkpointFields); + } + root.put("outboxCheckpoints", checkpoints); + return root; + } + + private static void validateFields(Map root) { + requireExactFields(root, ROOT_FIELDS, "bundle"); + requireText(root.get("schema"), SCHEMA, "schema"); + requireText(root.get("issuer"), ISSUER, "issuer"); + requireText(root.get("profile"), PROFILE, "profile"); + requireText(root.get("audience"), AUDIENCE, "audience"); + requireHash(root.get("snapshotIdentity"), "snapshotIdentity"); + requireHash(root.get("evaluationIdentity"), "evaluationIdentity"); + + Map ref = requireObject(root.get("bundleRef"), "bundleRef"); + requireExactFields(ref, BUNDLE_REF_FIELDS, "bundleRef"); + requirePositiveDecimal(ref.get("bundleVersion"), "bundleVersion"); + requirePositiveXid8(ref.get("sourceVersion"), "sourceVersion"); + requirePositiveDecimal(ref.get("sourceFence"), "sourceFence"); + requirePositiveXid8(ref.get("linearization"), "linearization"); + + Map scope = requireObject(root.get("scope"), "scope"); + requireExactFields(scope, SCOPE_FIELDS, "scope"); + requireText(scope.get("kind"), "account", "scope.kind"); + String accountId = requireUuid(scope.get("accountId"), "scope.accountId"); + requireEmptyList(scope.get("tenantIds"), "scope.tenantIds"); + + Map operation = requireObject(root.get("operation"), "operation"); + requireExactFields(operation, OPERATION_FIELDS, "operation"); + requireV4Uuid(operation.get("operationId"), "operation.operationId"); + requireV4Uuid(operation.get("requestId"), "operation.requestId"); + requireHash(operation.get("requestDigest"), "operation.requestDigest"); + String caller = + requireBoundedText(operation.get("callerWorkload"), "operation.callerWorkload", 256); + if (!GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(caller) + .matches()) { + throw invalid( + "Account auth-evidence bundle caller workload is not the exact Game Session peer"); + } + requireV4Uuid(operation.get("callerContextId"), "operation.callerContextId"); + if (!accountId.equals(requireUuid(operation.get("accountId"), "operation.accountId"))) { + throw invalid("Account auth-evidence bundle operation is scoped to another Account"); + } + + Map token = requireObject(root.get("tokenIdentity"), "tokenIdentity"); + requireExactFields(token, TOKEN_IDENTITY_FIELDS, "tokenIdentity"); + requireV4Uuid(token.get("jti"), "tokenIdentity.jti"); + long tokenGeneration = parsePositiveDecimal(token.get("tokenGeneration"), "tokenGeneration"); + long issuedAt = requirePositiveInteger(token.get("iat"), "iat"); + long notBefore = requirePositiveInteger(token.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(token.get("exp"), "exp"); + if (tokenGeneration != 1L + || notBefore > issuedAt + || expiresAt <= issuedAt + || expiresAt - issuedAt > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid("Account auth-evidence bundle token identity bounds are invalid"); + } + + Map tuple = requireObject(root.get("authorityTuple"), "authorityTuple"); + requireRequiredAndOptionalFields( + tuple, AUTHORITY_TUPLE_FIELDS, OPTIONAL_AUTHORITY_TUPLE_FIELDS, "authorityTuple"); + parsePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"); + parsePositiveDecimal(tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject(tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + requirePositiveDecimal(root.get("issuanceFence"), "issuanceFence"); + requireEmptyObject(root.get("membershipVersion"), "membershipVersion"); + + Map versions = + requireObject(root.get("authoritySourceVersions"), "authoritySourceVersions"); + requireExactFields(versions, AUTHORITY_SOURCE_VERSION_FIELDS, "authoritySourceVersions"); + for (String field : AUTHORITY_SOURCE_VERSION_FIELDS) { + requirePositiveDecimal(versions.get(field), field); + } + + Map identitySource = + requireObject(root.get("accountIdentitySource"), "accountIdentitySource"); + requireExactFields(identitySource, ACCOUNT_IDENTITY_FIELDS, "accountIdentitySource"); + long sourceRowId = parsePositiveDecimal(identitySource.get("sourceRowId"), "sourceRowId"); + long sourceNumericId = + parsePositiveDecimal(identitySource.get("sourceNumericId"), "sourceNumericId"); + if (sourceRowId != sourceNumericId) { + throw invalid("Account auth-evidence bundle Account source identity is contradictory"); + } + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue( + requireBoundedText(identitySource.get("provenance"), "provenance", 40)); + if (!AccountIdentityProvenance.isAccepted(provenance)) { + throw invalid("Account auth-evidence bundle Account provenance is not accepted"); + } + + List checkpoints = requireList(root.get("outboxCheckpoints"), "outboxCheckpoints"); + if (checkpoints.size() != 2) { + throw invalid("Account auth-evidence bundle requires exact issuer and Account checkpoints"); + } + String issuerStream = "account:auth-authority:v1:issuer/" + ISSUER; + String accountStream = "account:auth-authority:v1:account/" + accountId; + Map> byStream = new LinkedHashMap<>(); + for (Object item : checkpoints) { + Map checkpoint = requireObject(item, "outbox checkpoint"); + String stream = + requireBoundedText(checkpoint.get("outboxStreamKey"), "outboxStreamKey", 2048); + if (byStream.put(stream, checkpoint) != null) { + throw invalid("Account auth-evidence bundle has a duplicate outbox stream"); + } + long sequence = parseNonnegativeDecimal(checkpoint.get("outboxSequence"), "outboxSequence"); + if (sequence == 0L) { + requireExactFields(checkpoint, ZERO_OUTBOX_CHECKPOINT_FIELDS, "zero outbox baseline"); + } else { + requireExactFields(checkpoint, OUTBOX_CHECKPOINT_FIELDS, "positive outbox checkpoint"); + requireBoundedText(checkpoint.get("sourceEventId"), "sourceEventId", 512); + requireEventDigest(checkpoint.get("sourceEventDigest"), "sourceEventDigest"); + } + } + if (!byStream.keySet().equals(Set.of(issuerStream, accountStream))) { + throw invalid("Account auth-evidence bundle outbox checkpoint scope is not exact"); + } + List canonicalOrder = new ArrayList<>(byStream.keySet()); + canonicalOrder.sort(Comparator.naturalOrder()); + List suppliedOrder = new ArrayList<>(); + for (Object item : checkpoints) { + Map checkpoint = requireObject(item, "outbox checkpoint"); + suppliedOrder.add( + requireBoundedText(checkpoint.get("outboxStreamKey"), "outboxStreamKey", 2048)); + } + if (!canonicalOrder.equals(suppliedOrder)) { + throw invalid("Account auth-evidence bundle checkpoints are not in canonical stream order"); + } + if (tuple.containsKey("accountSecurityCutoff")) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "authorityTuple.accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + long cutoffGeneration = + parsePositiveDecimal( + cutoff.get("accountAuthorityGeneration"), + "authorityTuple.accountSecurityCutoff.accountAuthorityGeneration"); + requirePositiveDecimal( + cutoff.get("outboxSequence"), "authorityTuple.accountSecurityCutoff.outboxSequence"); + String cutoffStream = + requireBoundedText( + cutoff.get("outboxStreamKey"), + "authorityTuple.accountSecurityCutoff.outboxStreamKey", + 2048); + if (!accountStream.equals(cutoffStream) + || cutoffGeneration + != parsePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration")) { + throw invalid("Account auth-evidence security cutoff is outside the exact Account scope"); + } + Map accountCheckpoint = byStream.get(accountStream); + if (parseNonnegativeDecimal( + accountCheckpoint.get("outboxSequence"), "account outbox sequence") + < parsePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence")) { + throw invalid("Account auth-evidence checkpoint does not cover the security cutoff"); + } + } + if (!accountId.equals(requireUuid(scope.get("accountId"), "scope.accountId"))) { + throw invalid("Account auth-evidence bundle Account scope is inconsistent"); + } + } + + private static AccountAuthEvidenceBundle canonicalValue(Map fields) { + try { + String json = JSON.writeValueAsString(fields); + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) { + throw invalid("Account auth-evidence bundle exceeds its canonical byte bound"); + } + return new AccountAuthEvidenceBundle(fields, bytes); + } catch (IOException | RuntimeException ex) { + if (ex instanceof InvalidBundleException invalid) throw invalid; + throw invalid("Account auth-evidence bundle canonicalization failed"); + } + } + + private static Map immutableMap(Map input) { + return Collections.unmodifiableMap(deepCopyMap(input)); + } + + private static Map deepCopyMap(Map input) { + Map copy = new LinkedHashMap<>(); + for (Map.Entry entry : input.entrySet()) { + Object value = entry.getValue(); + if (value == null) throw invalid("Account auth-evidence bundle contains null"); + if (value instanceof Map map) { + Map child = new LinkedHashMap<>(); + for (Map.Entry item : map.entrySet()) { + if (!(item.getKey() instanceof String key)) { + throw invalid("Account auth-evidence bundle object key is not text"); + } + child.put(key, item.getValue()); + } + copy.put(entry.getKey(), immutableMap(child)); + } else if (value instanceof List list) { + List child = new ArrayList<>(list.size()); + for (Object item : list) { + if (item == null) throw invalid("Account auth-evidence bundle contains null"); + if (item instanceof Map map) { + Map nested = new LinkedHashMap<>(); + for (Map.Entry nestedItem : map.entrySet()) { + if (!(nestedItem.getKey() instanceof String key)) { + throw invalid("Account auth-evidence bundle object key is not text"); + } + nested.put(key, nestedItem.getValue()); + } + child.add(immutableMap(nested)); + } else { + child.add(item); + } + } + copy.put(entry.getKey(), List.copyOf(child)); + } else { + copy.put(entry.getKey(), value); + } + } + return copy; + } + + private static Map requireObject(Object value, String field) { + if (!(value instanceof Map input)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : input.entrySet()) { + if (!(entry.getKey() instanceof String key) || entry.getValue() == null) { + throw invalid(field + " has a non-text key or null value"); + } + result.put(key, entry.getValue()); + } + return result; + } + + private static List requireList(Object value, String field) { + if (!(value instanceof List list)) throw invalid(field + " must be an array"); + return list; + } + + private static void requireExactFields( + Map value, Set expected, String field) { + if (!value.keySet().equals(expected) || value.values().stream().anyMatch(Objects::isNull)) { + throw invalid(field + " has missing, unknown, or null fields"); + } + } + + private static void requireRequiredAndOptionalFields( + Map value, Set required, Set optional, String field) { + if (!value.keySet().containsAll(required) + || !union(required, optional).containsAll(value.keySet()) + || value.values().stream().anyMatch(Objects::isNull)) { + throw invalid(field + " has missing, unknown, or null fields"); + } + } + + private static Set union(Set required, Set optional) { + java.util.HashSet values = new java.util.HashSet<>(required); + values.addAll(optional); + return Set.copyOf(values); + } + + private static void requireText(Object value, String expected, String field) { + if (!(value instanceof String text) || !text.equals(expected)) { + throw invalid(field + " is not the exact Account delegation value"); + } + } + + private static String requireBoundedText(Object value, String field, int maxLength) { + if (!(value instanceof String text) + || text.isEmpty() + || text.length() > maxLength + || !text.equals(text.strip()) + || text.chars().anyMatch(Character::isISOControl)) { + throw invalid(field + " is absent, unbounded, or malformed"); + } + return text; + } + + private static String requireUuid(Object value, String field) { + String text = requireBoundedText(value, field, 36); + if (!UUID_TEXT.matcher(text).matches()) throw invalid(field + " is not a canonical UUID"); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " is not a nonzero canonical UUID"); + } + } catch (IllegalArgumentException ex) { + throw invalid(field + " is not a canonical UUID"); + } + return text; + } + + private static void requireHash(Object value, String field) { + if (!(value instanceof String text) || !SHA256.matcher(text).matches()) { + throw invalid(field + " must be lowercase SHA-256 hex"); + } + } + + private static void requireEventDigest(Object value, String field) { + if (!(value instanceof String text) || !EVENT_DIGEST.matcher(text).matches()) { + throw invalid(field + " must be a canonical Account event digest"); + } + } + + private static String requireV4Uuid(Object value, String field) { + String text = requireBoundedText(value, field, 36); + if (!V4_UUID_TEXT.matcher(text).matches()) { + throw invalid(field + " is not a canonical high-entropy UUID"); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " is not a nonzero canonical UUID"); + } + } catch (IllegalArgumentException ex) { + throw invalid(field + " is not a canonical UUID"); + } + return text; + } + + private static long requirePositiveInteger(Object value, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be a JSON integer"); + String text = number.toString(); + if (!POSITIVE_DECIMAL.matcher(text).matches()) + throw invalid(field + " is not a canonical integer"); + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw invalid(field + " is outside the supported bound"); + } + } + + private static void requirePositiveDecimal(Object value, String field) { + parsePositiveDecimal(value, field); + } + + private static long parsePositiveDecimal(Object value, String field) { + if (!(value instanceof String text) || !POSITIVE_DECIMAL.matcher(text).matches()) { + throw invalid(field + " must be a canonical positive decimal string"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw invalid(field + " is outside the supported bound"); + } + } + + private static long parseNonnegativeDecimal(Object value, String field) { + if (!(value instanceof String text) || !NONNEGATIVE_DECIMAL.matcher(text).matches()) { + throw invalid(field + " must be a canonical non-negative decimal string"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw invalid(field + " is outside the supported bound"); + } + } + + private static void requirePositiveXid8(Object value, String field) { + if (!(value instanceof String text) || !POSITIVE_XID8.matcher(text).matches()) { + throw invalid(field + " must be a positive canonical xid8 decimal string"); + } + BigInteger xact = new BigInteger(text); + if (xact.signum() <= 0 || xact.bitLength() > 64) { + throw invalid(field + " is outside the PostgreSQL xid8 bound"); + } + } + + private static String decimal(long value) { + if (value <= 0L) throw invalid("Account auth-evidence bundle counter must be positive"); + return Long.toString(value); + } + + private static String nonnegativeDecimal(long value) { + if (value < 0L) throw invalid("Account auth-evidence checkpoint cannot be negative"); + return Long.toString(value); + } + + private static void requireEmptyObject(Object value, String field) { + Map object = requireObject(value, field); + if (!object.isEmpty()) throw invalid(field + " must be an empty object for this profile"); + } + + private static void requireEmptyList(Object value, String field) { + if (!(value instanceof List list) || !list.isEmpty()) { + throw invalid(field + " must be an empty array for this profile"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw invalid("Account auth-evidence bundle is not valid UTF-8"); + } + } + + private static byte[] canonicalize(String value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(value); + } catch (IOException | RuntimeException ex) { + throw invalid("Account auth-evidence bundle canonicalization failed"); + } + } + + private static InvalidBundleException invalid(String message) { + return new InvalidBundleException(message); + } + + /** Values captured from locked Account source rows; this record itself is not authority. */ + public record OwnerEvaluation( + BundleReference bundleReference, + String snapshotIdentity, + String evaluationIdentity, + UUID accountId, + OperationIdentity operation, + TokenIdentity token, + Map authorityTuple, + long issuanceFence, + AuthoritySourceVersions authoritySourceVersions, + AccountIdentitySource accountIdentitySource, + List outboxCheckpoints) { + public OwnerEvaluation { + Objects.requireNonNull(bundleReference, "Bundle reference is required"); + requireHash(snapshotIdentity, "snapshotIdentity"); + requireHash(evaluationIdentity, "evaluationIdentity"); + Objects.requireNonNull(accountId, "Account ID is required"); + if (issuanceFence <= 0L) { + throw invalid("Account issuance fence must be positive"); + } + Objects.requireNonNull(operation, "Operation identity is required"); + Objects.requireNonNull(token, "Token identity is required"); + authorityTuple = immutableMap(authorityTuple); + Objects.requireNonNull(authoritySourceVersions, "Authority source versions are required"); + Objects.requireNonNull(accountIdentitySource, "Account identity source is required"); + outboxCheckpoints = List.copyOf(outboxCheckpoints); + if (outboxCheckpoints.stream().anyMatch(Objects::isNull)) { + throw invalid("Account auth-evidence bundle has a null outbox checkpoint"); + } + if (!accountId.equals(operation.accountId())) { + throw invalid("Account auth-evidence bundle operation scope is contradictory"); + } + } + + @Override + public Map authorityTuple() { + return immutableMap(authorityTuple); + } + } + + public record BundleReference( + String bundleVersion, String sourceVersion, String sourceFence, String linearization) { + public BundleReference { + requirePositiveDecimal(bundleVersion, "bundleVersion"); + requirePositiveXid8(sourceVersion, "sourceVersion"); + requirePositiveDecimal(sourceFence, "sourceFence"); + requirePositiveXid8(linearization, "linearization"); + } + } + + public record OperationIdentity( + UUID operationId, + UUID requestId, + String requestDigest, + String callerWorkload, + UUID callerContextId, + UUID accountId) { + public OperationIdentity { + requireV4Uuid(operationId == null ? null : operationId.toString(), "operationId"); + requireV4Uuid(requestId == null ? null : requestId.toString(), "requestId"); + requireHash(requestDigest, "requestDigest"); + if (callerWorkload == null + || !GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(callerWorkload) + .matches()) { + throw invalid("Account auth-evidence caller is not the exact Game Session workload"); + } + requireV4Uuid(callerContextId == null ? null : callerContextId.toString(), "callerContextId"); + requireUuid(accountId == null ? null : accountId.toString(), "accountId"); + } + } + + public record TokenIdentity( + UUID jti, + long tokenGeneration, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + public TokenIdentity { + requireV4Uuid(jti == null ? null : jti.toString(), "jti"); + if (tokenGeneration != 1L + || issuedAtEpochSecond <= 0L + || notBeforeEpochSecond <= 0L + || notBeforeEpochSecond > issuedAtEpochSecond + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid("Account auth-evidence token identity is invalid"); + } + } + } + + public record AuthoritySourceVersions( + long issuerSourceVersion, long accountSourceVersion, long issuanceFenceSourceVersion) { + public AuthoritySourceVersions { + if (issuerSourceVersion <= 0L + || accountSourceVersion <= 0L + || issuanceFenceSourceVersion <= 0L) { + throw invalid("Account authority source versions must be positive"); + } + } + } + + public record AccountIdentitySource( + long sourceRowId, AccountIdentityProvenance provenance, long sourceNumericId) { + public AccountIdentitySource { + if (sourceRowId <= 0L || sourceNumericId != sourceRowId) { + throw invalid("Account UUID source row identity is contradictory"); + } + Objects.requireNonNull(provenance, "Account UUID provenance is required"); + if (!AccountIdentityProvenance.isAccepted(provenance)) { + throw invalid("Account UUID provenance is not accepted"); + } + } + } + + public record OutboxCheckpoint( + String outboxStreamKey, long outboxSequence, String sourceEventId, String sourceEventDigest) { + public OutboxCheckpoint { + if (outboxStreamKey == null || outboxStreamKey.isBlank() || outboxStreamKey.length() > 2048) { + throw invalid("Account authority outbox stream key is invalid"); + } + if (outboxSequence < 0L) { + throw invalid("Account outbox checkpoint sequence cannot be negative"); + } + if (outboxSequence == 0L) { + if (sourceEventId != null || sourceEventDigest != null) { + throw invalid("An explicit zero baseline cannot claim an event identity"); + } + } else { + if (sourceEventId == null || sourceEventId.isBlank() || sourceEventId.length() > 512) { + throw invalid("Account outbox checkpoint event ID is invalid"); + } + requireEventDigest(sourceEventDigest, "sourceEventDigest"); + } + } + } + + public static final class InvalidBundleException extends IllegalArgumentException { + public InvalidBundleException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java new file mode 100644 index 0000000000..4f228b4732 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; + +/** Account SQL token identity and monotonic fence; contains no credential or registry assertion. */ +public record AccountGameplayTokenIdentityFence( + TokenIdentity identity, + long tokenIdentityFence, + State state, + UUID revocationRequestId, + String revocationDigest) { + public AccountGameplayTokenIdentityFence { + Objects.requireNonNull(identity); + Objects.requireNonNull(state); + if (tokenIdentityFence <= 0L) + throw new IllegalArgumentException("Positive token fence required"); + if (state == State.ACTIVE) { + if (tokenIdentityFence != 1L || revocationRequestId != null || revocationDigest != null) { + throw new IllegalArgumentException("Initial active fence is malformed"); + } + } else { + requireUuid(revocationRequestId); + requireDigest(revocationDigest); + if (tokenIdentityFence != (state == State.PENDING ? 2L : 3L)) { + throw new IllegalArgumentException("Revocation fence is malformed"); + } + } + } + + public enum State { + ACTIVE, + PENDING, + COMMITTED + } + + /** Exact immutable Account COMMITTED issuance identity, never reconstructed from Redis. */ + public record TokenIdentity( + UUID accountId, + UUID operationId, + UUID issuanceRequestId, + String tokenSha256, + UUID tokenJti, + long notBeforeEpochSecond, + long tokenGeneration, + long issuanceFence) { + public TokenIdentity { + requireUuid(accountId); + requireUuid(operationId); + requireUuid(issuanceRequestId); + requireUuid(tokenJti); + requireDigest(tokenSha256); + if (notBeforeEpochSecond <= 0L || tokenGeneration <= 0L || issuanceFence <= 0L) { + throw new IllegalArgumentException("Positive exact token identity metadata required"); + } + } + + @Override + public String toString() { + return "TokenIdentity[redacted]"; + } + } + + private static void requireUuid(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Canonical UUIDv4 required"); + } + } + + private static void requireDigest(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical SHA-256 required"); + } + } + + @Override + public String toString() { + return "AccountGameplayTokenIdentityFence[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalGameplayLoginRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalGameplayLoginRequest.java new file mode 100644 index 0000000000..d15d053913 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalGameplayLoginRequest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; + +/** + * Transient canonical LOGIN input. The credential is never persisted or rendered in diagnostics. + */ +public record CanonicalGameplayLoginRequest( + UUID requestId, + String email, + String credential, + GameplayCredentialSourceContext sourceContext) { + public CanonicalGameplayLoginRequest { + if (requestId == null || requestId.version() != 4 || requestId.variant() != 2) { + throw new IllegalArgumentException("A high-entropy gameplay LOGIN request ID is required"); + } + Objects.requireNonNull(email, "Email is required"); + Objects.requireNonNull(credential, "Credential is required"); + if (email.length() > 320 || credential.length() > 1024) { + throw new IllegalArgumentException("Gameplay LOGIN input exceeds its finite bound"); + } + Objects.requireNonNull(sourceContext, "Typed pre-auth source context is required"); + } + + @Override + public String toString() { + return "CanonicalGameplayLoginRequest[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/GameplayCredentialSourceContext.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/GameplayCredentialSourceContext.java new file mode 100644 index 0000000000..06adc8b93a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/GameplayCredentialSourceContext.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** Typed, Game Session-attested source context bound to one pre-auth socket attempt. */ +public record GameplayCredentialSourceContext( + UUID contextId, String canonicalClientAddress, String transportClass) { + public GameplayCredentialSourceContext { + if (contextId == null || contextId.version() != 4 || contextId.variant() != 2) { + throw new IllegalArgumentException("A high-entropy pre-auth context ID is required"); + } + requireBoundedText(canonicalClientAddress, 256, "Canonical client address"); + requireBoundedText(transportClass, 64, "Transport class"); + } + + private static void requireBoundedText(String value, int maxLength, String field) { + if (value == null + || value.isBlank() + || value.length() > maxLength + || !value.equals(value.trim()) + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(field + " is malformed"); + } + } + + @Override + public String toString() { + return "GameplayCredentialSourceContext[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResult.java new file mode 100644 index 0000000000..247b88bd02 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResult.java @@ -0,0 +1,259 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import tools.jackson.databind.json.JsonMapper; + +/** Exact recovered gameplay LOGIN credential and Account metadata; never a gameplay binding. */ +public final class InitialGameplayLoginResult { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final RecoveredCredential credential; + private final UUID requestId; + private final UUID callerContextId; + private final String tokenGeneration; + private final String issuanceFence; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final byte[] authorityTupleCanonicalJson; + private final byte[] outboxCheckpointsCanonicalJson; + private final byte[] outboxSourceEventEvidenceCanonicalJson; + + private InitialGameplayLoginResult( + RecoveredCredential credential, + UUID requestId, + UUID callerContextId, + String tokenGeneration, + String issuanceFence, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + byte[] authorityTupleCanonicalJson, + byte[] outboxCheckpointsCanonicalJson, + byte[] outboxSourceEventEvidenceCanonicalJson) { + this.credential = credential; + this.requestId = requestId; + this.callerContextId = callerContextId; + this.tokenGeneration = tokenGeneration; + this.issuanceFence = issuanceFence; + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.notBeforeEpochSecond = notBeforeEpochSecond; + this.authorityTupleCanonicalJson = authorityTupleCanonicalJson.clone(); + this.outboxCheckpointsCanonicalJson = outboxCheckpointsCanonicalJson.clone(); + this.outboxSourceEventEvidenceCanonicalJson = outboxSourceEventEvidenceCanonicalJson.clone(); + } + + /** Wraps only a credential privately created by the verified Account response-recovery owner. */ + public static InitialGameplayLoginResult fromRecoveredCredential(RecoveredCredential credential) { + Objects.requireNonNull(credential, "Verified recovered credential is required"); + AccountAuthEvidenceBundle bundle = + Objects.requireNonNull( + credential.authEvidenceBundle(), "Verified Account auth-evidence bundle is required"); + Map fields = bundle.fields(); + Map operation = object(fields.get("operation"), "operation"); + Map token = object(fields.get("tokenIdentity"), "tokenIdentity"); + Map authorityTuple = object(fields.get("authorityTuple"), "authorityTuple"); + + UUID requestId = v4Uuid(operation.get("requestId"), "requestId"); + UUID callerContextId = v4Uuid(operation.get("callerContextId"), "callerContextId"); + UUID accountId = uuid(operation.get("accountId"), "operation.accountId"); + UUID tokenJti = v4Uuid(token.get("jti"), "tokenIdentity.jti"); + String tokenGeneration = positiveDecimal(token.get("tokenGeneration"), "tokenGeneration"); + String issuanceFence = positiveDecimal(fields.get("issuanceFence"), "issuanceFence"); + long issuedAt = positiveInteger(token.get("iat"), "iat"); + long notBefore = positiveInteger(token.get("nbf"), "nbf"); + long expiresAt = positiveInteger(token.get("exp"), "exp"); + + if (!accountId.equals(credential.accountId()) + || !tokenJti.equals(credential.tokenJti()) + || !GameSessionAccountDelegationProfile.PROFILE.equals(credential.profile()) + || expiresAt != credential.expiresAtEpochSecond() + || credential.tokenSha256() == null + || !SHA256.matcher(credential.tokenSha256()).matches() + || notBefore > issuedAt + || issuedAt >= expiresAt) { + throw invalidAggregate(); + } + + List checkpoints = list(fields.get("outboxCheckpoints"), "outboxCheckpoints"); + List> checkpointPairs = new ArrayList<>(checkpoints.size()); + List> sourceEvents = new ArrayList<>(checkpoints.size()); + for (Object value : checkpoints) { + Map checkpoint = object(value, "outbox checkpoint"); + String streamKey = text(checkpoint.get("outboxStreamKey"), "outboxStreamKey"); + String sequence = nonnegativeDecimal(checkpoint.get("outboxSequence"), "outboxSequence"); + Map pair = new LinkedHashMap<>(); + pair.put("outboxStreamKey", streamKey); + pair.put("outboxSequence", sequence); + checkpointPairs.add(Map.copyOf(pair)); + if (!"0".equals(sequence)) { + sourceEvents.add(checkpoint); + } + } + + return new InitialGameplayLoginResult( + credential, + requestId, + callerContextId, + tokenGeneration, + issuanceFence, + issuedAt, + notBefore, + canonicalJson(authorityTuple), + canonicalJson(checkpointPairs), + canonicalJson(sourceEvents)); + } + + public byte[] compactJwtBytes() { + return credential.compactJwtBytes(); + } + + public UUID accountId() { + return credential.accountId(); + } + + public UUID tokenJti() { + return credential.tokenJti(); + } + + public String tokenSha256() { + return credential.tokenSha256(); + } + + public String profile() { + return credential.profile(); + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + public long expiresAtEpochSecond() { + return credential.expiresAtEpochSecond(); + } + + public String tokenGeneration() { + return tokenGeneration; + } + + public String issuanceFence() { + return issuanceFence; + } + + /** Immutable original operation identity, projected from the stored Account evidence bundle. */ + public UUID requestId() { + return requestId; + } + + /** Immutable original caller context, projected from the stored Account evidence bundle. */ + public UUID callerContextId() { + return callerContextId; + } + + public byte[] authorityTupleCanonicalJson() { + return authorityTupleCanonicalJson.clone(); + } + + /** Ordered stream/sequence pairs include explicit zero baselines and omit event payloads. */ + public byte[] outboxCheckpointsCanonicalJson() { + return outboxCheckpointsCanonicalJson.clone(); + } + + /** Ordered positive source events only; zero baselines are not event evidence. */ + public byte[] outboxSourceEventEvidenceCanonicalJson() { + return outboxSourceEventEvidenceCanonicalJson.clone(); + } + + @Override + public String toString() { + return "InitialGameplayLoginResult[redacted, non-admitting]"; + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException failure) { + throw invalidAggregate(); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map map)) throw invalidAggregate(); + return map; + } + + private static List list(Object value, String field) { + if (!(value instanceof List list)) throw invalidAggregate(); + return list; + } + + private static UUID uuid(Object value, String field) { + String text = text(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.equals(new UUID(0L, 0L)) + || parsed.variant() != 2) { + throw invalidAggregate(); + } + return parsed; + } catch (IllegalArgumentException failure) { + throw invalidAggregate(); + } + } + + private static UUID v4Uuid(Object value, String field) { + UUID parsed = uuid(value, field); + if (parsed.version() != 4) throw invalidAggregate(); + return parsed; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank()) throw invalidAggregate(); + return text; + } + + private static String positiveDecimal(Object value, String field) { + String text = text(value, field); + if (!POSITIVE_DECIMAL.matcher(text).matches()) throw invalidAggregate(); + return text; + } + + private static String nonnegativeDecimal(Object value, String field) { + String text = text(value, field); + if (!"0".equals(text) && !POSITIVE_DECIMAL.matcher(text).matches()) { + throw invalidAggregate(); + } + return text; + } + + private static long positiveInteger(Object value, String field) { + if (!(value instanceof Number number)) throw invalidAggregate(); + try { + long parsed = new BigDecimal(number.toString()).longValueExact(); + if (parsed <= 0L) throw invalidAggregate(); + return parsed; + } catch (ArithmeticException | NumberFormatException failure) { + throw invalidAggregate(); + } + } + + private static IllegalArgumentException invalidAggregate() { + return new IllegalArgumentException("Recovered gameplay LOGIN metadata is inconsistent"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java new file mode 100644 index 0000000000..e05fa9e804 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java @@ -0,0 +1,681 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-local persistence boundary for immutable, non-authorizing delegation evidence bundles. + * + *

Capture consumes the Account-owned, codec-verified issuer/account source snapshot in the same + * transaction as the locked PENDING operation. It never accepts caller-supplied bundle bytes or + * synthesizes an empty checkpoint. The source repository proves a zero checkpoint only from its + * exact fresh-initialization provenance and exhaustive empty history; retained or ambiguous history + * fails closed. + */ +public class AccountAuthEvidenceBundleRepository { + private static final String ISSUER_STREAM = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + private static final String OPERATION_TABLE = "account_gameplay_delegation_issuance_operations"; + private static final String BUNDLE_TABLE = "account_gameplay_delegation_auth_evidence_bundles"; + private static final Pattern V4_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountAuthorityGenerationRepository authorityGenerations; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountAuthEvidenceBundleRepository( + DSLContext dsl, + AccountAuthorityGenerationRepository authorityGenerations, + AccountAuthorityOutboxRepository authorityOutbox) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.authorityGenerations = + Objects.requireNonNull(authorityGenerations, "Account authority repository is required"); + Objects.requireNonNull(authorityOutbox, "Account authority outbox is required"); + this.sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, authorityGenerations, authorityOutbox); + } + + /** + * Captures and immutably persists source evidence for the exact Account-owned PENDING row. Caller + * data supplies only the lookup identity; every value in the bundle is read from locked Account + * operation, identity, authority, source, and retained-event rows. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountAuthEvidenceBundle captureAndPersist(UUID requestId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + // This first read only discovers immutable row identity. It does not authorize capture or lock + // the operation before the Account and composite authority rows. + Record preliminary = + dsl.fetchOne( + "SELECT operation_id, request_id, account_uuid FROM " + + OPERATION_TABLE + + " WHERE request_id = ?", + requestId); + if (preliminary == null) throw new OperationNotFoundException(); + UUID preliminaryRequestId = preliminary.get("request_id", UUID.class); + UUID preliminaryOperationId = preliminary.get("operation_id", UUID.class); + UUID preliminaryAccountId = preliminary.get("account_uuid", UUID.class); + if (!requestId.equals(preliminaryRequestId) + || !canonicalV4(preliminaryOperationId) + || preliminaryAccountId == null) { + throw new OwnerEvidenceUnavailableException(); + } + + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id " + + "FROM accounts WHERE account_uuid = ? FOR SHARE", + preliminaryAccountId); + if (account == null) throw new OwnerEvidenceUnavailableException(); + long rowId = positive(account.get("id", Long.class)); + long sourceId = positive(account.get("account_uuid_source_numeric_id", Long.class)); + AccountIdentityProvenance provenance; + try { + provenance = + AccountIdentityProvenance.fromStorageValue( + account.get("account_uuid_provenance", String.class)); + } catch (RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + if (!preliminaryAccountId.equals(account.get("account_uuid", UUID.class)) + || rowId != sourceId + || !AccountIdentityProvenance.isAccepted(provenance)) { + throw new OwnerEvidenceUnavailableException(); + } + + CompositeSnapshot current = + authorityGenerations.readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, preliminaryAccountId, List.of(), List.of()); + + // Re-read and lock the operation only after the Account and authority snapshot are locked. + // Every identity/status/authority field is checked again; the preliminary lookup is never + // evidence for capture. + Record operation = + dsl.fetchOne( + "SELECT * FROM " + OPERATION_TABLE + " WHERE request_id = ? FOR UPDATE", requestId); + if (operation == null) throw new OwnerEvidenceUnavailableException(); + UUID storedRequestId = operation.get("request_id", UUID.class); + UUID operationId = operation.get("operation_id", UUID.class); + UUID accountId = operation.get("account_uuid", UUID.class); + UUID callerContextId = operation.get("caller_context_id", UUID.class); + UUID tokenJti = operation.get("token_jti", UUID.class); + String requestDigest = operation.get("request_digest", String.class); + String callerWorkload = operation.get("caller_workload", String.class); + if (!requestId.equals(storedRequestId) + || !requestId.equals(preliminaryRequestId) + || !preliminaryOperationId.equals(operationId) + || !preliminaryAccountId.equals(accountId) + || !canonicalV4(operationId) + || !canonicalV4(callerContextId) + || !canonicalV4(tokenJti) + || requestDigest == null + || !SHA256.matcher(requestDigest).matches() + || !"PENDING".equals(operation.get("status", String.class)) + || callerWorkload == null + || !GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(callerWorkload) + .matches()) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactPendingAuthority(operation, current, accountId); + final IssuerAccountSourceSnapshot sources; + try { + sources = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + } catch (RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactSourceSnapshot(sources, current, operation, account, accountId); + + Record prior = + dsl.fetchOne( + "SELECT operation_id FROM " + BUNDLE_TABLE + " WHERE operation_id = ?", operationId); + if (prior != null) { + AccountAuthEvidenceBundle stored = readStoredNonAuthorizingValue(operationId); + AccountAuthEvidenceBundle expected = + makeBundle(operation, account, sources, storedBundleReference(stored)); + if (!MessageDigest.isEqual(expected.canonicalBytes(), stored.canonicalBytes())) { + throw new OwnerEvidenceUnavailableException(); + } + return stored; + } + + String transactionId = currentTransactionId(); + String sourceFence = allocateSourceFence(operationId, transactionId); + AccountAuthEvidenceBundle.BundleReference bundleReference = + new AccountAuthEvidenceBundle.BundleReference( + "1", transactionId, sourceFence, transactionId); + AccountAuthEvidenceBundle candidate = makeBundle(operation, account, sources, bundleReference); + int inserted = + dsl.execute( + "INSERT INTO " + + BUNDLE_TABLE + + " (operation_id, request_id, account_uuid, bundle_schema, bundle_version, " + + "source_version, source_fence, issuance_fence, linearization, canonical_sha256, " + + "canonical_bundle_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT DO NOTHING", + operationId, + requestId, + accountId, + AccountAuthEvidenceBundle.SCHEMA, + bundleReference.bundleVersion(), + bundleReference.sourceVersion(), + bundleReference.sourceFence(), + Long.toString(sources.issuanceFence().value()), + bundleReference.linearization(), + candidate.canonicalSha256(), + candidate.canonicalBytes()); + AccountAuthEvidenceBundle readback = readStoredNonAuthorizingValue(operationId); + if (inserted != 1 + || !MessageDigest.isEqual(candidate.canonicalBytes(), readback.canonicalBytes())) { + throw new OwnerEvidenceUnavailableException(); + } + return readback; + } + + /** + * Returns a strictly parsed immutable value for diagnostics/reconciliation only; this method does + * not revalidate or grant source freshness, promotion, activation, or caller authority. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountAuthEvidenceBundle readStoredNonAuthorizingValue(UUID operationId) { + Objects.requireNonNull(operationId, "Operation ID is required"); + Record row = + dsl.fetchOne( + "SELECT operation_id, request_id, account_uuid, bundle_schema, canonical_sha256, " + + "bundle_version, source_version, source_fence, issuance_fence, linearization, " + + "canonical_bundle_bytes FROM " + + BUNDLE_TABLE + + " WHERE operation_id = ?", + operationId); + if (row == null) throw new StoredBundleUnavailableException(); + try { + if (!operationId.equals(row.get("operation_id", UUID.class))) { + throw new StoredBundleUnavailableException(); + } + AccountAuthEvidenceBundle bundle = + AccountAuthEvidenceBundle.parseCanonical(row.get("canonical_bundle_bytes", byte[].class)); + String digest = row.get("canonical_sha256", String.class); + if (!MessageDigest.isEqual( + bundle.canonicalSha256().getBytes(StandardCharsets.US_ASCII), + Objects.toString(digest, "").getBytes(StandardCharsets.US_ASCII)) + || !AccountAuthEvidenceBundle.SCHEMA.equals(row.get("bundle_schema", String.class)) + || !Objects.equals( + operationId.toString(), nestedText(bundle.fields(), "operation", "operationId")) + || !Objects.equals( + row.get("request_id", UUID.class).toString(), + nestedText(bundle.fields(), "operation", "requestId")) + || !Objects.equals( + row.get("account_uuid", UUID.class).toString(), + nestedText(bundle.fields(), "scope", "accountId")) + || !Objects.equals( + row.get("bundle_version", String.class), + nestedText(bundle.fields(), "bundleRef", "bundleVersion")) + || !Objects.equals( + row.get("source_version", String.class), + nestedText(bundle.fields(), "bundleRef", "sourceVersion")) + || !Objects.equals( + row.get("source_fence", String.class), + nestedText(bundle.fields(), "bundleRef", "sourceFence")) + || !Objects.equals( + row.get("issuance_fence", String.class), + Objects.toString(bundle.fields().get("issuanceFence"), null)) + || !Objects.equals( + row.get("linearization", String.class), + nestedText(bundle.fields(), "bundleRef", "linearization"))) { + throw new StoredBundleUnavailableException(); + } + return bundle; + } catch (RuntimeException ex) { + if (ex instanceof StoredBundleUnavailableException unavailable) throw unavailable; + throw new StoredBundleUnavailableException(); + } + } + + private static void requireExactPendingAuthority( + Record operation, CompositeSnapshot snapshot, UUID accountId) { + if (snapshot.account().scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ACCOUNT + || !accountId.equals(snapshot.account().scope().accountId()) + || snapshot.account().scope().issuerId() != null + || snapshot.account().scope().tenantId() != null + || snapshot.issuer().scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ISSUER + || !GameSessionAccountDelegationProfile.ISSUER.equals(snapshot.issuer().scope().issuerId()) + || snapshot.issuer().scope().accountId() != null + || snapshot.issuer().scope().tenantId() != null + || !snapshot.tenants().isEmpty() + || !snapshot.memberships().isEmpty() + || !Objects.equals( + operation.get("authority_issuer_generation", Long.class), + snapshot.issuer().generation()) + || !Objects.equals( + operation.get("authority_issuer_source_version", Long.class), + snapshot.issuer().sourceVersion()) + || !Objects.equals( + operation.get("authority_account_generation", Long.class), + snapshot.account().generation()) + || !Objects.equals( + operation.get("authority_account_source_version", Long.class), + snapshot.account().sourceVersion()) + || !Objects.equals( + operation.get("issuance_fence", Long.class), snapshot.issuanceFence().value()) + || !Objects.equals( + operation.get("issuance_fence_source_version", Long.class), + snapshot.issuanceFence().sourceVersion()) + || !accountId.equals(snapshot.issuanceFence().accountId())) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static void requireExactSourceSnapshot( + IssuerAccountSourceSnapshot sources, + CompositeSnapshot current, + Record operation, + Record account, + UUID accountId) { + CurrentSourceEvidence issuer = sources.issuer(); + CurrentSourceEvidence accountSource = sources.account(); + String accountStream = "account:auth-authority:v1:account/" + accountId; + if (issuer.scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ISSUER + || !GameSessionAccountDelegationProfile.ISSUER.equals(issuer.scope().issuerId()) + || issuer.scope().accountId() != null + || issuer.scope().tenantId() != null + || accountSource.scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ACCOUNT + || !accountId.equals(accountSource.scope().accountId()) + || accountSource.scope().issuerId() != null + || accountSource.scope().tenantId() != null + || !ISSUER_STREAM.equals(issuer.checkpoint().outboxStreamKey()) + || !accountStream.equals(accountSource.checkpoint().outboxStreamKey()) + || issuer.generation() != current.issuer().generation() + || issuer.sourceVersion() != current.issuer().sourceVersion() + || accountSource.generation() != current.account().generation() + || accountSource.sourceVersion() != current.account().sourceVersion() + || !Objects.equals(accountSource.issuanceFence(), sources.issuanceFence()) + || !Objects.equals(sources.issuanceFence(), current.issuanceFence()) + || !Objects.equals( + operation.get("authority_issuer_generation", Long.class), issuer.generation()) + || !Objects.equals( + operation.get("authority_issuer_source_version", Long.class), issuer.sourceVersion()) + || !Objects.equals( + operation.get("authority_account_generation", Long.class), accountSource.generation()) + || !Objects.equals( + operation.get("authority_account_source_version", Long.class), + accountSource.sourceVersion()) + || !Objects.equals( + operation.get("issuance_fence", Long.class), sources.issuanceFence().value()) + || !Objects.equals( + operation.get("issuance_fence_source_version", Long.class), + sources.issuanceFence().sourceVersion()) + || !"ISSUER_SCOPE_INSERT".equals(issuer.initializationProvenance()) + || !"ACCOUNT_REPOSITORY_INSERT".equals(accountSource.initializationProvenance()) + || !Objects.equals( + positive(account.get("id", Long.class)), accountSource.accountSourceNumericId()) + || !Objects.equals( + account.get("account_uuid_provenance", String.class), + accountSource.accountUuidProvenance())) { + throw new OwnerEvidenceUnavailableException(); + } + Map tuple = authorityTuple(sources); + if (!MessageDigest.isEqual( + canonicalJson(tuple), requiredBytes(operation, "authority_tuple_canonical_bytes")) + || !MessageDigest.isEqual( + requiredBytes(operation, "membership_version_canonical_bytes"), + "{}".getBytes(StandardCharsets.US_ASCII))) { + // The exact current tuple, including an applicable Account security cutoff, must match the + // immutable PENDING operation. A baseline-only or synthesized-empty tuple is not accepted. + throw new OwnerEvidenceUnavailableException(); + } + } + + private AccountAuthEvidenceBundle makeBundle( + Record operation, + Record account, + IssuerAccountSourceSnapshot sources, + AccountAuthEvidenceBundle.BundleReference bundleReference) { + UUID accountId = requiredUuid(operation, "account_uuid"); + UUID operationId = requiredUuid(operation, "operation_id"); + UUID requestId = requiredUuid(operation, "request_id"); + UUID callerContextId = requiredUuid(operation, "caller_context_id"); + UUID tokenJti = requiredUuid(operation, "token_jti"); + String requestDigest = requiredText(operation, "request_digest"); + String callerWorkload = requiredText(operation, "caller_workload"); + long issuedAt = positive(operation.get("issued_at_epoch_second", Long.class)); + long notBefore = positive(operation.get("not_before_epoch_second", Long.class)); + long expiresAt = positive(operation.get("expires_at_epoch_second", Long.class)); + long tokenGeneration = positive(operation.get("token_generation", Long.class)); + Map tuple = authorityTuple(sources); + Map sourceVersions = sourceVersions(sources); + List checkpoints = + List.of( + checkpoint(sources.account().checkpoint()), checkpoint(sources.issuer().checkpoint())); + long sourceRowId = positive(account.get("id", Long.class)); + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue( + requiredText(account, "account_uuid_provenance")); + long sourceNumericId = positive(account.get("account_uuid_source_numeric_id", Long.class)); + AccountAuthEvidenceBundle.AccountIdentitySource identitySource = + new AccountAuthEvidenceBundle.AccountIdentitySource( + sourceRowId, provenance, sourceNumericId); + String snapshotIdentity = + sha256( + canonicalJson( + snapshotIdentityPreimage( + sources, accountId, identitySource, tuple, sourceVersions))); + String evaluationIdentity = + sha256( + canonicalJson( + evaluationIdentityPreimage( + snapshotIdentity, + bundleReference, + operationId, + requestId, + requestDigest, + callerWorkload, + callerContextId, + accountId, + tokenJti, + tokenGeneration, + issuedAt, + notBefore, + expiresAt))); + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new AccountAuthEvidenceBundle.OwnerEvaluation( + new AccountAuthEvidenceBundle.BundleReference( + bundleReference.bundleVersion(), + bundleReference.sourceVersion(), + bundleReference.sourceFence(), + bundleReference.linearization()), + snapshotIdentity, + evaluationIdentity, + accountId, + new AccountAuthEvidenceBundle.OperationIdentity( + operationId, requestId, requestDigest, callerWorkload, callerContextId, accountId), + new AccountAuthEvidenceBundle.TokenIdentity( + tokenJti, tokenGeneration, issuedAt, notBefore, expiresAt), + tuple, + sources.issuanceFence().value(), + new AccountAuthEvidenceBundle.AuthoritySourceVersions( + sources.issuer().sourceVersion(), + sources.account().sourceVersion(), + sources.issuanceFence().sourceVersion()), + identitySource, + checkpoints)); + } + + private static Map authorityTuple(IssuerAccountSourceSnapshot sources) { + return GameSessionAccountDelegationProfile.authorityTuple( + sources.issuer().generation(), + sources.account().generation(), + sources + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))); + } + + private static Map sourceVersions(IssuerAccountSourceSnapshot sources) { + Map versions = new LinkedHashMap<>(); + versions.put("issuerSourceVersion", Long.toString(sources.issuer().sourceVersion())); + versions.put("accountSourceVersion", Long.toString(sources.account().sourceVersion())); + versions.put( + "issuanceFenceSourceVersion", Long.toString(sources.issuanceFence().sourceVersion())); + return versions; + } + + private static AccountAuthEvidenceBundle.OutboxCheckpoint checkpoint(SourceCheckpoint source) { + return new AccountAuthEvidenceBundle.OutboxCheckpoint( + source.outboxStreamKey(), + source.sequence(), + source.sourceEventId().orElse(null), + source.sourceEventDigest().orElse(null)); + } + + private static Map snapshotIdentityPreimage( + IssuerAccountSourceSnapshot sources, + UUID accountId, + AccountAuthEvidenceBundle.AccountIdentitySource identitySource, + Map tuple, + Map sourceVersions) { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("domain", "firemud/account-auth-evidence/snapshot/v1"); + snapshot.put("schema", AccountAuthEvidenceBundle.SCHEMA); + snapshot.put("issuer", GameSessionAccountDelegationProfile.ISSUER); + snapshot.put("profile", GameSessionAccountDelegationProfile.PROFILE); + snapshot.put("accountId", accountId.toString()); + snapshot.put("authorityTuple", tuple); + snapshot.put("issuanceFence", Long.toString(sources.issuanceFence().value())); + snapshot.put("authoritySourceVersions", sourceVersions); + snapshot.put("issuerCheckpoint", checkpointFields(sources.issuer().checkpoint())); + snapshot.put("accountCheckpoint", checkpointFields(sources.account().checkpoint())); + snapshot.put("issuerInitializationProvenance", sources.issuer().initializationProvenance()); + snapshot.put("accountInitializationProvenance", sources.account().initializationProvenance()); + snapshot.put("accountIdentitySource", identitySourceFields(identitySource)); + return snapshot; + } + + private static Map evaluationIdentityPreimage( + String snapshotIdentity, + AccountAuthEvidenceBundle.BundleReference bundleReference, + UUID operationId, + UUID requestId, + String requestDigest, + String callerWorkload, + UUID callerContextId, + UUID accountId, + UUID tokenJti, + long tokenGeneration, + long issuedAt, + long notBefore, + long expiresAt) { + Map operation = new LinkedHashMap<>(); + operation.put("operationId", operationId.toString()); + operation.put("requestId", requestId.toString()); + operation.put("requestDigest", requestDigest); + operation.put("callerWorkload", callerWorkload); + operation.put("callerContextId", callerContextId.toString()); + operation.put("accountId", accountId.toString()); + Map token = new LinkedHashMap<>(); + token.put("jti", tokenJti.toString()); + token.put("tokenGeneration", Long.toString(tokenGeneration)); + token.put("iat", issuedAt); + token.put("nbf", notBefore); + token.put("exp", expiresAt); + Map evaluation = new LinkedHashMap<>(); + evaluation.put("domain", "firemud/account-auth-evidence/evaluation/v1"); + evaluation.put("schema", AccountAuthEvidenceBundle.SCHEMA); + evaluation.put("snapshotIdentity", snapshotIdentity); + evaluation.put( + "bundleRef", + Map.of( + "bundleVersion", bundleReference.bundleVersion(), + "sourceVersion", bundleReference.sourceVersion(), + "sourceFence", bundleReference.sourceFence(), + "linearization", bundleReference.linearization())); + evaluation.put("operation", operation); + evaluation.put("tokenIdentity", token); + evaluation.put("membershipVersion", Map.of()); + return evaluation; + } + + private static Map checkpointFields(SourceCheckpoint checkpoint) { + Map fields = new LinkedHashMap<>(); + fields.put("outboxStreamKey", checkpoint.outboxStreamKey()); + fields.put("outboxSequence", Long.toString(checkpoint.sequence())); + checkpoint.sourceEventId().ifPresent(value -> fields.put("sourceEventId", value)); + checkpoint.sourceEventDigest().ifPresent(value -> fields.put("sourceEventDigest", value)); + return fields; + } + + private static Map identitySourceFields( + AccountAuthEvidenceBundle.AccountIdentitySource identitySource) { + Map fields = new LinkedHashMap<>(); + fields.put("sourceRowId", Long.toString(identitySource.sourceRowId())); + fields.put("provenance", identitySource.provenance().name()); + fields.put("sourceNumericId", Long.toString(identitySource.sourceNumericId())); + return fields; + } + + private String currentTransactionId() { + Record transaction = dsl.fetchOne("SELECT pg_current_xact_id()::text AS transaction_id"); + String value = transaction == null ? null : transaction.get("transaction_id", String.class); + if (value == null || !value.matches("[1-9][0-9]{0,19}")) { + throw new OwnerEvidenceUnavailableException(); + } + try { + if (new java.math.BigInteger(value).bitLength() > 64) { + throw new OwnerEvidenceUnavailableException(); + } + } catch (NumberFormatException ex) { + throw new OwnerEvidenceUnavailableException(); + } + return value; + } + + private static AccountAuthEvidenceBundle.BundleReference storedBundleReference( + AccountAuthEvidenceBundle stored) { + Object reference = stored.fields().get("bundleRef"); + if (!(reference instanceof Map fields) + || !(fields.get("bundleVersion") instanceof String bundleVersion) + || !(fields.get("sourceVersion") instanceof String sourceVersion) + || !(fields.get("sourceFence") instanceof String sourceFence) + || !(fields.get("linearization") instanceof String linearization)) { + throw new StoredBundleUnavailableException(); + } + try { + return new AccountAuthEvidenceBundle.BundleReference( + bundleVersion, sourceVersion, sourceFence, linearization); + } catch (RuntimeException ex) { + throw new StoredBundleUnavailableException(); + } + } + + private String allocateSourceFence(UUID operationId, String transactionId) { + Record allocation = + dsl.fetchOne( + "UPDATE account_gameplay_auth_evidence_source_fence " + + "SET last_source_fence = last_source_fence + 1, last_operation_id = ?, " + + "last_transaction_id = ? " + + "WHERE allocator_id = TRUE AND last_source_fence < 9223372036854775807 " + + "RETURNING last_source_fence", + operationId, + transactionId); + if (allocation == null) throw new OwnerEvidenceUnavailableException(); + Long sourceFence = allocation.get("last_source_fence", Long.class); + if (sourceFence == null || sourceFence <= 0L) { + throw new OwnerEvidenceUnavailableException(); + } + return Long.toString(sourceFence); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw new OwnerEvidenceUnavailableException(); + return value; + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw new OwnerEvidenceUnavailableException(); + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw new OwnerEvidenceUnavailableException(); + return value.clone(); + } + + private static long positive(Long value) { + if (value == null || value <= 0L) throw new OwnerEvidenceUnavailableException(); + return value; + } + + private static boolean canonicalV4(UUID value) { + return value != null && value.version() == 4 && V4_UUID.matcher(value.toString()).matches(); + } + + private static String nestedText(Map root, String parent, String child) { + Object value = root.get(parent); + if (!(value instanceof Map object)) throw new StoredBundleUnavailableException(); + Object nested = object.get(child); + if (!(nested instanceof String text)) throw new StoredBundleUnavailableException(); + return text; + } + + private static void requireWritableAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account auth-evidence capture requires a writable Account transaction"); + } + } + + public static final class OwnerEvidenceUnavailableException extends IllegalStateException { + public OwnerEvidenceUnavailableException() { + super("Account owner source and retained-history evidence is unavailable or ambiguous"); + } + } + + public static final class OperationNotFoundException extends IllegalStateException { + public OperationNotFoundException() { + super("Account gameplay delegation operation is absent"); + } + } + + public static final class StoredBundleUnavailableException extends IllegalStateException { + public StoredBundleUnavailableException() { + super("Stored Account auth-evidence bundle is unavailable or malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java index 7766cfa838..87109ba150 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.accountservice.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.LongFunction; @@ -33,6 +35,7 @@ public class AccountAuthorityOutboxRepository { private static final int MAX_REQUEST_ID_LENGTH = 512; private static final int MAX_EVENT_ID_LENGTH = 512; private static final int MAX_EVENT_DIGEST_LENGTH = 512; + public static final int MAX_EVENT_HISTORY_PAGE_SIZE = 128; private final DSLContext dsl; @@ -209,6 +212,38 @@ public Optional findEvent(String outboxStreamKey, String requestId) { : Optional.of(toEvent(outboxStreamKey, row.get("request_id", String.class), row)); } + /** + * Reads a bounded page from one immutable retained authority-event prefix. + * + *

The caller owns the captured positive checkpoint and must verify that every sequence from + * one through that checkpoint is present and ordered. This method never widens the requested head + * when later events are appended. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public List findEventPage( + String outboxStreamKey, long afterSequence, long throughSequence) { + validateStreamKey(outboxStreamKey); + if (afterSequence < 0L || throughSequence <= 0L || afterSequence > throughSequence) { + throw new IllegalArgumentException( + "A bounded positive Account authority event range is required"); + } + List rows = + dsl.fetch( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence > ? " + + "AND outbox_sequence <= ? ORDER BY outbox_sequence LIMIT ?", + outboxStreamKey, + afterSequence, + throughSequence, + MAX_EVENT_HISTORY_PAGE_SIZE); + List events = new ArrayList<>(rows.size()); + for (Record row : rows) { + events.add(toEvent(outboxStreamKey, row.get("request_id", String.class), row)); + } + return List.copyOf(events); + } + /** * Reads the exact latest positive checkpoint for a stream, or empty when no canonical event has * ever been committed to that stream. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java new file mode 100644 index 0000000000..770ca2ef61 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java @@ -0,0 +1,2535 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection.ProjectionObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned immutable issuance intent, candidate binding, and non-authorizing commit evidence. + * + *

This is deliberately not an Authenticate issuer, signer-promotion authority, response recovery + * store, active-token validator, or registry activation path. It records a bounded pre-sign intent, + * separately binds the candidate hash and canonical pending projection, and can persist COMMITTED + * only with signer-owned verification, pinned Redis, current projection, full bundle, and sealed + * envelope evidence. Every mutation locks the existing Account authority rows in the caller's + * Account transaction; no remote operation is performed while those locks are held. + */ +public class AccountGameplayDelegationIssuanceRepository { + private static final String TABLE = "account_gameplay_delegation_issuance_operations"; + private static final int REQUEST_DIGEST_VERSION = 2; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final int MAX_INTENT_BYTES = 16 * 1024; + private static final int MAX_COMMIT_PROOF_BYTES = + AccountGameplayDelegationIssuanceCommitService.MAX_COMMIT_PROOF_BYTES; + private static final byte[] EMPTY_OBJECT = "{}".getBytes(StandardCharsets.US_ASCII); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final DSLContext dsl; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountAuthEvidenceBundleRepository evidenceBundles; + private final Clock clock; + private final AccountGameplayTokenIdentityFenceRepository tokenIdentityFences; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayDelegationIssuanceRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles) { + this(dsl, sourceEvidence, evidenceBundles, Clock.systemUTC()); + } + + /** Compatibility for non-signing repositories/fixtures that only use the pending boundary. */ + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayDelegationIssuanceRepository( + DSLContext dsl, AccountAuthoritySourceEvidenceRepository sourceEvidence) { + this(dsl, sourceEvidence, defaultEvidenceBundles(dsl), Clock.systemUTC()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayDelegationIssuanceRepository( + DSLContext dsl, AccountAuthoritySourceEvidenceRepository sourceEvidence, Clock clock) { + this(dsl, sourceEvidence, defaultEvidenceBundles(dsl), clock); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayDelegationIssuanceRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles, + Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.sourceEvidence = + Objects.requireNonNull(sourceEvidence, "Account authority source evidence is required"); + this.evidenceBundles = evidenceBundles; + this.clock = Objects.requireNonNull(clock, "Clock is required"); + this.tokenIdentityFences = new AccountGameplayTokenIdentityFenceRepository(dsl); + } + + /** Persists an immutable pre-sign intent or returns its exact still-current replay. */ + @Transactional(propagation = Propagation.MANDATORY) + public PendingOperation beginPending(PendingIntent intent) { + requireWritableAccountTransaction(); + Objects.requireNonNull(intent, "Account gameplay delegation intent is required"); + tokenIdentityFences.lockAccountForUpdate(intent.authoritySnapshot().accountId()); + lockRequestId(intent.requestId()); + long now = Math.floorDiv(clock.millis(), 1000L); + long latestIssueTime; + try { + latestIssueTime = Math.addExact(now, 5L); + } catch (ArithmeticException ex) { + latestIssueTime = Long.MAX_VALUE; + } + if (now <= 0L + || intent.expiresAtEpochSecond() <= now + || intent.issuedAtEpochSecond() > latestIssueTime) { + throw new IllegalArgumentException("Delegation issuance intent is expired"); + } + IssuerAccountSourceSnapshot current = readAndCompareAuthority(intent); + String digest = requestDigest(intent); + Record prior = selectByRequestId(intent.requestId(), false); + if (prior != null) { + requireExactIntent(prior, intent, digest, current); + Record locked = selectByRequestId(intent.requestId(), true); + if (locked == null) throw new StorageUnavailableException(); + requireExactIntent(locked, intent, digest, current); + return decodeOperation(locked); + } + + insertIntent(intent, digest, current); + Record readback = selectByRequestId(intent.requestId(), true); + if (readback == null) throw new StorageUnavailableException(); + requireExactIntent(readback, intent, digest, current); + return decodeOperation(readback); + } + + /** + * Reads the exact current PENDING or COMMITTED gameplay-login request under its request-id + * serialization lock. A COMMITTED replay additionally requires the canonical persisted commit + * proof. This metadata-only owner boundary rechecks current source authority and original expiry; + * it never reconstructs the request identity or returns a credential. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional readCurrentGameplayLoginReplay( + UUID requestId) { + requireWritableAccountTransaction(); + requireRequestId(requestId); + + Record preliminary = selectByRequestId(requestId, false); + if (preliminary == null) return java.util.Optional.empty(); + String preliminaryStatus = preliminary.get("status", String.class); + if (!isReplayableGameplayLoginStatus(preliminaryStatus)) { + throw new IdempotencyConflictException(); + } + UUID accountId = preliminary.get("account_uuid", UUID.class); + UUID operationId = preliminary.get("operation_id", UUID.class); + if (accountId == null || operationId == null) throw new StorageUnavailableException(); + + tokenIdentityFences.lockAccountForUpdate(accountId); + lockRequestId(requestId); + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + Record locked = selectByRequestId(requestId, true); + String lockedStatus = locked == null ? null : locked.get("status", String.class); + if (locked == null + || !accountId.equals(locked.get("account_uuid", UUID.class)) + || !operationId.equals(locked.get("operation_id", UUID.class)) + || !isReplayableGameplayLoginStatus(lockedStatus) + || ("COMMITTED".equals(preliminaryStatus) && !"COMMITTED".equals(lockedStatus))) { + throw new IdempotencyConflictException(); + } + AccountGameplayDelegationPendingIdentity identity = identity(locked); + requireStoredAuthority(locked, current); + AccountAuthoritySnapshot currentAuthority = authoritySnapshot(current); + PendingIntent exactIntent = + new PendingIntent( + identity.operationId(), + identity.requestId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.tokenJti(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + currentAuthority, + identity.credentialRequestBinding()); + if (!requestId.equals(identity.requestId()) + || !identity.requestDigest().equals(requestDigest(exactIntent))) { + throw new IdempotencyConflictException(); + } + if (identity.expiresAtEpochSecond() <= Math.floorDiv(clock.millis(), 1000L)) { + throw new PendingCandidateUnavailableException(); + } + PendingOperation operation = decodeOperation(locked); + CommittedIssuanceReadback committedProof = null; + GameplayLoginReplayState replayState = GameplayLoginReplayState.PENDING; + if ("COMMITTED".equals(lockedStatus)) { + if (!operation.candidateBound()) throw new StorageUnavailableException(); + committedProof = + decodeCommittedReadback( + locked, + locked.get("commit_proof_sha256", String.class), + locked.get("commit_proof_canonical_bytes", byte[].class)); + replayState = GameplayLoginReplayState.COMMITTED; + } + return java.util.Optional.of( + new GameplayLoginReplayReadback(identity, operation, replayState, committedProof, false)); + } + + /** Creates a single Account-owned request identity from the current locked authority snapshot. */ + @Transactional(propagation = Propagation.MANDATORY) + public GameplayLoginReplayReadback beginPendingForAccount( + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding) { + requireWritableAccountTransaction(); + requireRequestId(requestId); + Objects.requireNonNull(accountId, "Account UUID is required"); + if (accountId.version() != 4 || accountId.variant() != 2) { + throw new IllegalArgumentException("A canonical version-4 Account UUID is required"); + } + requireRequestId(callerContextId); + Objects.requireNonNull(callerWorkload, "Caller workload is required"); + Objects.requireNonNull( + credentialRequestBinding, "Keyed credential request binding is required"); + tokenIdentityFences.lockAccountForUpdate(accountId); + lockRequestId(requestId); + + java.util.Optional existing = + readCurrentGameplayLoginReplay(requestId); + if (existing.isPresent()) { + GameplayLoginReplayReadback replay = existing.orElseThrow(); + AccountGameplayDelegationPendingIdentity identity = replay.identity(); + if (!accountId.equals(identity.accountId()) + || !callerWorkload.equals(identity.callerWorkload()) + || !callerContextId.equals(identity.callerContextId()) + || !credentialRequestBinding.equals(identity.credentialRequestBinding())) { + throw new IdempotencyConflictException(); + } + return replay; + } + + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + long issuedAt = Math.floorDiv(clock.millis(), 1000L); + long expiresAt; + try { + expiresAt = + Math.addExact(issuedAt, GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); + } catch (ArithmeticException ex) { + throw new StorageUnavailableException(); + } + PendingIntent intent = + new PendingIntent( + UUID.randomUUID(), + requestId, + callerWorkload, + callerContextId, + UUID.randomUUID(), + issuedAt, + issuedAt, + expiresAt, + authoritySnapshot(current), + credentialRequestBinding); + PendingOperation operation = beginPending(intent); + Record readback = selectByRequestId(requestId, true); + if (readback == null) throw new StorageUnavailableException(); + AccountGameplayDelegationPendingIdentity identity = identity(readback); + requireExactIntent(readback, intent, requestDigest(intent), current); + if (!operation.equals(decodeOperation(readback))) throw new StorageUnavailableException(); + return new GameplayLoginReplayReadback( + identity, operation, GameplayLoginReplayState.PENDING, null, true); + } + + /** + * Reads the exact current owner identity and persisted full evidence bundle before signing or + * resuming a previously signed candidate. Account and authority rows are locked before the + * immutable operation row; the canonical bundle owner re-evaluates and returns its persisted + * bytes in this same Account transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PendingSigningIdentity readPendingSigningIdentity(UUID requestId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + if (evidenceBundles == null) throw new PendingCandidateUnavailableException(); + + Record preliminary = selectByRequestId(requestId, false); + if (preliminary == null) throw new PendingCandidateUnavailableException(); + UUID preliminaryAccountId = preliminary.get("account_uuid", UUID.class); + UUID preliminaryOperationId = preliminary.get("operation_id", UUID.class); + if (preliminaryAccountId == null || preliminaryOperationId == null) { + throw new PendingCandidateUnavailableException(); + } + + IssuerAccountSourceSnapshot current = readCurrentAuthority(preliminaryAccountId); + Record operation = selectByRequestId(requestId, true); + if (operation == null + || !preliminaryAccountId.equals(operation.get("account_uuid", UUID.class)) + || !preliminaryOperationId.equals(operation.get("operation_id", UUID.class)) + || !"PENDING".equals(operation.get("status", String.class)) + || !Objects.equals(operation.get("token_generation", Long.class), 1L) + || !hasConsistentCandidateBinding(operation)) { + throw new PendingCandidateUnavailableException(); + } + + AccountGameplayDelegationPendingIdentity identity = identity(operation); + AccountAuthoritySnapshot authority = authoritySnapshot(current); + if (!requestId.equals(identity.requestId()) + || !preliminaryAccountId.equals(identity.accountId())) { + throw new PendingCandidateUnavailableException(); + } + requireStoredAuthority(operation, current); + PendingIntent exactIntent = + new PendingIntent( + identity.operationId(), + identity.requestId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.tokenJti(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + authority, + identity.credentialRequestBinding()); + if (!identity.requestDigest().equals(requestDigest(exactIntent))) { + throw new IdempotencyConflictException(); + } + long now = Math.floorDiv(clock.millis(), 1000L); + if (now <= 0L || identity.expiresAtEpochSecond() <= now) { + throw new PendingCandidateUnavailableException(); + } + + AccountAuthEvidenceBundle captured = evidenceBundles.captureAndPersist(requestId); + AccountAuthEvidenceBundle stored = + evidenceBundles.readStoredNonAuthorizingValue(identity.operationId()); + if (!MessageDigest.isEqual(captured.canonicalBytes(), stored.canonicalBytes())) { + throw new PendingCandidateUnavailableException(); + } + requireExactSigningBundle(stored, identity, authority, current); + Optional persistedCandidate = + operation.get("token_hash", String.class) == null + ? Optional.empty() + : Optional.of(decodePendingRegistryCandidate(operation, current, stored)); + return new PendingSigningIdentity(identity, authority, stored, persistedCandidate); + } + + private static boolean hasConsistentCandidateBinding(Record operation) { + String tokenHash = operation.get("token_hash", String.class); + String kid = operation.get("signer_kid", String.class); + String generation = operation.get("signer_generation", String.class); + byte[] candidateBytes = operation.get("pending_registry_candidate_bytes", byte[].class); + boolean any = tokenHash != null || kid != null || generation != null || candidateBytes != null; + boolean all = tokenHash != null && kid != null && generation != null && candidateBytes != null; + return !any || all; + } + + /** + * Binds the signed compact-token identity once. The raw JWT is transient and never stored; this + * method cannot assert signature validity, promotion, or active-token authority. + */ + @Transactional(propagation = Propagation.MANDATORY) + public BoundTokenCandidate bindSignedCandidate( + UUID requestId, String compactJwt, String signerGeneration) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + Objects.requireNonNull(compactJwt, "Compact JWT is required"); + requirePositiveDecimal(signerGeneration, "signerGeneration"); + Record prior = selectByRequestId(requestId, false); + if (prior == null) throw new StorageUnavailableException(); + UUID accountId = prior.get("account_uuid", UUID.class); + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + Record operation = selectByRequestId(requestId, true); + if (operation == null || !accountId.equals(operation.get("account_uuid", UUID.class))) { + throw new StorageUnavailableException(); + } + requireStoredAuthority(operation, current); + + AccountGameplayDelegationPendingIdentity identity = identity(operation); + AccountAuthoritySnapshot accountSnapshot = authoritySnapshot(current); + AccountAuthEvidenceBundle evidenceBundle = + requireCurrentEvidenceBundle(requestId, identity, accountSnapshot, current); + GameSessionAccountDelegationRegistryRecord candidate = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compactJwt, + signerGeneration, + new IssuanceBinding( + identity.operationId().toString(), + identity.requestId().toString(), + identity.requestDigest(), + identity.accountId().toString()), + accountSnapshot, + evidenceBundleReference(evidenceBundle), + Math.floorDiv(clock.millis(), 1000L), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + Map candidateFields = candidate.fields(); + if (!identity.operationId().toString().equals(candidate.operationId()) + || !identity.requestId().toString().equals(candidate.requestId()) + || !identity.requestDigest().equals(candidate.requestDigest()) + || !identity.accountId().toString().equals(candidate.accountId()) + || !identity.tokenJti().toString().equals(candidate.jti()) + || identity.issuedAtEpochSecond() != candidate.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != candidate.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != candidate.expiresAtEpochSecond() + || candidate.issuanceFence() != authoritySnapshot(current).issuanceFence() + || !Arrays.equals( + canonicalJson(candidateFields.get("authorityTuple")), + canonicalJson(authorityTuple(authoritySnapshot(current)))) + || !Arrays.equals(canonicalJson(candidateFields.get("membershipVersion")), EMPTY_OBJECT) + || !Arrays.equals( + canonicalJson(candidateFields.get("authoritySourceVersions")), + canonicalJson(sourceVersionsMap(current)))) { + throw new IdempotencyConflictException(); + } + byte[] candidateBytes = + candidate.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + String hash = candidate.tokenHash(); + String kid = candidate.kid(); + String existingHash = operation.get("token_hash", String.class); + byte[] existingBytes = operation.get("pending_registry_candidate_bytes", byte[].class); + String existingSigner = operation.get("signer_generation", String.class); + String existingKid = operation.get("signer_kid", String.class); + if (existingHash != null + || existingBytes != null + || existingSigner != null + || existingKid != null) { + if (!hash.equals(existingHash) + || !Arrays.equals(candidateBytes, existingBytes) + || !signerGeneration.equals(existingSigner) + || !kid.equals(existingKid)) { + throw new IdempotencyConflictException(); + } + return new BoundTokenCandidate(identity.requestId(), hash, kid, signerGeneration); + } + + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET token_hash = ?, signer_kid = ?, signer_generation = ?, " + + "pending_registry_candidate_bytes = ? WHERE request_id = ? " + + "AND status = 'PENDING' AND token_hash IS NULL AND signer_kid IS NULL " + + "AND signer_generation IS NULL AND pending_registry_candidate_bytes IS NULL", + hash, + kid, + signerGeneration, + candidateBytes, + requestId); + if (changed != 1) throw new StorageUnavailableException(); + Record readback = selectByRequestId(requestId, true); + if (readback == null + || !hash.equals(readback.get("token_hash", String.class)) + || !kid.equals(readback.get("signer_kid", String.class)) + || !signerGeneration.equals(readback.get("signer_generation", String.class)) + || !Arrays.equals( + candidateBytes, readback.get("pending_registry_candidate_bytes", byte[].class))) { + throw new StorageUnavailableException(); + } + requireStoredAuthority(readback, current); + return new BoundTokenCandidate(identity.requestId(), hash, kid, signerGeneration); + } + + /** Reads a canonical pending projection only after an exact current-authority SQL recheck. */ + @Transactional(propagation = Propagation.REQUIRED) + public PendingRegistryCandidate readPendingRegistryCandidate(UUID requestId) { + Objects.requireNonNull(requestId, "Request ID is required"); + Record prior = selectByRequestId(requestId, false); + if (prior == null) throw new StorageUnavailableException(); + UUID accountId = prior.get("account_uuid", UUID.class); + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + Record row = selectByRequestId(requestId, true); + if (row == null + || !accountId.equals(row.get("account_uuid", UUID.class)) + || !"PENDING".equals(row.get("status", String.class))) { + throw new StorageUnavailableException(); + } + requireStoredAuthority(row, current); + AccountAuthEvidenceBundle evidenceBundle = + requireCurrentEvidenceBundle(requestId, identity(row), authoritySnapshot(current), current); + return decodePendingRegistryCandidate(row, current, evidenceBundle); + } + + private PendingRegistryCandidate decodePendingRegistryCandidate( + Record row, IssuerAccountSourceSnapshot current, AccountAuthEvidenceBundle evidenceBundle) { + byte[] bytes = row.get("pending_registry_candidate_bytes", byte[].class); + String hash = row.get("token_hash", String.class); + String kid = row.get("signer_kid", String.class); + String signer = row.get("signer_generation", String.class); + if (bytes == null || hash == null || kid == null || signer == null) { + throw new PendingCandidateUnavailableException(); + } + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.decode( + bytes, GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + AccountGameplayDelegationPendingIdentity identity = identity(row); + if (!record.tokenHash().equals(hash) + || !record.kid().equals(kid) + || !record.signerGeneration().equals(signer) + || !"pending".equals(record.state()) + || !record.operationId().equals(identity.operationId().toString()) + || !record.requestId().equals(identity.requestId().toString()) + || !record.requestDigest().equals(identity.requestDigest()) + || !record.accountId().equals(identity.accountId().toString()) + || !record.jti().equals(identity.tokenJti().toString()) + || record.issuanceFence() != authoritySnapshot(current).issuanceFence() + || !Arrays.equals( + canonicalJson(record.fields().get("authorityTuple")), + canonicalJson(authorityTuple(authoritySnapshot(current)))) + || !Arrays.equals(canonicalJson(record.fields().get("membershipVersion")), EMPTY_OBJECT) + || !Arrays.equals( + canonicalJson(record.fields().get("authoritySourceVersions")), + canonicalJson(sourceVersionsMap(current))) + || !record.evidenceBundleReference().equals(evidenceBundleReference(evidenceBundle)) + || !Long.valueOf(identity.issuedAtEpochSecond()) + .equals(requireJsonInteger(record.fields().get("iat"))) + || !Long.valueOf(identity.notBeforeEpochSecond()) + .equals(requireJsonInteger(record.fields().get("nbf"))) + || !Long.valueOf(identity.expiresAtEpochSecond()) + .equals(requireJsonInteger(record.fields().get("exp")))) { + throw new StorageUnavailableException(); + } + return new PendingRegistryCandidate( + identity, + hash, + kid, + signer, + record.expiresAtEpochSecond(), + bytes, + authoritySnapshot(current), + evidenceBundleReference(evidenceBundle)); + } + + /** + * Reads and validates the complete immutable COMMITTED owner evidence under the same Account, + * authority, and operation lock order used by issuance. The result is non-authorizing metadata; + * it deliberately contains neither the JWT, registry bytes, response ciphertext, nor proof bytes. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CommittedCandidateVerificationData readCurrentCommittedCandidate(UUID requestId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + if (evidenceBundles == null) throw new StorageUnavailableException(); + + Record preliminary = selectByRequestId(requestId, false); + if (preliminary == null) throw new StorageUnavailableException(); + UUID accountId = preliminary.get("account_uuid", UUID.class); + UUID operationId = preliminary.get("operation_id", UUID.class); + if (accountId == null || operationId == null) throw new StorageUnavailableException(); + + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + Record row = selectByRequestId(requestId, true); + if (row == null + || !accountId.equals(row.get("account_uuid", UUID.class)) + || !operationId.equals(row.get("operation_id", UUID.class)) + || !requestId.equals(row.get("request_id", UUID.class)) + || !"COMMITTED".equals(row.get("status", String.class)) + || !Objects.equals(row.get("token_generation", Long.class), 1L) + || row.get("token_hash", String.class) == null + || row.get("signer_kid", String.class) == null + || row.get("signer_generation", String.class) == null + || row.get("pending_registry_candidate_bytes", byte[].class) == null) { + throw new StorageUnavailableException(); + } + AccountGameplayDelegationPendingIdentity identity = identity(row); + AccountAuthoritySnapshot authority = authoritySnapshot(current); + requireStoredAuthority(row, current); + PendingIntent exactIntent = + new PendingIntent( + identity.operationId(), + identity.requestId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.tokenJti(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + authority, + identity.credentialRequestBinding()); + if (!requestDigest(exactIntent).equals(identity.requestDigest())) { + throw new IdempotencyConflictException(); + } + requireUnexpired(identity); + + AccountAuthEvidenceBundle bundle; + try { + bundle = evidenceBundles.readStoredNonAuthorizingValue(operationId); + } catch (RuntimeException failure) { + throw new StorageUnavailableException(); + } + requireExactSigningBundle(bundle, identity, authority, current); + PendingRegistryCandidate candidate = decodePendingRegistryCandidate(row, current, bundle); + + CommittedIssuanceReadback readback = decodeCommittedReadback(row, null, null); + String proofSha256 = row.get("commit_proof_sha256", String.class); + byte[] proofBytes = row.get("commit_proof_canonical_bytes", byte[].class); + Map proof = parseCommitProof(proofBytes); + requireCommittedProofIdentity(proof, identity, readback, candidate, bundle, current); + tokenIdentityFences.requireActiveForUpdate(tokenIdentity(row)); + AuthenticatedSignerCorrespondence correspondence = + requireCommittedSignerProof(proof, candidate); + EnvelopeIdentity envelope = + requireCommittedEnvelopeProof(proof, identity, candidate, authority, bundle); + Map persistedRegistry = requireMap(proof.get("registry")); + long registryExpiryMillis = + positiveCanonicalLong(persistedRegistry.get("absoluteExpiryMillis")); + long registrationLocalAofCount = positiveCanonicalLong(persistedRegistry.get("localAofCount")); + long registrationReplicaAofCount = + positiveCanonicalLong(persistedRegistry.get("replicaAofCount")); + PendingRegistrationOutcome registrationOutcome = + switch (Objects.toString(persistedRegistry.get("outcome"), "")) { + case "CREATED" -> PendingRegistrationOutcome.CREATED; + case "EXACT_RETRY" -> PendingRegistrationOutcome.EXACT_RETRY; + default -> throw new StorageUnavailableException(); + }; + + return new CommittedCandidateVerificationData( + identity, + authority, + evidenceBundleReference(bundle), + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + sha256(candidate.canonicalRecordBytes()), + proofSha256, + correspondence, + envelope.keyId(), + envelope.sha256(), + envelope.length(), + envelope.expiryMillis(), + registryExpiryMillis, + registrationLocalAofCount, + registrationReplicaAofCount, + registrationOutcome); + } + + /** + * Resolves an untrusted signed-token JTI only to the request key of a committed operation, then + * runs the same full current-authority/commit-proof read used by the issuance owner. The JTI is a + * lookup hint, never authentication or permission by itself. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional readCurrentCommittedCandidateByJti( + UUID tokenJti) { + requireWritableAccountTransaction(); + if (tokenJti == null || tokenJti.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil token JTI is required"); + } + Record requestRow; + try { + requestRow = + dsl.fetchOne( + "SELECT request_id FROM account_gameplay_delegation_issuance_operations " + + "WHERE token_jti = ? AND status = 'COMMITTED' AND token_generation = 1", + tokenJti); + } catch (org.jooq.exception.TooManyRowsException ambiguous) { + throw new StorageUnavailableException(); + } + if (requestRow == null) return java.util.Optional.empty(); + UUID requestId = requestRow.get("request_id", UUID.class); + if (requestId == null || requestId.equals(new UUID(0L, 0L))) { + throw new StorageUnavailableException(); + } + CommittedCandidateVerificationData current = readCurrentCommittedCandidate(requestId); + if (current == null + || !requestId.equals(current.identity().requestId()) + || !tokenJti.equals(current.identity().tokenJti())) { + throw new StorageUnavailableException(); + } + return java.util.Optional.of(current); + } + + private void requireUnexpired(AccountGameplayDelegationPendingIdentity identity) { + long now = Math.floorDiv(clock.millis(), 1_000L); + long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; + if (now <= 0L + || identity.notBeforeEpochSecond() > now + || identity.issuedAtEpochSecond() > latestIssuedAt + || identity.expiresAtEpochSecond() <= now) { + throw new StorageUnavailableException(); + } + } + + private static void requireCommittedProofIdentity( + Map proof, + AccountGameplayDelegationPendingIdentity identity, + CommittedIssuanceReadback readback, + PendingRegistryCandidate candidate, + AccountAuthEvidenceBundle bundle, + IssuerAccountSourceSnapshot current) { + Map proofIdentity = requireMap(proof.get("identity")); + requireExactFields( + proofIdentity, + Set.of( + "operationId", + "requestId", + "accountId", + "requestDigest", + "callerWorkload", + "callerContextId", + "tokenJti", + "tokenGeneration", + "issuedAtEpochSecond", + "notBeforeEpochSecond", + "expiresAtEpochSecond", + "tokenSha256")); + if (!AccountGameplayDelegationIssuanceCommitService.COMMIT_PROOF_SCHEMA.equals( + proof.get("schema")) + || !identity.operationId().toString().equals(proofIdentity.get("operationId")) + || !identity.requestId().toString().equals(proofIdentity.get("requestId")) + || !identity.accountId().toString().equals(proofIdentity.get("accountId")) + || !identity.requestDigest().equals(proofIdentity.get("requestDigest")) + || !identity.callerWorkload().equals(proofIdentity.get("callerWorkload")) + || !identity.callerContextId().toString().equals(proofIdentity.get("callerContextId")) + || !identity.tokenJti().toString().equals(proofIdentity.get("tokenJti")) + || !"1".equals(proofIdentity.get("tokenGeneration")) + || !Long.toString(identity.issuedAtEpochSecond()) + .equals(proofIdentity.get("issuedAtEpochSecond")) + || !Long.toString(identity.notBeforeEpochSecond()) + .equals(proofIdentity.get("notBeforeEpochSecond")) + || !Long.toString(identity.expiresAtEpochSecond()) + .equals(proofIdentity.get("expiresAtEpochSecond")) + || !candidate.tokenHash().equals(proofIdentity.get("tokenSha256")) + || !candidate.tokenHash().equals(proof.get("tokenSha256")) + || !sha256(candidate.canonicalRecordBytes()).equals(proof.get("registryRecordSha256")) + || !readback.operationId().equals(identity.operationId()) + || !readback.requestId().equals(identity.requestId()) + || !readback.accountId().equals(identity.accountId()) + || !readback.requestDigest().equals(identity.requestDigest()) + || !readback.tokenHash().equals(candidate.tokenHash()) + || !readback.signerKid().equals(candidate.kid()) + || !readback.signerGeneration().equals(candidate.signerGeneration())) { + throw new StorageUnavailableException(); + } + + Map registry = requireMap(proof.get("registry")); + requireExactFields( + registry, + Set.of( + "state", + "registryVersion", + "tokenKey", + "tokenHash", + "kid", + "signerGeneration", + "operationId", + "requestId", + "requestDigest", + "absoluteExpiryMillis", + "localAofCount", + "replicaAofCount", + "outcome", + "canonicalRecordSha256", + "evidenceBundleSha256", + "aclIdentity")); + long tokenExpiryMillis; + long registryExpiryMillis; + try { + tokenExpiryMillis = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + registryExpiryMillis = positiveCanonicalLong(registry.get("absoluteExpiryMillis")); + } catch (RuntimeException invalidExpiry) { + throw new StorageUnavailableException(); + } + long expiryMargin; + try { + expiryMargin = Math.subtractExact(registryExpiryMillis, tokenExpiryMillis); + } catch (ArithmeticException invalidMargin) { + throw new StorageUnavailableException(); + } + Object outcome = registry.get("outcome"); + if (!"pending".equals(registry.get("state")) + || positiveCanonicalLong(registry.get("registryVersion")) != 1L + || !AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + .concat(candidate.tokenHash()) + .equals(registry.get("tokenKey")) + || !candidate.tokenHash().equals(registry.get("tokenHash")) + || !candidate.kid().equals(registry.get("kid")) + || !candidate.signerGeneration().equals(registry.get("signerGeneration")) + || !identity.operationId().toString().equals(registry.get("operationId")) + || !identity.requestId().toString().equals(registry.get("requestId")) + || !identity.requestDigest().equals(registry.get("requestDigest")) + || expiryMargin < 0L + || expiryMargin > 300_000L + || positiveCanonicalLong(registry.get("localAofCount")) < 1L + || positiveCanonicalLong(registry.get("replicaAofCount")) < 1L + || !("CREATED".equals(outcome) || "EXACT_RETRY".equals(outcome)) + || !sha256(candidate.canonicalRecordBytes()).equals(registry.get("canonicalRecordSha256")) + || !bundle.canonicalSha256().equals(registry.get("evidenceBundleSha256")) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals( + registry.get("aclIdentity"))) { + throw new StorageUnavailableException(); + } + + Map bundleReference = requireMap(proof.get("bundle")); + if (!sameCanonicalMap(bundleReference, evidenceBundleReference(bundle).toMap())) { + throw new StorageUnavailableException(); + } + + Map authority = requireMap(proof.get("authority")); + requireExactFields( + authority, + Set.of( + "issuerGeneration", + "issuerSourceVersion", + "accountGeneration", + "accountSourceVersion", + "issuanceFence", + "issuanceFenceSourceVersion", + "authorityTuple", + "authoritySourceVersions", + "issuerProjectionGeneration", + "accountProjectionGeneration", + "issuerProjectionSha256", + "accountProjectionSha256")); + byte[][] projectionPair = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(current); + AccountAuthoritySnapshot snapshot = authoritySnapshot(current); + if (!Long.toString(snapshot.issuerGeneration()).equals(authority.get("issuerGeneration")) + || !Long.toString(snapshot.issuerSourceVersion()) + .equals(authority.get("issuerSourceVersion")) + || !Long.toString(snapshot.accountGeneration()).equals(authority.get("accountGeneration")) + || !Long.toString(snapshot.accountSourceVersion()) + .equals(authority.get("accountSourceVersion")) + || !Long.toString(snapshot.issuanceFence()).equals(authority.get("issuanceFence")) + || !Long.toString(snapshot.issuanceFenceSourceVersion()) + .equals(authority.get("issuanceFenceSourceVersion")) + || !sameCanonicalMap(authority.get("authorityTuple"), authorityTuple(snapshot)) + || !sameCanonicalMap(authority.get("authoritySourceVersions"), snapshot.sourceVersions()) + || !Long.toString(snapshot.issuerGeneration()) + .equals(authority.get("issuerProjectionGeneration")) + || !Long.toString(snapshot.accountGeneration()) + .equals(authority.get("accountProjectionGeneration")) + || !sha256(projectionPair[0]).equals(authority.get("issuerProjectionSha256")) + || !sha256(projectionPair[1]).equals(authority.get("accountProjectionSha256"))) { + throw new StaleAuthorityException(); + } + } + + private static AuthenticatedSignerCorrespondence requireCommittedSignerProof( + Map proof, PendingRegistryCandidate candidate) { + Map signer = requireMap(proof.get("signer")); + requireExactFields( + signer, + Set.of( + "promotionStatus", + "promotionOperationId", + "generationOperationId", + "targetKid", + "targetGeneration", + "correspondenceSha256", + "correspondence")); + Map correspondenceMap = requireMap(signer.get("correspondence")); + Set correspondenceFields = + Arrays.stream(AuthenticatedSignerCorrespondence.class.getRecordComponents()) + .map(java.lang.reflect.RecordComponent::getName) + .collect(java.util.stream.Collectors.toUnmodifiableSet()); + requireExactFields(correspondenceMap, correspondenceFields); + if (!"COMMITTED".equals(signer.get("promotionStatus")) + || !candidate.kid().equals(signer.get("targetKid")) + || !candidate.signerGeneration().equals(signer.get("targetGeneration")) + || !sha256(canonicalProofJson(correspondenceMap)) + .equals(signer.get("correspondenceSha256"))) { + throw new StorageUnavailableException(); + } + try { + byte[] bytes = JSON.writeValueAsBytes(correspondenceMap); + AuthenticatedSignerCorrespondence correspondence = + JSON.readValue(bytes, AuthenticatedSignerCorrespondence.class); + if (!correspondence + .promotionOperationId() + .toString() + .equals(signer.get("promotionOperationId")) + || !correspondence + .generationOperationId() + .toString() + .equals(signer.get("generationOperationId")) + || !"COMMITTED".equals(correspondence.promotionStatus()) + || !correspondence.privatePromotionDispatched() + || !correspondence + .promotionOperationId() + .equals(correspondence.privatePromotionOperationId()) + || !correspondence + .promotionOperationId() + .equals(correspondence.publicPromotionOperationId()) + || !correspondence + .generationOperationId() + .equals(correspondence.privatePromotionGenerationOperationId()) + || correspondence + .durableActive() + .filter( + active -> + active.generation().equals(candidate.signerGeneration()) + && active.kid().equals(candidate.kid())) + .isEmpty() + || correspondence + .publishedActive() + .filter( + active -> + active.generation().equals(candidate.signerGeneration()) + && active.kid().equals(candidate.kid())) + .isEmpty() + || correspondence + .promotionPrivateObservedResourceVersion() + .filter(correspondence.privatePromotionObservedResourceVersion()::equals) + .isEmpty() + || correspondence + .promotionPrivateReceiptDigest() + .filter(correspondence.privatePromotionReceiptDigest()::equals) + .isEmpty() + || correspondence + .activeJwksObservedResourceVersion() + .filter(correspondence.observedPublicResourceVersion()::equals) + .isEmpty() + || correspondence + .activeJwksPublicDataDigest() + .filter(correspondence.publicDataDigest()::equals) + .isEmpty() + || correspondence + .activeJwksReceiptDigest() + .filter(correspondence.publicReceiptDigest()::equals) + .isEmpty() + || !correspondence + .publicConfigMapUid() + .equals(correspondence.publicJwksSourceIdentity().configMapUid())) { + throw new StorageUnavailableException(); + } + return correspondence; + } catch (RuntimeException failure) { + throw new StorageUnavailableException(); + } + } + + private EnvelopeIdentity requireCommittedEnvelopeProof( + Map proof, + AccountGameplayDelegationPendingIdentity identity, + PendingRegistryCandidate candidate, + AccountAuthoritySnapshot authority, + AccountAuthEvidenceBundle bundle) { + Map envelopeProof = requireMap(proof.get("envelope")); + requireExactFields( + envelopeProof, + Set.of( + "operationId", + "requestId", + "tokenHash", + "kid", + "signerGeneration", + "authorityEvidenceBundleSha256", + "issuanceFence", + "responseRecoveryExpiryEpochMillis", + "envelopeSha256", + "envelopeBytesLength")); + long expectedExpiryMillis; + try { + expectedExpiryMillis = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException failure) { + throw new StorageUnavailableException(); + } + Record envelope = + dsl.fetchOne( + "SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, envelope_bytes " + + "FROM account_gameplay_delegation_response_envelopes " + + "WHERE operation_id = ? FOR SHARE", + identity.operationId()); + if (envelope == null) throw new StorageUnavailableException(); + byte[] bytes = envelope.get("envelope_bytes", byte[].class); + String digest = envelope.get("envelope_sha256", String.class); + String tokenHash = envelope.get("token_hash", String.class); + String keyId = envelope.get("signer_kid", String.class); + String signerGeneration = envelope.get("signer_generation", String.class); + long expiry = positive(envelope.get("response_recovery_expiry_epoch_ms", Long.class), "expiry"); + if (bytes == null + || bytes.length == 0 + || bytes.length > 65_610 + || !SHA256.matcher(Objects.toString(digest, "")).matches() + || !digest.equals(sha256(bytes)) + || !identity.operationId().equals(envelope.get("operation_id", UUID.class)) + || !identity.requestId().equals(envelope.get("request_id", UUID.class)) + || !candidate.tokenHash().equals(tokenHash) + || !candidate.kid().equals(keyId) + || !candidate.signerGeneration().equals(signerGeneration) + || !bundle + .canonicalSha256() + .equals(envelope.get("authority_evidence_bundle_sha256", String.class)) + || authority.issuanceFence() + != positive(envelope.get("issuance_fence", Long.class), "issuance fence") + || expiry != expectedExpiryMillis + || !identity.operationId().toString().equals(envelopeProof.get("operationId")) + || !identity.requestId().toString().equals(envelopeProof.get("requestId")) + || !candidate.tokenHash().equals(envelopeProof.get("tokenHash")) + || !candidate.kid().equals(envelopeProof.get("kid")) + || !candidate.signerGeneration().equals(envelopeProof.get("signerGeneration")) + || !bundle.canonicalSha256().equals(envelopeProof.get("authorityEvidenceBundleSha256")) + || !Long.toString(authority.issuanceFence()).equals(envelopeProof.get("issuanceFence")) + || !Long.toString(expiry).equals(envelopeProof.get("responseRecoveryExpiryEpochMillis")) + || !digest.equals(envelopeProof.get("envelopeSha256")) + || !Integer.toString(bytes.length).equals(envelopeProof.get("envelopeBytesLength"))) { + throw new StorageUnavailableException(); + } + EnvelopeHeader header = parseEnvelopeHeader(bytes, expiry); + return new EnvelopeIdentity(digest, bytes.length, expiry, header.keyId()); + } + + private static long positiveCanonicalLong(Object value) { + if (!(value instanceof String text) || !POSITIVE_DECIMAL.matcher(text).matches()) { + throw new StorageUnavailableException(); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException invalid) { + throw new StorageUnavailableException(); + } + } + + private static EnvelopeHeader parseEnvelopeHeader(byte[] bytes, long expectedExpiryMillis) { + final byte[] magic = {'F', 'R', 'E', 'A'}; + final int minimumLength = 4 + 1 + 1 + 1 + Long.BYTES + 12 + 16 + 1; + if (bytes.length < minimumLength + || bytes.length > 65_610 + || bytes[0] != magic[0] + || bytes[1] != magic[1] + || bytes[2] != magic[2] + || bytes[3] != magic[3] + || bytes[4] != 1) { + throw new StorageUnavailableException(); + } + int keyLength = Byte.toUnsignedInt(bytes[5]); + if (keyLength < 1 + || keyLength > 32 + || bytes.length < 6 + keyLength + Long.BYTES + 12 + 16 + 1) { + throw new StorageUnavailableException(); + } + String keyId = new String(bytes, 6, keyLength, StandardCharsets.US_ASCII); + if (!keyId.matches("[A-Za-z0-9_-]{1,32}")) throw new StorageUnavailableException(); + long expiry = ByteBuffer.wrap(bytes, 6 + keyLength, Long.BYTES).getLong(); + if (expiry <= 0L || expiry != expectedExpiryMillis) throw new StorageUnavailableException(); + return new EnvelopeHeader(keyId); + } + + private static boolean sameCanonicalMap(Object actual, Object expected) { + try { + return Arrays.equals(canonicalJson(actual), canonicalJson(expected)); + } catch (RuntimeException failure) { + return false; + } + } + + private static void requireExactFields(Map value, Set fields) { + if (!value.keySet().equals(fields)) throw new StorageUnavailableException(); + } + + /** + * Persists signer-verified, exact pinned-Redis registration and source-projection evidence as one + * immutable non-authorizing PENDING-to-COMMITTED transition. Network work is supplied only as + * private-constructor owner receipts and is complete before this Account transaction begins. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CommittedIssuanceReadback commitPendingCandidate( + UUID requestId, + AccountGameplayDelegationSigner.PendingCandidateVerificationProof signerProof, + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt redisReceipt, + ProjectionObservation projectionObservation, + AccountGameplayDelegationIssuanceCommitService.CommitProof commitProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + Objects.requireNonNull(signerProof, "Signer-owned candidate proof is required"); + Objects.requireNonNull(redisReceipt, "Pinned pending registration receipt is required"); + Objects.requireNonNull(projectionObservation, "Current Account projection is required"); + Objects.requireNonNull(commitProof, "Canonical Account commit proof is required"); + + PendingRegistryCandidate candidate = readPendingRegistryCandidate(requestId); + AccountGameplayDelegationPendingIdentity identity = candidate.identity(); + if (!identity.operationId().equals(signerProof.operationId()) + || !requestId.equals(signerProof.requestId()) + || !identity.accountId().equals(signerProof.accountId()) + || !identity.requestDigest().equals(signerProof.identity().requestDigest()) + || !identity.callerWorkload().equals(signerProof.identity().callerWorkload()) + || !identity.callerContextId().equals(signerProof.identity().callerContextId()) + || !identity.tokenJti().equals(signerProof.tokenJti()) + || identity.issuedAtEpochSecond() != signerProof.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != signerProof.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != signerProof.expiresAtEpochSecond() + || !candidate.tokenHash().equals(signerProof.tokenSha256()) + || !candidate.kid().equals(signerProof.signerKid()) + || !candidate.signerGeneration().equals(signerProof.signerGeneration()) + || candidate.authoritySnapshot().issuanceFence() != signerProof.issuanceFence() + || !candidate.authoritySnapshot().equals(signerProof.authoritySnapshot()) + || !candidate.evidenceBundleReference().equals(signerProof.evidenceBundleReference()) + || !sha256(candidate.canonicalRecordBytes()) + .equals(signerProof.canonicalRegistryRecordSha256()) + || !commitProof.operationId().equals(identity.operationId()) + || !commitProof.requestId().equals(requestId) + || !commitProof.accountId().equals(identity.accountId()) + || !commitProof.requestDigest().equals(identity.requestDigest()) + || !commitProof.tokenSha256().equals(candidate.tokenHash())) { + throw new IdempotencyConflictException(); + } + + IssuerAccountSourceSnapshot current = readCurrentAuthority(identity.accountId()); + AccountAuthoritySnapshot currentAuthority = authoritySnapshot(current); + if (!currentAuthority.equals(candidate.authoritySnapshot()) + || !currentAuthority.equals(signerProof.authoritySnapshot())) { + throw new StaleAuthorityException(); + } + requireExactProjectionObservation(projectionObservation, current); + requireExactRedisReceipt(redisReceipt, candidate); + requireExactSealedEnvelope(signerProof.sealedCandidate(), candidate); + requireCanonicalCommitProof(commitProof, signerProof, redisReceipt, projectionObservation); + + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'COMMITTED', commit_proof_version = 1, commit_proof_sha256 = ?, " + + "commit_proof_canonical_bytes = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND status = 'PENDING' AND token_hash = ? " + + "AND signer_kid = ? AND signer_generation = ? " + + "AND pending_registry_candidate_bytes = ?", + commitProof.sha256(), + commitProof.canonicalBytes(), + requestId, + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + candidate.canonicalRecordBytes()); + if (changed != 1) throw new StaleAuthorityException(); + + Record readback = selectByRequestId(requestId, true); + CommittedIssuanceReadback exact = + decodeCommittedReadback(readback, commitProof.sha256(), commitProof.canonicalBytes()); + requireStoredAuthority(readback, current); + tokenIdentityFences.registerCommittedIssuance(tokenIdentity(readback)); + return exact; + } + + /** + * Reads only the immutable non-authorizing COMMITTED result. A prior exact commit replay never + * invokes the signer, extends Redis TTL, or returns/decrypts the encrypted response envelope. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) + public java.util.Optional readCommittedProof(UUID requestId) { + Objects.requireNonNull(requestId, "Request ID is required"); + Record row = selectByRequestId(requestId, false); + if (row == null) throw new StorageUnavailableException(); + String status = row.get("status", String.class); + if ("PENDING".equals(status)) return java.util.Optional.empty(); + if (!"COMMITTED".equals(status)) throw new StorageUnavailableException(); + String proofSha = row.get("commit_proof_sha256", String.class); + byte[] proofBytes = row.get("commit_proof_canonical_bytes", byte[].class); + CommittedIssuanceReadback exact = decodeCommittedReadback(row, proofSha, proofBytes); + tokenIdentityFences.requireActiveReadback(tokenIdentity(row)); + return java.util.Optional.of(exact); + } + + private static void requireExactProjectionObservation( + ProjectionObservation observation, IssuerAccountSourceSnapshot current) { + byte[][] expected = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(current); + var issuer = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + expected[0], "issuer", GameSessionAccountDelegationProfile.ISSUER); + var account = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + expected[1], "account", current.account().scope().accountId().toString()); + if (!issuer.digest().equals(observation.issuerDigest()) + || !account.digest().equals(observation.accountDigest()) + || issuer.generation() != observation.issuerGeneration() + || !account + .generationValue() + .equals(java.math.BigInteger.valueOf(observation.accountGeneration())) + || !current.issuanceFence().equals(current.account().issuanceFence())) { + throw new StaleAuthorityException(); + } + } + + private static void requireExactRedisReceipt( + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt receipt, + PendingRegistryCandidate candidate) { + AccountGameplayDelegationPendingIdentity identity = candidate.identity(); + long tokenExpiry; + try { + tokenExpiry = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + long margin = Math.subtractExact(receipt.absoluteExpiryMillis(), tokenExpiry); + if (margin < 0L || margin > 300_000L) throw new StorageUnavailableException(); + } catch (ArithmeticException ex) { + throw new StorageUnavailableException(); + } + if (!receipt + .tokenKey() + .equals(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + candidate.tokenHash()) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals(receipt.aclIdentity()) + || !receipt.canonicalRecordSha256().equals(sha256(candidate.canonicalRecordBytes())) + || !receipt.operationId().equals(identity.operationId().toString()) + || !receipt.requestId().equals(identity.requestId().toString()) + || !receipt.requestDigest().equals(identity.requestDigest()) + || !receipt.accountId().equals(identity.accountId().toString()) + || !receipt.tokenJti().equals(identity.tokenJti().toString()) + || !receipt.tokenHash().equals(candidate.tokenHash()) + || !receipt.kid().equals(candidate.kid()) + || !receipt.signerGeneration().equals(candidate.signerGeneration()) + || receipt.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || receipt.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || receipt.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || receipt.issuanceFence() != candidate.authoritySnapshot().issuanceFence() + || receipt.registryVersion() != 1L + || !receipt.evidenceBundleReference().equals(candidate.evidenceBundleReference()) + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L) { + throw new StorageUnavailableException(); + } + } + + private void requireExactSealedEnvelope( + AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation sealed, + PendingRegistryCandidate candidate) { + Record envelope = + dsl.fetchOne( + "SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, " + + "octet_length(envelope_bytes) AS envelope_bytes_length " + + "FROM account_gameplay_delegation_response_envelopes " + + "WHERE operation_id = ? FOR SHARE", + candidate.identity().operationId()); + if (envelope == null + || !Objects.equals(envelope.get("operation_id", UUID.class), sealed.operationId()) + || !Objects.equals(envelope.get("request_id", UUID.class), sealed.requestId()) + || !Objects.equals(envelope.get("token_hash", String.class), candidate.tokenHash()) + || !Objects.equals(envelope.get("signer_kid", String.class), candidate.kid()) + || !Objects.equals( + envelope.get("signer_generation", String.class), candidate.signerGeneration()) + || !Objects.equals( + envelope.get("authority_evidence_bundle_sha256", String.class), + sealed.authorityEvidenceBundleSha256()) + || !Objects.equals(envelope.get("issuance_fence", Long.class), sealed.issuanceFence()) + || !Objects.equals( + envelope.get("response_recovery_expiry_epoch_ms", Long.class), + sealed.responseRecoveryExpiryEpochMillis()) + || !Objects.equals(envelope.get("envelope_sha256", String.class), sealed.envelopeSha256()) + || !Objects.equals( + envelope.get("envelope_bytes_length", Integer.class), sealed.envelopeBytesLength())) { + throw new StorageUnavailableException(); + } + } + + private static void requireCanonicalCommitProof( + AccountGameplayDelegationIssuanceCommitService.CommitProof commitProof, + AccountGameplayDelegationSigner.PendingCandidateVerificationProof signerProof, + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt redisReceipt, + ProjectionObservation projectionObservation) { + byte[] bytes = commitProof.canonicalBytes(); + if (bytes.length == 0 + || bytes.length > MAX_COMMIT_PROOF_BYTES + || !sha256(bytes).equals(commitProof.sha256()) + || !commitProof.operationId().equals(signerProof.operationId()) + || !commitProof.requestId().equals(signerProof.requestId()) + || !commitProof.accountId().equals(signerProof.accountId()) + || !commitProof.requestDigest().equals(signerProof.identity().requestDigest()) + || !commitProof.tokenSha256().equals(redisReceipt.tokenHash())) { + throw new StorageUnavailableException(); + } + Map proof = parseCommitProof(bytes); + Object identityValue = proof.get("identity"); + Object registryValue = proof.get("registry"); + Object bundleValue = proof.get("bundle"); + Object authorityValue = proof.get("authority"); + Object signerValue = proof.get("signer"); + Object envelopeValue = proof.get("envelope"); + var identity = requireMap(identityValue); + var registry = requireMap(registryValue); + var bundle = requireMap(bundleValue); + var authority = requireMap(authorityValue); + var signer = requireMap(signerValue); + var envelope = requireMap(envelopeValue); + var correspondence = requireMap(signer.get("correspondence")); + var pending = signerProof.identity(); + var snapshot = signerProof.authoritySnapshot(); + var bundleReference = signerProof.evidenceBundleReference(); + var sealed = signerProof.sealedCandidate(); + long expectedExpiryMillis; + try { + expectedExpiryMillis = Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException ex) { + throw new StorageUnavailableException(); + } + if (!identity + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "accountId", + "requestDigest", + "callerWorkload", + "callerContextId", + "tokenJti", + "tokenGeneration", + "issuedAtEpochSecond", + "notBeforeEpochSecond", + "expiresAtEpochSecond", + "tokenSha256")) + || !registry + .keySet() + .equals( + Set.of( + "state", + "registryVersion", + "tokenKey", + "tokenHash", + "kid", + "signerGeneration", + "operationId", + "requestId", + "requestDigest", + "absoluteExpiryMillis", + "localAofCount", + "replicaAofCount", + "outcome", + "canonicalRecordSha256", + "evidenceBundleSha256", + "aclIdentity")) + || !bundle + .keySet() + .equals( + Set.of( + "bundleVersion", + "sourceVersion", + "sourceFence", + "linearization", + "canonicalSha256")) + || !authority + .keySet() + .equals( + Set.of( + "issuerGeneration", + "issuerSourceVersion", + "accountGeneration", + "accountSourceVersion", + "issuanceFence", + "issuanceFenceSourceVersion", + "authorityTuple", + "authoritySourceVersions", + "issuerProjectionGeneration", + "accountProjectionGeneration", + "issuerProjectionSha256", + "accountProjectionSha256")) + || !signer + .keySet() + .equals( + Set.of( + "promotionStatus", + "promotionOperationId", + "generationOperationId", + "targetKid", + "targetGeneration", + "correspondenceSha256", + "correspondence")) + || !envelope + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "tokenHash", + "kid", + "signerGeneration", + "authorityEvidenceBundleSha256", + "issuanceFence", + "responseRecoveryExpiryEpochMillis", + "envelopeSha256", + "envelopeBytesLength")) + || !AccountGameplayDelegationIssuanceCommitService.COMMIT_PROOF_SCHEMA.equals( + proof.get("schema")) + || !pending.operationId().toString().equals(identity.get("operationId")) + || !pending.requestId().toString().equals(identity.get("requestId")) + || !pending.accountId().toString().equals(identity.get("accountId")) + || !pending.requestDigest().equals(identity.get("requestDigest")) + || !pending.callerWorkload().equals(identity.get("callerWorkload")) + || !pending.callerContextId().toString().equals(identity.get("callerContextId")) + || !pending.tokenJti().toString().equals(identity.get("tokenJti")) + || !"1".equals(identity.get("tokenGeneration")) + || !Long.toString(pending.issuedAtEpochSecond()).equals(identity.get("issuedAtEpochSecond")) + || !Long.toString(pending.notBeforeEpochSecond()) + .equals(identity.get("notBeforeEpochSecond")) + || !Long.toString(pending.expiresAtEpochSecond()) + .equals(identity.get("expiresAtEpochSecond")) + || !signerProof.tokenSha256().equals(identity.get("tokenSha256")) + || !signerProof.tokenSha256().equals(proof.get("tokenSha256")) + || !redisReceipt.canonicalRecordSha256().equals(proof.get("registryRecordSha256")) + || !"pending".equals(registry.get("state")) + || !"1".equals(registry.get("registryVersion")) + || !redisReceipt.tokenKey().equals(registry.get("tokenKey")) + || !redisReceipt.tokenHash().equals(registry.get("tokenHash")) + || !redisReceipt.kid().equals(registry.get("kid")) + || !redisReceipt.signerGeneration().equals(registry.get("signerGeneration")) + || !redisReceipt.operationId().equals(registry.get("operationId")) + || !redisReceipt.requestId().equals(registry.get("requestId")) + || !redisReceipt.requestDigest().equals(registry.get("requestDigest")) + || !Long.toString(redisReceipt.absoluteExpiryMillis()) + .equals(registry.get("absoluteExpiryMillis")) + || !Long.toString(redisReceipt.localAofCount()).equals(registry.get("localAofCount")) + || !Long.toString(redisReceipt.replicaAofCount()).equals(registry.get("replicaAofCount")) + || !redisReceipt.outcome().name().equals(registry.get("outcome")) + || !redisReceipt.canonicalRecordSha256().equals(registry.get("canonicalRecordSha256")) + || !bundleReference.canonicalSha256().equals(registry.get("evidenceBundleSha256")) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals( + registry.get("aclIdentity")) + || !bundleReference.toMap().equals(bundle) + || !Long.toString(snapshot.issuerGeneration()).equals(authority.get("issuerGeneration")) + || !Long.toString(snapshot.issuerSourceVersion()) + .equals(authority.get("issuerSourceVersion")) + || !Long.toString(snapshot.accountGeneration()).equals(authority.get("accountGeneration")) + || !Long.toString(snapshot.accountSourceVersion()) + .equals(authority.get("accountSourceVersion")) + || !Long.toString(snapshot.issuanceFence()).equals(authority.get("issuanceFence")) + || !Long.toString(snapshot.issuanceFenceSourceVersion()) + .equals(authority.get("issuanceFenceSourceVersion")) + || !Arrays.equals( + canonicalJson(authorityTuple(snapshot)), canonicalJson(authority.get("authorityTuple"))) + || !Arrays.equals( + canonicalJson(snapshot.sourceVersions()), + canonicalJson(authority.get("authoritySourceVersions"))) + || !Long.toString(projectionObservation.issuerGeneration()) + .equals(authority.get("issuerProjectionGeneration")) + || !Long.toString(projectionObservation.accountGeneration()) + .equals(authority.get("accountProjectionGeneration")) + || !projectionObservation.issuerDigest().equals(authority.get("issuerProjectionSha256")) + || !projectionObservation.accountDigest().equals(authority.get("accountProjectionSha256")) + || !"COMMITTED".equals(signer.get("promotionStatus")) + || !signerProof + .signerCorrespondence() + .promotionOperationId() + .toString() + .equals(signer.get("promotionOperationId")) + || !signerProof + .signerCorrespondence() + .generationOperationId() + .toString() + .equals(signer.get("generationOperationId")) + || !signerProof.signerKid().equals(signer.get("targetKid")) + || !signerProof.signerGeneration().equals(signer.get("targetGeneration")) + || !SHA256.matcher(Objects.toString(signer.get("correspondenceSha256"), "")).matches() + || !sha256(canonicalJson(correspondence)).equals(signer.get("correspondenceSha256")) + || !pending.operationId().toString().equals(envelope.get("operationId")) + || !pending.requestId().toString().equals(envelope.get("requestId")) + || !signerProof.tokenSha256().equals(envelope.get("tokenHash")) + || !signerProof.signerKid().equals(envelope.get("kid")) + || !signerProof.signerGeneration().equals(envelope.get("signerGeneration")) + || !bundleReference.canonicalSha256().equals(envelope.get("authorityEvidenceBundleSha256")) + || !Long.toString(signerProof.issuanceFence()).equals(envelope.get("issuanceFence")) + || !Long.toString(sealed.responseRecoveryExpiryEpochMillis()) + .equals(envelope.get("responseRecoveryExpiryEpochMillis")) + || !sealed.envelopeSha256().equals(envelope.get("envelopeSha256")) + || !Integer.toString(sealed.envelopeBytesLength()) + .equals(envelope.get("envelopeBytesLength")) + || redisReceipt.absoluteExpiryMillis() < expectedExpiryMillis + || redisReceipt.absoluteExpiryMillis() - expectedExpiryMillis > 300_000L + || redisReceipt.localAofCount() < 1L + || redisReceipt.replicaAofCount() < 1L + || !redisReceipt.outcome().name().equals(registry.get("outcome")) + || !redisReceipt.canonicalRecordSha256().equals(registry.get("canonicalRecordSha256"))) { + throw new StorageUnavailableException(); + } + } + + private static Map requireMap(Object value) { + if (!(value instanceof Map map)) throw new StorageUnavailableException(); + return map; + } + + private CommittedIssuanceReadback decodeCommittedReadback( + Record row, String expectedSha256, byte[] expectedBytes) { + Object storedVersion = row == null ? null : row.get("commit_proof_version"); + if (row == null + || !"COMMITTED".equals(row.get("status", String.class)) + || !(storedVersion instanceof Number version) + || version.intValue() != 1 + || row.get("committed_at") == null) { + throw new StorageUnavailableException(); + } + String storedSha = row.get("commit_proof_sha256", String.class); + byte[] storedBytes = row.get("commit_proof_canonical_bytes", byte[].class); + if (storedSha == null + || !SHA256.matcher(storedSha).matches() + || storedBytes == null + || storedBytes.length == 0 + || storedBytes.length > MAX_COMMIT_PROOF_BYTES + || !storedSha.equals(sha256(storedBytes)) + || (expectedSha256 != null && !expectedSha256.equals(storedSha)) + || (expectedBytes != null && !Arrays.equals(expectedBytes, storedBytes))) { + throw new StorageUnavailableException(); + } + Map proof = parseCommitProof(storedBytes); + AccountGameplayDelegationPendingIdentity identity = identity(row); + Object proofIdentity = proof.get("identity"); + if (!(proofIdentity instanceof Map fields) + || !fields + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "accountId", + "requestDigest", + "callerWorkload", + "callerContextId", + "tokenJti", + "tokenGeneration", + "issuedAtEpochSecond", + "notBeforeEpochSecond", + "expiresAtEpochSecond", + "tokenSha256")) + || !AccountGameplayDelegationIssuanceCommitService.COMMIT_PROOF_SCHEMA.equals( + proof.get("schema")) + || !identity.operationId().toString().equals(fields.get("operationId")) + || !identity.requestId().toString().equals(fields.get("requestId")) + || !identity.accountId().toString().equals(fields.get("accountId")) + || !identity.requestDigest().equals(fields.get("requestDigest")) + || !identity.tokenJti().toString().equals(fields.get("tokenJti")) + || !"1".equals(fields.get("tokenGeneration")) + || !Long.toString(identity.issuedAtEpochSecond()).equals(fields.get("issuedAtEpochSecond")) + || !Long.toString(identity.notBeforeEpochSecond()) + .equals(fields.get("notBeforeEpochSecond")) + || !Long.toString(identity.expiresAtEpochSecond()) + .equals(fields.get("expiresAtEpochSecond")) + || !identity.callerWorkload().equals(fields.get("callerWorkload")) + || !identity.callerContextId().toString().equals(fields.get("callerContextId")) + || !Objects.equals(row.get("token_hash", String.class), fields.get("tokenSha256")) + || !identity.tokenJti().toString().equals(row.get("token_jti", UUID.class).toString()) + || !Objects.equals(row.get("token_hash", String.class), proof.get("tokenSha256"))) { + throw new StorageUnavailableException(); + } + return new CommittedIssuanceReadback( + identity.operationId(), + identity.requestId(), + identity.accountId(), + identity.requestDigest(), + row.get("token_hash", String.class), + row.get("signer_kid", String.class), + row.get("signer_generation", String.class), + storedSha); + } + + private static Map parseCommitProof(byte[] bytes) { + try { + Map parsed = JSON.readValue(bytes, new TypeReference<>() {}); + if (!parsed + .keySet() + .equals( + Set.of( + "schema", + "identity", + "tokenSha256", + "registryRecordSha256", + "registry", + "bundle", + "authority", + "signer", + "envelope")) + || !Arrays.equals(bytes, canonicalProofJson(parsed))) { + throw new StorageUnavailableException(); + } + return parsed; + } catch (RuntimeException ex) { + if (ex instanceof StorageUnavailableException unavailable) throw unavailable; + throw new StorageUnavailableException(); + } + } + + private static byte[] canonicalProofJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException ex) { + throw new StorageUnavailableException(); + } + } + + /** Versioned request digest over the immutable pre-sign operation and locked authority tuple. */ + public static String requestDigest(PendingIntent intent) { + Objects.requireNonNull(intent, "Intent is required"); + Map value = + Map.ofEntries( + Map.entry("schema", "account-game-session-delegation-issuance/v2"), + Map.entry("operationId", intent.operationId().toString()), + Map.entry("requestId", intent.requestId().toString()), + Map.entry("accountId", intent.authoritySnapshot().accountId().toString()), + Map.entry("callerWorkload", intent.callerWorkload()), + Map.entry("callerContextId", intent.callerContextId().toString()), + Map.entry( + "credentialRequestBinding", + Map.of( + "digestSchemaVersion", + intent.credentialRequestBinding().digestSchemaVersion(), + "digestKeyId", + intent.credentialRequestBinding().digestKeyId(), + "credentialRequestDigest", + intent.credentialRequestBinding().credentialRequestDigest())), + Map.entry("jti", intent.tokenJti().toString()), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", intent.expiresAtEpochSecond()), + Map.entry("authorityTuple", authorityTuple(intent.authoritySnapshot())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence())), + Map.entry("authoritySourceVersions", intent.authoritySnapshot().sourceVersions())); + return sha256(canonicalJson(value)); + } + + private void insertIntent( + PendingIntent intent, String digest, IssuerAccountSourceSnapshot current) { + AccountAuthoritySnapshot authority = authoritySnapshot(current); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "request_digest_version, request_digest, credential_request_digest_version, " + + "credential_digest_key_id, credential_request_digest, token_jti, token_generation, " + + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " + + "authority_issuer_generation, authority_issuer_source_version, " + + "authority_account_generation, authority_account_source_version, issuance_fence, " + + "issuance_fence_source_version, authority_tuple_canonical_bytes, " + + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, 2, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (request_id) DO NOTHING", + intent.operationId(), + intent.requestId(), + authority.accountId(), + intent.callerWorkload(), + intent.callerContextId(), + digest, + intent.credentialRequestBinding().digestSchemaVersion(), + intent.credentialRequestBinding().digestKeyId(), + intent.credentialRequestBinding().credentialRequestDigest(), + intent.tokenJti(), + intent.issuedAtEpochSecond(), + intent.notBeforeEpochSecond(), + intent.expiresAtEpochSecond(), + authority.issuerGeneration(), + authority.issuerSourceVersion(), + authority.accountGeneration(), + authority.accountSourceVersion(), + authority.issuanceFence(), + authority.issuanceFenceSourceVersion(), + canonicalJson(authorityTuple(authority)), + EMPTY_OBJECT, + canonicalJson(authority.sourceVersions())); + if (inserted < 0 || inserted > 1) throw new StorageUnavailableException(); + } + + private Record selectByRequestId(UUID requestId, boolean lock) { + return dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE request_id = ?" + (lock ? " FOR UPDATE" : ""), + requestId); + } + + private void lockRequestId(UUID requestId) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "account-gameplay-delegation-request/" + requestId); + } + + private static void requireRequestId(UUID value) { + Objects.requireNonNull(value, "Non-nil high-entropy UUID is required"); + if (value.equals(new UUID(0L, 0L)) || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Non-nil high-entropy UUID is required"); + } + } + + private static boolean isReplayableGameplayLoginStatus(String status) { + return "PENDING".equals(status) || "COMMITTED".equals(status); + } + + private IssuerAccountSourceSnapshot readAndCompareAuthority(PendingIntent intent) { + IssuerAccountSourceSnapshot current = + readCurrentAuthority(intent.authoritySnapshot().accountId()); + AccountAuthoritySnapshot expected = intent.authoritySnapshot(); + if (!authoritySnapshot(current).equals(expected)) throw new StaleAuthorityException(); + return current; + } + + private IssuerAccountSourceSnapshot readCurrentAuthority(UUID accountId) { + tokenIdentityFences.lockAccountForUpdate(accountId); + IssuerAccountSourceSnapshot snapshot = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + if (snapshot.issuer().scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ISSUER + || !GameSessionAccountDelegationProfile.ISSUER.equals(snapshot.issuer().scope().issuerId()) + || snapshot.issuer().scope().accountId() != null + || snapshot.issuer().scope().tenantId() != null + || snapshot.account().scope().kind() + != AccountAuthorityGenerationRepository.ScopeKind.ACCOUNT + || !accountId.equals(snapshot.account().scope().accountId()) + || snapshot.account().scope().issuerId() != null + || snapshot.account().scope().tenantId() != null + || !accountId.equals(snapshot.issuanceFence().accountId()) + || !Objects.equals(snapshot.account().issuanceFence(), snapshot.issuanceFence())) { + throw new IllegalStateException("Exact non-tenant Account authority snapshot is required"); + } + return snapshot; + } + + private static TokenIdentity tokenIdentity(Record row) { + return new TokenIdentity( + row.get("account_uuid", UUID.class), row.get("operation_id", UUID.class), + row.get("request_id", UUID.class), row.get("token_hash", String.class), + row.get("token_jti", UUID.class), row.get("not_before_epoch_second", Long.class), + row.get("token_generation", Long.class), row.get("issuance_fence", Long.class)); + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot snapshot) { + AccountSecurityCutoff cutoff = + snapshot + .account() + .accountSecurityCutoff() + .map( + value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())) + .orElse(null); + return new AccountAuthoritySnapshot( + snapshot.account().scope().accountId(), + snapshot.issuer().generation(), + snapshot.issuer().sourceVersion(), + snapshot.account().generation(), + snapshot.account().sourceVersion(), + snapshot.issuanceFence().value(), + snapshot.issuanceFence().sourceVersion(), + java.util.Optional.ofNullable(cutoff)); + } + + private static Map authorityTuple(AccountAuthoritySnapshot snapshot) { + return GameSessionAccountDelegationProfile.authorityTuple( + snapshot.issuerGeneration(), + snapshot.accountGeneration(), + snapshot.accountSecurityCutoff()); + } + + private static Map sourceVersionsMap(IssuerAccountSourceSnapshot snapshot) { + return authoritySnapshot(snapshot).sourceVersions(); + } + + private static void requireExactIntent( + Record row, PendingIntent intent, String digest, IssuerAccountSourceSnapshot current) { + AccountGameplayDelegationPendingIdentity identity = identity(row); + if (!identity.operationId().equals(intent.operationId()) + || !identity.requestId().equals(intent.requestId()) + || !identity.accountId().equals(intent.authoritySnapshot().accountId()) + || !identity.callerWorkload().equals(intent.callerWorkload()) + || !identity.callerContextId().equals(intent.callerContextId()) + || !identity.credentialRequestBinding().equals(intent.credentialRequestBinding()) + || !identity.tokenJti().equals(intent.tokenJti()) + || identity.issuedAtEpochSecond() != intent.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != intent.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != intent.expiresAtEpochSecond() + || !identity.requestDigest().equals(digest)) { + throw new IdempotencyConflictException(); + } + requireStoredAuthority(row, current); + if (!"PENDING".equals(row.get("status", String.class))) { + throw new StorageUnavailableException(); + } + } + + private static void requireStoredAuthority(Record row, IssuerAccountSourceSnapshot current) { + AccountAuthoritySnapshot authority = authoritySnapshot(current); + if (!Objects.equals( + row.get("authority_issuer_generation", Long.class), authority.issuerGeneration()) + || !Objects.equals( + row.get("authority_issuer_source_version", Long.class), authority.issuerSourceVersion()) + || !Objects.equals( + row.get("authority_account_generation", Long.class), authority.accountGeneration()) + || !Objects.equals( + row.get("authority_account_source_version", Long.class), + authority.accountSourceVersion()) + || !Objects.equals(row.get("issuance_fence", Long.class), authority.issuanceFence()) + || !Objects.equals( + row.get("issuance_fence_source_version", Long.class), + authority.issuanceFenceSourceVersion()) + || !Arrays.equals( + row.get("authority_tuple_canonical_bytes", byte[].class), + canonicalJson(authorityTuple(authority))) + || !Arrays.equals(row.get("membership_version_canonical_bytes", byte[].class), EMPTY_OBJECT) + || !Arrays.equals( + row.get("authority_source_versions_canonical_bytes", byte[].class), + canonicalJson(authority.sourceVersions()))) { + throw new StaleAuthorityException(); + } + } + + private static void requireExactSigningBundle( + AccountAuthEvidenceBundle bundle, + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authority, + IssuerAccountSourceSnapshot current) { + try { + Map fields = bundle.fields(); + if (!AccountAuthEvidenceBundle.SCHEMA.equals(fields.get("schema")) + || !GameSessionAccountDelegationProfile.ISSUER.equals(fields.get("issuer")) + || !GameSessionAccountDelegationProfile.PROFILE.equals(fields.get("profile")) + || !GameSessionAccountDelegationProfile.AUDIENCE.equals(fields.get("audience"))) { + throw new PendingCandidateUnavailableException(); + } + requireCanonicalSubtree( + fields.get("scope"), + Map.of( + "kind", + "account", + "accountId", + identity.accountId().toString(), + "tenantIds", + java.util.List.of())); + requireCanonicalSubtree( + fields.get("operation"), + Map.of( + "operationId", identity.operationId().toString(), + "requestId", identity.requestId().toString(), + "requestDigest", identity.requestDigest(), + "callerWorkload", identity.callerWorkload(), + "callerContextId", identity.callerContextId().toString(), + "accountId", identity.accountId().toString())); + requireCanonicalSubtree( + fields.get("tokenIdentity"), + Map.of( + "jti", identity.tokenJti().toString(), + "tokenGeneration", "1", + "iat", identity.issuedAtEpochSecond(), + "nbf", identity.notBeforeEpochSecond(), + "exp", identity.expiresAtEpochSecond())); + requireCanonicalSubtree(fields.get("authorityTuple"), authorityTuple(authority)); + requireCanonicalSubtree(fields.get("membershipVersion"), Map.of()); + Object issuanceFence = fields.get("issuanceFence"); + if (!(issuanceFence instanceof String fence) + || !Long.toString(authority.issuanceFence()).equals(fence)) { + throw new PendingCandidateUnavailableException(); + } + requireCanonicalSubtree(fields.get("authoritySourceVersions"), sourceVersionStrings(current)); + requireCanonicalSubtree(fields.get("accountIdentitySource"), accountIdentitySource(current)); + requireCanonicalSubtree(fields.get("outboxCheckpoints"), outboxCheckpoints(current)); + } catch (RuntimeException ex) { + if (ex instanceof PendingCandidateUnavailableException unavailable) throw unavailable; + throw new PendingCandidateUnavailableException(); + } + } + + private AccountAuthEvidenceBundle requireCurrentEvidenceBundle( + UUID requestId, + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authority, + IssuerAccountSourceSnapshot current) { + if (evidenceBundles == null) throw new PendingCandidateUnavailableException(); + AccountAuthEvidenceBundle captured; + AccountAuthEvidenceBundle stored; + try { + captured = evidenceBundles.captureAndPersist(requestId); + stored = evidenceBundles.readStoredNonAuthorizingValue(identity.operationId()); + } catch (RuntimeException ex) { + throw new PendingCandidateUnavailableException(); + } + if (!MessageDigest.isEqual(captured.canonicalBytes(), stored.canonicalBytes())) { + throw new PendingCandidateUnavailableException(); + } + requireExactSigningBundle(stored, identity, authority, current); + return stored; + } + + private static EvidenceBundleReference evidenceBundleReference(AccountAuthEvidenceBundle bundle) { + Object value = bundle.fields().get("bundleRef"); + if (!(value instanceof Map reference)) { + throw new PendingCandidateUnavailableException(); + } + Object bundleVersion = reference.get("bundleVersion"); + Object sourceVersion = reference.get("sourceVersion"); + Object sourceFence = reference.get("sourceFence"); + Object linearization = reference.get("linearization"); + if (!(bundleVersion instanceof String version) + || !(sourceVersion instanceof String source) + || !(sourceFence instanceof String fence) + || !(linearization instanceof String xid)) { + throw new PendingCandidateUnavailableException(); + } + try { + return new EvidenceBundleReference(version, source, fence, xid, bundle.canonicalSha256()); + } catch (RuntimeException ex) { + throw new PendingCandidateUnavailableException(); + } + } + + private static AccountAuthEvidenceBundleRepository defaultEvidenceBundles(DSLContext dsl) { + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + return new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + } + + private static void requireCanonicalSubtree(Object actual, Object expected) { + if (!Arrays.equals(canonicalJson(actual), canonicalJson(expected))) { + throw new PendingCandidateUnavailableException(); + } + } + + private static Map sourceVersionStrings(IssuerAccountSourceSnapshot current) { + AccountAuthoritySnapshot authority = authoritySnapshot(current); + return Map.of( + "issuerSourceVersion", Long.toString(authority.issuerSourceVersion()), + "accountSourceVersion", Long.toString(authority.accountSourceVersion()), + "issuanceFenceSourceVersion", Long.toString(authority.issuanceFenceSourceVersion())); + } + + private static Map accountIdentitySource(IssuerAccountSourceSnapshot current) { + var account = current.account(); + if (account.accountSourceNumericId() == null || account.accountUuidProvenance() == null) { + throw new PendingCandidateUnavailableException(); + } + String sourceId = Long.toString(account.accountSourceNumericId()); + return Map.of( + "sourceRowId", sourceId, + "provenance", account.accountUuidProvenance(), + "sourceNumericId", sourceId); + } + + private static java.util.List> outboxCheckpoints( + IssuerAccountSourceSnapshot current) { + java.util.List> result = new java.util.ArrayList<>(2); + for (var source : java.util.List.of(current.account(), current.issuer())) { + var checkpoint = source.checkpoint(); + Map value = new java.util.LinkedHashMap<>(); + value.put("outboxStreamKey", checkpoint.outboxStreamKey()); + value.put("outboxSequence", Long.toString(checkpoint.sequence())); + if (checkpoint.sequence() > 0L) { + value.put("sourceEventId", checkpoint.sourceEventId().orElseThrow()); + value.put("sourceEventDigest", checkpoint.sourceEventDigest().orElseThrow()); + } + result.add(Map.copyOf(value)); + } + return java.util.List.copyOf(result); + } + + private static AccountGameplayDelegationPendingIdentity identity(Record row) { + try { + if (row.get("request_digest_version", Short.class) == null + || row.get("request_digest_version", Short.class).intValue() != REQUEST_DIGEST_VERSION) { + throw new StorageUnavailableException(); + } + return new AccountGameplayDelegationPendingIdentity( + row.get("operation_id", UUID.class), + row.get("request_id", UUID.class), + row.get("account_uuid", UUID.class), + row.get("caller_workload", String.class), + row.get("caller_context_id", UUID.class), + new AccountGameplayCredentialRequestBinding( + row.get("credential_request_digest_version", Short.class).intValue(), + row.get("credential_digest_key_id", String.class), + row.get("credential_request_digest", String.class)), + row.get("request_digest", String.class), + row.get("token_jti", UUID.class), + positive(row.get("issued_at_epoch_second", Long.class), "issued-at"), + positive(row.get("not_before_epoch_second", Long.class), "not-before"), + positive(row.get("expires_at_epoch_second", Long.class), "expiry")); + } catch (RuntimeException ex) { + throw new StorageUnavailableException(); + } + } + + private static PendingOperation decodeOperation(Record row) { + AccountGameplayDelegationPendingIdentity identity = identity(row); + return new PendingOperation( + identity.operationId(), + identity.requestId(), + identity.requestDigest(), + identity.tokenJti(), + row.get("token_hash", String.class) != null); + } + + private static byte[] canonicalJson(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (canonical.length == 0 || canonical.length > MAX_INTENT_BYTES) { + throw new IllegalArgumentException("Account issuance metadata exceeds its finite bound"); + } + return canonical; + } catch (IOException ex) { + throw new StorageUnavailableException(); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable"); + } + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0L) + throw new IllegalArgumentException(field + " must be positive"); + return value; + } + + private static Long requireJsonInteger(Object value) { + if (!(value instanceof Number number)) throw new StorageUnavailableException(); + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) throw new StorageUnavailableException(); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException ex) { + throw new StorageUnavailableException(); + } + } + + private static void requirePositiveDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a canonical positive decimal"); + } + try { + Long.parseLong(value); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException(field + " exceeds its supported range"); + } + } + + private static void requireWritableAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account gameplay delegation issuance requires a writable Account transaction"); + } + } + + public record PendingIntent( + UUID operationId, + UUID requestId, + String callerWorkload, + UUID callerContextId, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + AccountAuthoritySnapshot authoritySnapshot, + AccountGameplayCredentialRequestBinding credentialRequestBinding) { + public PendingIntent { + requireUuid(operationId, "operationId"); + requireUuid(requestId, "requestId"); + requireUuid(callerContextId, "callerContextId"); + requireUuid(tokenJti, "token jti"); + if (callerWorkload == null + || callerWorkload.length() > 256 + || !GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(callerWorkload) + .matches()) { + throw new IllegalArgumentException("Exact Game Session workload identity is required"); + } + Objects.requireNonNull(authoritySnapshot, "Expected Account authority snapshot is required"); + Objects.requireNonNull( + credentialRequestBinding, "Keyed credential request binding is required"); + if (issuedAtEpochSecond <= 0L + || notBeforeEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || notBeforeEpochSecond > issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw new IllegalArgumentException("Delegation token time bounds are invalid"); + } + try { + if (Math.subtractExact(expiresAtEpochSecond, issuedAtEpochSecond) <= 0L + || Math.subtractExact(expiresAtEpochSecond, issuedAtEpochSecond) + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw new IllegalArgumentException("Delegation token time bounds are invalid"); + } + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Delegation token time bounds are invalid"); + } + } + + private static void requireUuid(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (value.equals(new UUID(0L, 0L)) || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException(field + " must be a non-zero high-entropy UUID"); + } + } + + @Override + public String toString() { + return "PendingIntent[redacted]"; + } + } + + public record PendingOperation( + UUID operationId, + UUID requestId, + String requestDigest, + UUID tokenJti, + boolean candidateBound) { + @Override + public String toString() { + return "PendingOperation[redacted]"; + } + } + + public enum GameplayLoginReplayState { + PENDING, + COMMITTED + } + + /** Exact current request replay readback; no token or envelope bytes are included. */ + public static final class GameplayLoginReplayReadback { + private final AccountGameplayDelegationPendingIdentity identity; + private final PendingOperation operation; + private final GameplayLoginReplayState state; + private final boolean created; + + private GameplayLoginReplayReadback( + AccountGameplayDelegationPendingIdentity identity, + PendingOperation operation, + GameplayLoginReplayState state, + CommittedIssuanceReadback committedProof, + boolean created) { + this.identity = Objects.requireNonNull(identity); + this.operation = Objects.requireNonNull(operation); + this.state = Objects.requireNonNull(state); + this.created = created; + if (!identity.operationId().equals(operation.operationId()) + || !identity.requestId().equals(operation.requestId()) + || !identity.tokenJti().equals(operation.tokenJti())) { + throw new StorageUnavailableException(); + } + if (state == GameplayLoginReplayState.COMMITTED) { + if (created + || !operation.candidateBound() + || committedProof == null + || !identity.operationId().equals(committedProof.operationId()) + || !identity.requestId().equals(committedProof.requestId()) + || !identity.accountId().equals(committedProof.accountId()) + || !identity.requestDigest().equals(committedProof.requestDigest())) { + throw new StorageUnavailableException(); + } + } else if (committedProof != null) { + throw new StorageUnavailableException(); + } + } + + public AccountGameplayDelegationPendingIdentity identity() { + return identity; + } + + public PendingOperation operation() { + return operation; + } + + public GameplayLoginReplayState state() { + return state; + } + + public boolean created() { + return created; + } + + @Override + public String toString() { + return "GameplayLoginReplayReadback[non-authorizing,redacted]"; + } + } + + /** Exact durable COMMITTED metadata only; this is not token validation or issuance authority. */ + public record CommittedIssuanceReadback( + UUID operationId, + UUID requestId, + UUID accountId, + String requestDigest, + String tokenHash, + String signerKid, + String signerGeneration, + String proofSha256) { + public CommittedIssuanceReadback { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + if (requestDigest == null + || !SHA256.matcher(requestDigest).matches() + || tokenHash == null + || !SHA256.matcher(tokenHash).matches() + || signerKid == null + || !signerKid.matches("[A-Za-z0-9_-]{1,64}") + || proofSha256 == null + || !SHA256.matcher(proofSha256).matches()) { + throw new IllegalArgumentException("Account committed issuance readback is malformed"); + } + requirePositiveDecimal(signerGeneration, "signerGeneration"); + } + + @Override + public String toString() { + return "CommittedIssuanceReadback[non-authorizing]"; + } + } + + public record BoundTokenCandidate( + UUID requestId, String tokenHash, String kid, String signerGeneration) { + public BoundTokenCandidate { + Objects.requireNonNull(requestId, "Request ID is required"); + if (tokenHash == null || !SHA256.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Token hash must be lowercase SHA-256 hex"); + } + if (kid == null || !kid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Signer kid is malformed"); + } + requirePositiveDecimal(signerGeneration, "signerGeneration"); + } + + @Override + public String toString() { + return "BoundTokenCandidate[redacted]"; + } + } + + public record PendingRegistryCandidate( + AccountGameplayDelegationPendingIdentity identity, + String tokenHash, + String kid, + String signerGeneration, + long expiresAtEpochSecond, + byte[] canonicalRecordBytes, + AccountAuthoritySnapshot authoritySnapshot, + EvidenceBundleReference evidenceBundleReference) { + public PendingRegistryCandidate { + canonicalRecordBytes = canonicalRecordBytes.clone(); + Objects.requireNonNull(identity); + Objects.requireNonNull(authoritySnapshot); + Objects.requireNonNull(evidenceBundleReference); + } + + @Override + public byte[] canonicalRecordBytes() { + return canonicalRecordBytes.clone(); + } + + @Override + public String toString() { + return "PendingRegistryCandidate[redacted]"; + } + } + + /** + * Repository-issued exact pre-sign identity plus the persisted full Account evidence value. + * Construction is private so callers cannot turn a supplied DTO into a signing authorization. + */ + public static final class PendingSigningIdentity { + private final AccountGameplayDelegationPendingIdentity identity; + private final AccountAuthoritySnapshot authoritySnapshot; + private final AccountAuthEvidenceBundle evidenceBundle; + private final Optional persistedCandidate; + + private PendingSigningIdentity( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + AccountAuthEvidenceBundle evidenceBundle, + Optional persistedCandidate) { + this.identity = Objects.requireNonNull(identity); + this.authoritySnapshot = Objects.requireNonNull(authoritySnapshot); + this.evidenceBundle = Objects.requireNonNull(evidenceBundle); + this.persistedCandidate = Objects.requireNonNull(persistedCandidate); + if (!identity.accountId().equals(authoritySnapshot.accountId())) { + throw new PendingCandidateUnavailableException(); + } + Map fields = evidenceBundle.fields(); + requireCanonicalSubtree( + fields.get("operation"), + Map.of( + "operationId", identity.operationId().toString(), + "requestId", identity.requestId().toString(), + "requestDigest", identity.requestDigest(), + "callerWorkload", identity.callerWorkload(), + "callerContextId", identity.callerContextId().toString(), + "accountId", identity.accountId().toString())); + requireCanonicalSubtree( + fields.get("tokenIdentity"), + Map.of( + "jti", identity.tokenJti().toString(), + "tokenGeneration", "1", + "iat", identity.issuedAtEpochSecond(), + "nbf", identity.notBeforeEpochSecond(), + "exp", identity.expiresAtEpochSecond())); + requireCanonicalSubtree(fields.get("authorityTuple"), authorityTuple(authoritySnapshot)); + requireCanonicalSubtree(fields.get("membershipVersion"), Map.of()); + Object issuanceFence = fields.get("issuanceFence"); + if (!(issuanceFence instanceof String fence) + || !Long.toString(authoritySnapshot.issuanceFence()).equals(fence)) { + throw new PendingCandidateUnavailableException(); + } + requireCanonicalSubtree( + fields.get("authoritySourceVersions"), + Map.of( + "issuerSourceVersion", Long.toString(authoritySnapshot.issuerSourceVersion()), + "accountSourceVersion", Long.toString(authoritySnapshot.accountSourceVersion()), + "issuanceFenceSourceVersion", + Long.toString(authoritySnapshot.issuanceFenceSourceVersion()))); + } + + public AccountGameplayDelegationPendingIdentity identity() { + return identity; + } + + public AccountAuthoritySnapshot authoritySnapshot() { + return authoritySnapshot; + } + + public AccountAuthEvidenceBundle evidenceBundle() { + return evidenceBundle; + } + + /** Exact persisted PENDING candidate, when a prior signing attempt bound it successfully. */ + public Optional persistedCandidate() { + return persistedCandidate; + } + + @Override + public String toString() { + return "PendingSigningIdentity[redacted]"; + } + } + + /** + * Repository-issued, non-authorizing snapshot of the exact current durable COMMITTED evidence. + * The type contains no candidate/JWT bytes, commit-proof bytes, registry bytes, or ciphertext. + */ + public static final class CommittedCandidateVerificationData { + private final AccountGameplayDelegationPendingIdentity identity; + private final AccountAuthoritySnapshot authoritySnapshot; + private final EvidenceBundleReference evidenceBundleReference; + private final String tokenSha256; + private final String signerKid; + private final String signerGeneration; + private final String canonicalRegistryRecordSha256; + private final String commitProofSha256; + private final AuthenticatedSignerCorrespondence signerCorrespondence; + private final String envelopeKeyId; + private final String envelopeSha256; + private final int envelopeBytesLength; + private final long responseRecoveryExpiryEpochMillis; + private final long registryAbsoluteExpiryMillis; + private final long registrationLocalAofCount; + private final long registrationReplicaAofCount; + private final AccountGameplayDelegationRedisClient.PendingRegistrationOutcome + registrationOutcome; + + private CommittedCandidateVerificationData( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + EvidenceBundleReference evidenceBundleReference, + String tokenSha256, + String signerKid, + String signerGeneration, + String canonicalRegistryRecordSha256, + String commitProofSha256, + AuthenticatedSignerCorrespondence signerCorrespondence, + String envelopeKeyId, + String envelopeSha256, + int envelopeBytesLength, + long responseRecoveryExpiryEpochMillis, + long registryAbsoluteExpiryMillis, + long registrationLocalAofCount, + long registrationReplicaAofCount, + AccountGameplayDelegationRedisClient.PendingRegistrationOutcome registrationOutcome) { + this.identity = Objects.requireNonNull(identity); + this.authoritySnapshot = Objects.requireNonNull(authoritySnapshot); + this.evidenceBundleReference = Objects.requireNonNull(evidenceBundleReference); + this.tokenSha256 = requireSha256(tokenSha256); + this.signerKid = Objects.requireNonNull(signerKid); + this.signerGeneration = Objects.requireNonNull(signerGeneration); + this.canonicalRegistryRecordSha256 = requireSha256(canonicalRegistryRecordSha256); + this.commitProofSha256 = requireSha256(commitProofSha256); + this.signerCorrespondence = Objects.requireNonNull(signerCorrespondence); + this.envelopeKeyId = Objects.requireNonNull(envelopeKeyId); + this.envelopeSha256 = requireSha256(envelopeSha256); + this.envelopeBytesLength = envelopeBytesLength; + this.responseRecoveryExpiryEpochMillis = responseRecoveryExpiryEpochMillis; + this.registryAbsoluteExpiryMillis = registryAbsoluteExpiryMillis; + this.registrationLocalAofCount = registrationLocalAofCount; + this.registrationReplicaAofCount = registrationReplicaAofCount; + this.registrationOutcome = Objects.requireNonNull(registrationOutcome); + if (!identity.accountId().equals(authoritySnapshot.accountId()) + || signerKid.isBlank() + || signerKid.length() > 64 + || !signerKid.matches("[A-Za-z0-9_-]+") + || envelopeKeyId.isBlank() + || envelopeKeyId.length() > 32 + || !envelopeKeyId.matches("[A-Za-z0-9_-]+") + || envelopeBytesLength < 1 + || envelopeBytesLength > 65_610 + || responseRecoveryExpiryEpochMillis <= 0L + || registryAbsoluteExpiryMillis <= 0L + || registrationLocalAofCount < 1L + || registrationReplicaAofCount < 1L) { + throw new StorageUnavailableException(); + } + requirePositiveDecimal(signerGeneration, "signer generation"); + } + + private static String requireSha256(String value) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new StorageUnavailableException(); + } + return value; + } + + public AccountGameplayDelegationPendingIdentity identity() { + return identity; + } + + public AccountAuthoritySnapshot authoritySnapshot() { + return authoritySnapshot; + } + + public EvidenceBundleReference evidenceBundleReference() { + return evidenceBundleReference; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String signerKid() { + return signerKid; + } + + public String signerGeneration() { + return signerGeneration; + } + + public String canonicalRegistryRecordSha256() { + return canonicalRegistryRecordSha256; + } + + public String commitProofSha256() { + return commitProofSha256; + } + + public AuthenticatedSignerCorrespondence signerCorrespondence() { + return signerCorrespondence; + } + + public String envelopeKeyId() { + return envelopeKeyId; + } + + public String envelopeSha256() { + return envelopeSha256; + } + + public int envelopeBytesLength() { + return envelopeBytesLength; + } + + public long responseRecoveryExpiryEpochMillis() { + return responseRecoveryExpiryEpochMillis; + } + + /** Exact absolute deadline persisted in the immutable COMMITTED proof. */ + public long registryAbsoluteExpiryMillis() { + return registryAbsoluteExpiryMillis; + } + + /** Historical WAITAOF counts validated from the immutable COMMITTED proof. */ + public long registrationLocalAofCount() { + return registrationLocalAofCount; + } + + public long registrationReplicaAofCount() { + return registrationReplicaAofCount; + } + + public AccountGameplayDelegationRedisClient.PendingRegistrationOutcome registrationOutcome() { + return registrationOutcome; + } + + @Override + public String toString() { + return "CommittedCandidateVerificationData[redacted]"; + } + } + + private record EnvelopeHeader(String keyId) {} + + private record EnvelopeIdentity(String sha256, int length, long expiryMillis, String keyId) {} + + public static class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException() { + super("Account gameplay delegation issuance storage is unavailable or ambiguous"); + } + } + + public static final class StaleAuthorityException extends IllegalStateException { + public StaleAuthorityException() { + super("Account gameplay delegation authority changed"); + } + } + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException() { + super("Account gameplay delegation request identity conflicts"); + } + } + + public static final class PendingCandidateUnavailableException extends IllegalStateException { + public PendingCandidateUnavailableException() { + super("Account gameplay delegation pending candidate is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java new file mode 100644 index 0000000000..25e885b407 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java @@ -0,0 +1,1383 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner.ActiveCommittedIssuanceObservation; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Stores and recovers one immutable encrypted compact-token candidate for an Account operation. + * + *

Sealing is candidate custody only. Recovery compares caller values to immutable owner rows but + * does not authenticate them; the actual Game Session boundary must provide its authenticated + * workload identity and enforce that its original socket context remains open and current. Recovery + * requires current Account owner evidence and the exact result of the separate registry activation + * owner before it returns the JWT in a redacted typed result. + */ +public class AccountGameplayDelegationResponseEnvelopeRepository { + private static final String OPERATION_TABLE = "account_gameplay_delegation_issuance_operations"; + private static final String BUNDLE_TABLE = "account_gameplay_delegation_auth_evidence_bundles"; + private static final String RESPONSE_TABLE = "account_gameplay_delegation_response_envelopes"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern V4_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final byte[] EMPTY_OBJECT = "{}".getBytes(StandardCharsets.US_ASCII); + private static final JsonMapper JSON = + JsonMapper.builder().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).build(); + + private final DSLContext dsl; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountAuthEvidenceBundleRepository evidenceBundles; + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final AccountResponseEnvelopeCryptography responseCryptography; + private final Clock clock; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep fail-fast collaborator preconditions in the delegated constructor; this non-final Spring repository acquires no external resources and does not escape partially initialized.") + public AccountGameplayDelegationResponseEnvelopeRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles, + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountResponseEnvelopeCryptography responseCryptography) { + this( + dsl, + sourceEvidence, + evidenceBundles, + issuanceRepository, + responseCryptography, + Clock.systemUTC()); + } + + /** Compatibility constructor for the existing candidate-sealing component fixtures. */ + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep fail-fast collaborator preconditions in the delegated constructor; constructing the lightweight owner adds no external resource acquisition or partially initialized escape.") + public AccountGameplayDelegationResponseEnvelopeRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles, + AccountResponseEnvelopeCryptography responseCryptography) { + this( + dsl, + sourceEvidence, + evidenceBundles, + new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence, evidenceBundles), + responseCryptography, + Clock.systemUTC()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator and clock null checks fail-fast; this non-final Spring repository acquires no external resources and does not escape partially initialized.") + AccountGameplayDelegationResponseEnvelopeRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles, + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountResponseEnvelopeCryptography responseCryptography, + Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.sourceEvidence = + Objects.requireNonNull(sourceEvidence, "Account authority source evidence is required"); + this.evidenceBundles = + Objects.requireNonNull(evidenceBundles, "Account auth-evidence bundle owner is required"); + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account durable issuance owner is required"); + this.responseCryptography = + Objects.requireNonNull( + responseCryptography, "Account response-envelope crypto is required"); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** + * Encrypts and durably read-backs an exact candidate once, or returns its existing sealed + * metadata for a matching retry. Caller values are comparison inputs from the upstream + * authenticated boundary; this repository does not authenticate them. + */ + @Transactional(propagation = Propagation.MANDATORY) + public SealedCandidateObservation sealPendingCandidate( + UUID requestId, CallerIdentity caller, String exactCompactJwt) { + requireWritableAccountTransaction(); + requireV4(requestId, "request ID"); + Objects.requireNonNull(caller, "Caller identity comparison is required"); + validateCompactJwt(exactCompactJwt); + + Record preliminary = selectOperation(requestId, false); + if (preliminary == null) throw new OperationUnavailableException(); + UUID accountId = uuid(preliminary, "account_uuid"); + UUID operationId = uuid(preliminary, "operation_id"); + requireV4(operationId, "operation ID"); + PendingIdentity identity = identity(preliminary); + if (!requestId.equals(identity.requestId())) throw new OperationUnavailableException(); + requireCallerMatch(identity, caller); + CandidateIdentity candidate = candidate(preliminary, identity); + String exactTokenHash = sha256(exactCompactJwt.getBytes(StandardCharsets.US_ASCII)); + if (!MessageDigest.isEqual( + exactTokenHash.getBytes(StandardCharsets.US_ASCII), + candidate.tokenHash().getBytes(StandardCharsets.US_ASCII))) { + throw new IdempotencyConflictException(); + } + long immutableExpiryMillis = expiryEpochMillis(identity.expiresAtEpochSecond()); + if (clock.millis() >= immutableExpiryMillis) throw new ResponseRecoveryExpiredException(); + + final IssuerAccountSourceSnapshot current; + try { + // Locks Account and authority before the operation row and verifies exact retained source + // checkpoints, including the applicable Account security cutoff. + current = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + } catch (RuntimeException ex) { + throw new AuthorityChangedException(); + } + Record operation = selectOperation(requestId, true); + if (operation == null + || !operationId.equals(uuid(operation, "operation_id")) + || !accountId.equals(uuid(operation, "account_uuid"))) { + throw new OperationUnavailableException(); + } + identity = identity(operation); + requireCallerMatch(identity, caller); + candidate = candidate(operation, identity); + if (!exactTokenHash.equals(candidate.tokenHash())) throw new IdempotencyConflictException(); + requireCurrentAuthority(operation, current, accountId); + + AccountAuthEvidenceBundle evaluatedBundle; + AccountAuthEvidenceBundle bundle; + try { + // This owner API performs the current locked source/history evaluation. A previously stored + // value alone is not enough for this new seal attempt. + evaluatedBundle = evidenceBundles.captureAndPersist(requestId); + bundle = evidenceBundles.readStoredNonAuthorizingValue(operationId); + } catch (RuntimeException ex) { + // A missing or malformed owner bundle is not replaced by operation-row fields or caller data. + throw new OwnerEvidenceUnavailableException(); + } + if (!MessageDigest.isEqual(evaluatedBundle.canonicalBytes(), bundle.canonicalBytes())) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactBundle(bundle, identity, operation, current, accountId); + requireCandidateMatchesBoundRows(candidate.record(), identity, operation, current); + + Record existing = selectEnvelope(operationId); + if (existing != null) { + return exactReadback(existing, identity, candidate, bundle, immutableExpiryMillis); + } + + Binding binding = binding(identity, operation, bundle); + Instant recoveryExpiry; + try { + recoveryExpiry = Instant.ofEpochMilli(immutableExpiryMillis); + } catch (RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + byte[] plaintext = exactCompactJwt.getBytes(StandardCharsets.US_ASCII); + final EncryptedResponseEnvelope sealed; + try { + sealed = responseCryptography.encrypt(binding, plaintext, recoveryExpiry); + } finally { + Arrays.fill(plaintext, (byte) 0); + } + byte[] envelopeBytes = sealed.bytes(); + try { + String envelopeHash = sha256(envelopeBytes); + String bundleHash = bundle.canonicalSha256(); + int inserted = + dsl.execute( + "INSERT INTO " + + RESPONSE_TABLE + + " (operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, envelope_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + identity.operationId(), + identity.requestId(), + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + bundleHash, + identity.issuanceFence(), + immutableExpiryMillis, + envelopeHash, + envelopeBytes); + if (inserted != 1) throw new StorageUnavailableException(); + Record readback = selectEnvelope(operationId); + if (readback == null) throw new StorageUnavailableException(); + SealedCandidateObservation observation = + exactReadback(readback, identity, candidate, bundle, immutableExpiryMillis); + byte[] readbackBytes = bytes(readback, "envelope_bytes"); + try { + if (!MessageDigest.isEqual(envelopeBytes, readbackBytes)) { + throw new StorageUnavailableException(); + } + } finally { + Arrays.fill(readbackBytes, (byte) 0); + } + return observation; + } finally { + Arrays.fill(envelopeBytes, (byte) 0); + } + } + + /** + * Opens one exact, still-current PENDING candidate for Account's internal signer verification + * retry. This is not caller recovery: no gameplay caller or public response boundary receives a + * credential, and the returned bytes are consumed only by the signer before commit. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PendingCandidateCredential openPendingCandidate(UUID requestId, CallerIdentity caller) { + requireWritableAccountTransaction(); + requireV4(requestId, "request ID"); + Objects.requireNonNull(caller, "Caller identity comparison is required"); + + Record preliminary = selectOperation(requestId, false); + if (preliminary == null) throw new OperationUnavailableException(); + PendingIdentity preliminaryIdentity = identity(preliminary); + requireCallerMatch(preliminaryIdentity, caller); + CandidateIdentity preliminaryCandidate = candidate(preliminary, preliminaryIdentity); + long immutableExpiryMillis = expiryEpochMillis(preliminaryIdentity.expiresAtEpochSecond()); + requirePendingCandidateUnexpired(immutableExpiryMillis); + + final IssuerAccountSourceSnapshot current; + try { + current = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, preliminaryIdentity.accountId()); + } catch (RuntimeException unavailable) { + throw new AuthorityChangedException(); + } + Record operation = selectOperation(requestId, true); + if (operation == null) throw new OperationUnavailableException(); + PendingIdentity identity = identity(operation); + requireCallerMatch(identity, caller); + CandidateIdentity persistedCandidate = candidate(operation, identity); + if (!preliminaryIdentity.equals(identity) + || !preliminaryCandidate.tokenHash().equals(persistedCandidate.tokenHash()) + || !preliminaryCandidate.kid().equals(persistedCandidate.kid()) + || !preliminaryCandidate.signerGeneration().equals(persistedCandidate.signerGeneration()) + || !Arrays.equals( + preliminaryCandidate + .record() + .toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES), + persistedCandidate + .record() + .toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES))) { + throw new IdempotencyConflictException(); + } + requireCurrentAuthority(operation, current, identity.accountId()); + requireCandidateMatchesBoundRows(persistedCandidate.record(), identity, operation, current); + + final AccountAuthEvidenceBundle bundle; + try { + bundle = evidenceBundles.readStoredNonAuthorizingValue(identity.operationId()); + } catch (RuntimeException unavailable) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactBundle(bundle, identity, operation, current, identity.accountId()); + if (!bundle + .canonicalSha256() + .equals(persistedCandidate.record().evidenceBundleReference().canonicalSha256())) { + throw new OwnerEvidenceUnavailableException(); + } + + Record envelope = selectEnvelopeForRecovery(identity.operationId()); + if (envelope == null) throw new StorageUnavailableException(); + byte[] envelopeBytes = bytes(envelope, "envelope_bytes"); + byte[] plaintext = null; + try { + SealedCandidateObservation sealed = + exactReadback(envelope, identity, persistedCandidate, bundle, immutableExpiryMillis); + requirePendingCandidateUnexpired(immutableExpiryMillis); + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(envelopeBytes), + binding(identity, operation, bundle), + Instant.ofEpochMilli(immutableExpiryMillis)); + validateRecoveredCompactJwt(plaintext, persistedCandidate.tokenHash()); + return new PendingCandidateCredential(plaintext, sealed); + } catch (AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired) { + throw new ResponseRecoveryExpiredException(); + } catch (RuntimeException failure) { + if (failure instanceof ResponseRecoveryExpiredException expired) throw expired; + throw new StorageUnavailableException(); + } finally { + if (plaintext != null) Arrays.fill(plaintext, (byte) 0); + Arrays.fill(envelopeBytes, (byte) 0); + } + } + + private void requirePendingCandidateUnexpired(long immutableExpiryMillis) { + long nowMillis = clock.millis(); + if (nowMillis <= 0L || nowMillis >= immutableExpiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + } + + /** + * Checks only immutable request/caller identity and the stored response horizon before registry + * activation. This deliberately does not authenticate the supplied identity or inspect/decrypt + * the response envelope; the actual Game Session boundary must supply its authenticated mTLS + * workload and ensure the original caller context is still open and current. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RecoveryPreflight preflightCommittedRecovery( + UUID requestId, UUID expectedAccountId, CallerIdentity caller) { + requireWritableAccountTransaction(); + requireRecoveryRequest(requestId, expectedAccountId, caller); + Record operation = selectOperation(requestId, false); + if (operation == null) throw new OperationUnavailableException(); + CommittedRecoveryIdentity identity = committedRecoveryIdentity(operation); + requireRecoveryCaller(identity, requestId, expectedAccountId, caller); + long expiryMillis = expiryEpochMillis(identity.expiresAtEpochSecond()); + long nowMillis = clock.millis(); + if (nowMillis <= 0L || nowMillis >= expiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + return new RecoveryPreflight( + identity.operationId(), + identity.requestId(), + identity.accountId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.requestDigest(), + identity.tokenJti(), + identity.expiresAtEpochSecond(), + expiryMillis); + } + + /** + * Reads current durable COMMITTED evidence and decrypts its exact original compact JWT only after + * the caller has completed the COMMITTED-to-ACTIVE registry postcondition. The SQL owner + * transaction contains no network operation; plaintext is returned only in the redacted typed + * credential result and the local byte buffer is wiped before exit. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RecoveredCredential recoverCommittedResponse( + UUID requestId, + UUID expectedAccountId, + CallerIdentity caller, + ActiveCommittedIssuanceObservation active) { + requireWritableAccountTransaction(); + requireRecoveryRequest(requestId, expectedAccountId, caller); + Objects.requireNonNull(active, "Completed Account activation evidence is required"); + + Record preliminary = selectOperation(requestId, false); + if (preliminary == null) throw new OperationUnavailableException(); + CommittedRecoveryIdentity preliminaryIdentity = committedRecoveryIdentity(preliminary); + requireRecoveryCaller(preliminaryIdentity, requestId, expectedAccountId, caller); + long immutableExpiryMillis = expiryEpochMillis(preliminaryIdentity.expiresAtEpochSecond()); + if (clock.millis() <= 0L || clock.millis() >= immutableExpiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + + final CommittedCandidateVerificationData committed; + try { + committed = issuanceRepository.readCurrentCommittedCandidate(requestId); + } catch (RuntimeException failure) { + if (clock.millis() >= immutableExpiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + throw new OwnerEvidenceUnavailableException(); + } + + Record operation = selectOperation(requestId, true); + if (operation == null) throw new OperationUnavailableException(); + CommittedRecoveryIdentity identity = committedRecoveryIdentity(operation); + requireRecoveryCaller(identity, requestId, expectedAccountId, caller); + if (!preliminaryIdentity.equals(identity) + || !committedMatches(committed, identity) + || !activeMatches(active, committed)) { + throw new OwnerEvidenceUnavailableException(); + } + if (clock.millis() <= 0L || clock.millis() >= immutableExpiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + + final IssuerAccountSourceSnapshot current; + try { + current = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, identity.accountId()); + } catch (RuntimeException failure) { + throw new AuthorityChangedException(); + } + requireCurrentAuthority(operation, current, identity.accountId()); + CandidateIdentity candidate = candidate(operation, identity.pendingIdentity()); + requireCandidateMatchesBoundRows( + candidate.record(), identity.pendingIdentity(), operation, current); + + final AccountAuthEvidenceBundle bundle; + try { + bundle = evidenceBundles.readStoredNonAuthorizingValue(identity.operationId()); + } catch (RuntimeException failure) { + throw new OwnerEvidenceUnavailableException(); + } + if (!committed.evidenceBundleReference().canonicalSha256().equals(bundle.canonicalSha256()) + || !candidate.record().evidenceBundleReference().equals(committed.evidenceBundleReference()) + || !committed.tokenSha256().equals(candidate.tokenHash()) + || !committed.signerKid().equals(candidate.kid()) + || !committed.signerGeneration().equals(candidate.signerGeneration()) + || !committed + .canonicalRegistryRecordSha256() + .equals(sha256(bytes(operation, "pending_registry_candidate_bytes"))) + || !committed.authoritySnapshot().equals(authoritySnapshot(current))) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactBundle( + bundle, identity.pendingIdentity(), operation, current, identity.accountId()); + + Record envelope = selectEnvelopeForRecovery(identity.operationId()); + if (envelope == null) throw new StorageUnavailableException(); + byte[] envelopeBytes = bytes(envelope, "envelope_bytes"); + String envelopeHash = text(envelope, "envelope_sha256"); + if (!exactCommittedEnvelope( + envelope, + envelopeBytes, + envelopeHash, + identity, + candidate, + committed, + bundle, + immutableExpiryMillis)) { + throw new StorageUnavailableException(); + } + + byte[] plaintext = null; + try { + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(envelopeBytes), + binding(identity.pendingIdentity(), operation, bundle), + Instant.ofEpochMilli(immutableExpiryMillis)); + validateRecoveredCompactJwt(plaintext, committed.tokenSha256()); + return new RecoveredCredential( + plaintext, + identity.accountId(), + identity.tokenJti(), + committed.tokenSha256(), + GameSessionAccountDelegationProfile.PROFILE, + identity.expiresAtEpochSecond(), + bundle); + } catch (AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired) { + throw new ResponseRecoveryExpiredException(); + } catch (RuntimeException failure) { + if (failure instanceof ResponseRecoveryExpiredException expired) throw expired; + throw new StorageUnavailableException(); + } finally { + if (plaintext != null) Arrays.fill(plaintext, (byte) 0); + Arrays.fill(envelopeBytes, (byte) 0); + } + } + + private Record selectEnvelopeForRecovery(UUID operationId) { + return dsl.fetchOne( + "SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, envelope_bytes " + + "FROM " + + RESPONSE_TABLE + + " WHERE operation_id = ? FOR SHARE", + operationId); + } + + private boolean exactCommittedEnvelope( + Record envelope, + byte[] envelopeBytes, + String envelopeHash, + CommittedRecoveryIdentity identity, + CandidateIdentity candidate, + CommittedCandidateVerificationData committed, + AccountAuthEvidenceBundle bundle, + long immutableExpiryMillis) { + return identity.operationId().equals(uuid(envelope, "operation_id")) + && identity.requestId().equals(uuid(envelope, "request_id")) + && candidate.tokenHash().equals(text(envelope, "token_hash")) + && candidate.kid().equals(text(envelope, "signer_kid")) + && candidate.signerGeneration().equals(text(envelope, "signer_generation")) + && bundle.canonicalSha256().equals(text(envelope, "authority_evidence_bundle_sha256")) + && identity.issuanceFence() == positive(envelope, "issuance_fence") + && immutableExpiryMillis == positive(envelope, "response_recovery_expiry_epoch_ms") + && immutableExpiryMillis == committed.responseRecoveryExpiryEpochMillis() + && committed.envelopeSha256().equals(envelopeHash) + && committed.envelopeBytesLength() == envelopeBytes.length + && envelopeBytes.length > 0 + && envelopeBytes.length <= 65_610 + && SHA256.matcher(envelopeHash).matches() + && MessageDigest.isEqual( + sha256(envelopeBytes).getBytes(StandardCharsets.US_ASCII), + envelopeHash.getBytes(StandardCharsets.US_ASCII)); + } + + private static boolean committedMatches( + CommittedCandidateVerificationData committed, CommittedRecoveryIdentity identity) { + var committedIdentity = committed.identity(); + return committedIdentity.operationId().equals(identity.operationId()) + && committedIdentity.requestId().equals(identity.requestId()) + && committedIdentity.accountId().equals(identity.accountId()) + && committedIdentity.callerWorkload().equals(identity.callerWorkload()) + && committedIdentity.callerContextId().equals(identity.callerContextId()) + && committedIdentity.requestDigest().equals(identity.requestDigest()) + && committedIdentity.tokenJti().equals(identity.tokenJti()) + && committedIdentity.issuedAtEpochSecond() == identity.issuedAtEpochSecond() + && committedIdentity.notBeforeEpochSecond() == identity.notBeforeEpochSecond() + && committedIdentity.expiresAtEpochSecond() == identity.expiresAtEpochSecond() + && committed.tokenSha256().equals(identity.tokenHash()) + && committed.authoritySnapshot().accountId().equals(identity.accountId()) + && committed.authoritySnapshot().issuanceFence() == identity.issuanceFence() + && committed.responseRecoveryExpiryEpochMillis() + == expiryEpochMillis(identity.expiresAtEpochSecond()); + } + + private static boolean activeMatches( + ActiveCommittedIssuanceObservation active, CommittedCandidateVerificationData committed) { + return active.operationId().equals(committed.identity().operationId()) + && active.requestId().equals(committed.identity().requestId()) + && active.accountId().equals(committed.identity().accountId()) + && active.tokenSha256().equals(committed.tokenSha256()) + && active.commitProofSha256().equals(committed.commitProofSha256()) + && active.registryVersion() == 2L + && active.absoluteExpiryMillis() == committed.registryAbsoluteExpiryMillis() + && active.observedAtEpochMillis() > 0L + && active.observedAtEpochMillis() < committed.responseRecoveryExpiryEpochMillis() + && active.activeRecordSha256() != null + && SHA256.matcher(active.activeRecordSha256()).matches(); + } + + private static void requireV4ForRecovery(UUID value, String field) { + requireV4(value, field); + if (value.variant() != 2) throw new OperationUnavailableException(); + } + + private CommittedRecoveryIdentity committedRecoveryIdentity(Record operation) { + if (!"COMMITTED".equals(text(operation, "status")) + || number(operation, "request_digest_version") != 2L + || number(operation, "token_generation") != 1L) { + throw new OperationUnavailableException(); + } + String callerWorkload = text(operation, "caller_workload"); + if (!GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(callerWorkload) + .matches()) { + throw new OperationUnavailableException(); + } + String requestDigest = text(operation, "request_digest"); + if (!SHA256.matcher(requestDigest).matches()) throw new OperationUnavailableException(); + UUID operationId = uuid(operation, "operation_id"); + UUID requestId = uuid(operation, "request_id"); + UUID accountId = uuid(operation, "account_uuid"); + UUID callerContextId = uuid(operation, "caller_context_id"); + UUID tokenJti = uuid(operation, "token_jti"); + requireV4ForRecovery(operationId, "operation ID"); + requireV4ForRecovery(requestId, "request ID"); + requireV4ForRecovery(accountId, "Account ID"); + requireV4ForRecovery(callerContextId, "caller context ID"); + requireV4ForRecovery(tokenJti, "token ID"); + String tokenHash = text(operation, "token_hash"); + if (!SHA256.matcher(tokenHash).matches()) throw new CandidateUnavailableException(); + return new CommittedRecoveryIdentity( + operationId, + requestId, + accountId, + callerWorkload, + callerContextId, + credentialRequestBinding(operation), + requestDigest, + tokenJti, + positive(operation, "issued_at_epoch_second"), + positive(operation, "not_before_epoch_second"), + positive(operation, "expires_at_epoch_second"), + tokenHash, + positive(operation, "issuance_fence")); + } + + private static void requireRecoveryCaller( + CommittedRecoveryIdentity identity, + UUID requestId, + UUID expectedAccountId, + CallerIdentity caller) { + if (!identity.requestId().equals(requestId)) throw new OperationUnavailableException(); + if (!identity.accountId().equals(expectedAccountId) + || !identity.callerWorkload().equals(caller.workload()) + || !identity.callerContextId().equals(caller.contextId())) { + throw new IdempotencyConflictException(); + } + } + + private static void requireRecoveryRequest( + UUID requestId, UUID expectedAccountId, CallerIdentity caller) { + requireV4ForRecovery(requestId, "request ID"); + requireV4ForRecovery(expectedAccountId, "Account ID"); + Objects.requireNonNull(caller, "Authenticated Game Session identity comparison is required"); + } + + private static void validateRecoveredCompactJwt(byte[] bytes, String expectedSha256) { + if (bytes == null + || bytes.length == 0 + || bytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + throw new StorageUnavailableException(); + } + for (byte value : bytes) { + int octet = Byte.toUnsignedInt(value); + if (octet < 0x21 || octet > 0x7e) throw new StorageUnavailableException(); + } + if (!MessageDigest.isEqual( + sha256(bytes).getBytes(StandardCharsets.US_ASCII), + expectedSha256.getBytes(StandardCharsets.US_ASCII))) { + throw new StorageUnavailableException(); + } + } + + private Record selectOperation(UUID requestId, boolean lock) { + return dsl.fetchOne( + "SELECT * FROM " + OPERATION_TABLE + " WHERE request_id = ?" + (lock ? " FOR UPDATE" : ""), + requestId); + } + + private Record selectEnvelope(UUID operationId) { + return dsl.fetchOne( + "SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, envelope_bytes " + + "FROM " + + RESPONSE_TABLE + + " WHERE operation_id = ?", + operationId); + } + + private SealedCandidateObservation exactReadback( + Record row, + PendingIdentity identity, + CandidateIdentity candidate, + AccountAuthEvidenceBundle bundle, + long expiryMillis) { + byte[] envelope = bytes(row, "envelope_bytes"); + String storedEnvelopeHash = text(row, "envelope_sha256"); + try { + if (!identity.operationId().equals(uuid(row, "operation_id")) + || !identity.requestId().equals(uuid(row, "request_id")) + || !candidate.tokenHash().equals(text(row, "token_hash")) + || !candidate.kid().equals(text(row, "signer_kid")) + || !candidate.signerGeneration().equals(text(row, "signer_generation")) + || !bundle.canonicalSha256().equals(text(row, "authority_evidence_bundle_sha256")) + || identity.issuanceFence() != positive(row, "issuance_fence") + || expiryMillis != positive(row, "response_recovery_expiry_epoch_ms") + || envelope.length == 0 + || envelope.length > 65_610 + || !SHA256.matcher(storedEnvelopeHash).matches() + || !MessageDigest.isEqual( + sha256(envelope).getBytes(StandardCharsets.US_ASCII), + storedEnvelopeHash.getBytes(StandardCharsets.US_ASCII))) { + throw new StorageUnavailableException(); + } + return new SealedCandidateObservation( + identity.operationId(), + identity.requestId(), + bundle.canonicalSha256(), + identity.issuanceFence(), + expiryMillis, + storedEnvelopeHash, + envelope.length); + } finally { + Arrays.fill(envelope, (byte) 0); + } + } + + private static Binding binding( + PendingIdentity identity, Record operation, AccountAuthEvidenceBundle bundle) { + return new Binding( + GameSessionAccountDelegationProfile.PROFILE, + identity.requestId().toString(), + HexFormat.of().parseHex(identity.requestDigest()), + identity.callerWorkload(), + identity.operationId().toString(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + identity.issuanceFence(), + bytes(operation, "authority_tuple_canonical_bytes"), + bytes(operation, "membership_version_canonical_bytes"), + bundle.canonicalBytes()); + } + + private static PendingIdentity identity(Record operation) { + if (!"PENDING".equals(text(operation, "status")) + || number(operation, "request_digest_version") != 2L + || number(operation, "token_generation") != 1L) { + throw new OperationUnavailableException(); + } + String caller = text(operation, "caller_workload"); + if (!GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(caller) + .matches()) { + throw new OperationUnavailableException(); + } + String digest = text(operation, "request_digest"); + if (!SHA256.matcher(digest).matches()) throw new OperationUnavailableException(); + return new PendingIdentity( + uuid(operation, "operation_id"), + uuid(operation, "request_id"), + uuid(operation, "account_uuid"), + caller, + uuid(operation, "caller_context_id"), + credentialRequestBinding(operation), + digest, + uuid(operation, "token_jti"), + positive(operation, "issued_at_epoch_second"), + positive(operation, "not_before_epoch_second"), + positive(operation, "expires_at_epoch_second"), + positive(operation, "issuance_fence")); + } + + private static AccountGameplayCredentialRequestBinding credentialRequestBinding( + Record operation) { + try { + return new AccountGameplayCredentialRequestBinding( + Math.toIntExact(number(operation, "credential_request_digest_version")), + text(operation, "credential_digest_key_id"), + text(operation, "credential_request_digest")); + } catch (RuntimeException ex) { + throw new OperationUnavailableException(); + } + } + + private static CandidateIdentity candidate(Record operation, PendingIdentity identity) { + String tokenHash = text(operation, "token_hash"); + String kid = text(operation, "signer_kid"); + String signerGeneration = text(operation, "signer_generation"); + byte[] candidateBytes = bytes(operation, "pending_registry_candidate_bytes"); + if (!SHA256.matcher(tokenHash).matches() + || !kid.matches("[A-Za-z0-9_-]{1,64}") + || !signerGeneration.matches("[1-9][0-9]{0,18}") + || candidateBytes.length == 0 + || candidateBytes.length > GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES) { + throw new CandidateUnavailableException(); + } + GameSessionAccountDelegationRegistryRecord record; + try { + record = + GameSessionAccountDelegationRegistryRecord.decode( + candidateBytes, GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + } catch (RuntimeException ex) { + throw new CandidateUnavailableException(); + } + return new CandidateIdentity(tokenHash, kid, signerGeneration, record); + } + + private static void requireCallerMatch(PendingIdentity identity, CallerIdentity caller) { + if (!identity.callerWorkload().equals(caller.workload()) + || !identity.callerContextId().equals(caller.contextId())) { + throw new IdempotencyConflictException(); + } + } + + private static void requireCurrentAuthority( + Record operation, IssuerAccountSourceSnapshot snapshot, UUID accountId) { + CurrentSourceEvidence issuer = snapshot.issuer(); + CurrentSourceEvidence account = snapshot.account(); + if (issuer.scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ISSUER + || !GameSessionAccountDelegationProfile.ISSUER.equals(issuer.scope().issuerId()) + || issuer.scope().accountId() != null + || issuer.scope().tenantId() != null + || account.scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ACCOUNT + || !accountId.equals(account.scope().accountId()) + || account.scope().issuerId() != null + || account.scope().tenantId() != null + || !Objects.equals(account.issuanceFence(), snapshot.issuanceFence()) + || !accountId.equals(snapshot.issuanceFence().accountId()) + || !Objects.equals(issuer.generation(), longValue(operation, "authority_issuer_generation")) + || !Objects.equals( + issuer.sourceVersion(), longValue(operation, "authority_issuer_source_version")) + || !Objects.equals( + account.generation(), longValue(operation, "authority_account_generation")) + || !Objects.equals( + account.sourceVersion(), longValue(operation, "authority_account_source_version")) + || !Objects.equals(snapshot.issuanceFence().value(), longValue(operation, "issuance_fence")) + || !Objects.equals( + snapshot.issuanceFence().sourceVersion(), + longValue(operation, "issuance_fence_source_version"))) { + throw new AuthorityChangedException(); + } + Map currentTuple = + GameSessionAccountDelegationProfile.authorityTuple( + issuer.generation(), + account.generation(), + account + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))); + if (!Arrays.equals( + bytes(operation, "authority_tuple_canonical_bytes"), canonicalJson(currentTuple)) + || !Arrays.equals(bytes(operation, "membership_version_canonical_bytes"), EMPTY_OBJECT)) { + throw new AuthorityChangedException(); + } + } + + private void requireExactBundle( + AccountAuthEvidenceBundle bundle, + PendingIdentity identity, + Record operation, + IssuerAccountSourceSnapshot current, + UUID accountId) { + Map root = bundle.fields(); + Map scope = object(root, "scope"); + Map operationFields = object(root, "operation"); + Map token = object(root, "tokenIdentity"); + Map authorityTuple = object(root, "authorityTuple"); + Map sourceVersions = object(root, "authoritySourceVersions"); + if (!"account".equals(scope.get("kind")) + || !accountId.toString().equals(scope.get("accountId")) + || !List.of().equals(scope.get("tenantIds")) + || !identity.operationId().toString().equals(operationFields.get("operationId")) + || !identity.requestId().toString().equals(operationFields.get("requestId")) + || !identity.requestDigest().equals(operationFields.get("requestDigest")) + || !identity.callerWorkload().equals(operationFields.get("callerWorkload")) + || !identity.callerContextId().toString().equals(operationFields.get("callerContextId")) + || !accountId.toString().equals(operationFields.get("accountId")) + || !identity.tokenJti().toString().equals(token.get("jti")) + || !Long.valueOf(1L).equals(numberFromString(token.get("tokenGeneration"))) + || numberValue(token.get("iat")) != identity.issuedAtEpochSecond() + || numberValue(token.get("nbf")) != identity.notBeforeEpochSecond() + || numberValue(token.get("exp")) != identity.expiresAtEpochSecond() + || !Long.toString(identity.issuanceFence()).equals(root.get("issuanceFence")) + || !Map.of().equals(root.get("membershipVersion")) + || !Long.valueOf(current.issuer().generation()) + .equals(numberFromString(authorityTuple.get("issuerAuthGeneration"))) + || !Long.valueOf(current.account().generation()) + .equals(numberFromString(authorityTuple.get("accountAuthorityGeneration"))) + || !Arrays.equals( + canonicalJson(authorityTuple), bytes(operation, "authority_tuple_canonical_bytes")) + || !Arrays.equals( + canonicalJson(root.get("membershipVersion")), + bytes(operation, "membership_version_canonical_bytes")) + || !Long.toString(current.issuer().sourceVersion()) + .equals(sourceVersions.get("issuerSourceVersion")) + || !Long.toString(current.account().sourceVersion()) + .equals(sourceVersions.get("accountSourceVersion")) + || !Long.toString(current.issuanceFence().sourceVersion()) + .equals(sourceVersions.get("issuanceFenceSourceVersion")) + || positive(operation, "authority_issuer_source_version") + != current.issuer().sourceVersion() + || positive(operation, "authority_account_source_version") + != current.account().sourceVersion() + || positive(operation, "issuance_fence_source_version") + != current.issuanceFence().sourceVersion()) { + throw new OwnerEvidenceUnavailableException(); + } + Record accountRow = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id " + + "FROM accounts WHERE account_uuid = ? FOR SHARE", + accountId); + if (accountRow == null + || !accountId.equals(uuid(accountRow, "account_uuid")) + || !Long.toString(positive(accountRow, "id")) + .equals(object(root, "accountIdentitySource").get("sourceRowId")) + || !Long.toString(positive(accountRow, "account_uuid_source_numeric_id")) + .equals(object(root, "accountIdentitySource").get("sourceNumericId"))) { + throw new OwnerEvidenceUnavailableException(); + } + AccountIdentityProvenance provenance; + try { + provenance = + AccountIdentityProvenance.fromStorageValue(text(accountRow, "account_uuid_provenance")); + } catch (RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + if (!AccountIdentityProvenance.isAccepted(provenance) + || !provenance.name().equals(object(root, "accountIdentitySource").get("provenance"))) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static void requireCandidateMatchesBoundRows( + GameSessionAccountDelegationRegistryRecord record, + PendingIdentity identity, + Record operation, + IssuerAccountSourceSnapshot current) { + AccountAuthoritySnapshot currentAuthority = authoritySnapshot(current); + Map fields = record.fields(); + if (!record.tokenHash().equals(text(operation, "token_hash")) + || !record.kid().equals(text(operation, "signer_kid")) + || !record.signerGeneration().equals(text(operation, "signer_generation")) + || !"pending".equals(record.state()) + || !identity.operationId().toString().equals(record.operationId()) + || !identity.requestId().toString().equals(record.requestId()) + || !identity.requestDigest().equals(record.requestDigest()) + || !identity.accountId().toString().equals(record.accountId()) + || !identity.tokenJti().toString().equals(record.jti()) + || identity.issuedAtEpochSecond() != record.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != record.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != record.expiresAtEpochSecond() + || identity.issuanceFence() != record.issuanceFence() + || !Arrays.equals( + canonicalJson(fields.get("authorityTuple")), + bytes(operation, "authority_tuple_canonical_bytes")) + || !Arrays.equals( + canonicalJson(fields.get("membershipVersion")), + bytes(operation, "membership_version_canonical_bytes")) + || !Arrays.equals( + canonicalJson(fields.get("authoritySourceVersions")), + canonicalJson(currentAuthority.sourceVersions()))) { + throw new CandidateUnavailableException(); + } + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot sources) { + Optional cutoff = + sources + .account() + .accountSecurityCutoff() + .map( + value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + return new AccountAuthoritySnapshot( + sources.account().scope().accountId(), + sources.issuer().generation(), + sources.issuer().sourceVersion(), + sources.account().generation(), + sources.account().sourceVersion(), + sources.issuanceFence().value(), + sources.issuanceFence().sourceVersion(), + cutoff); + } + + private static long expiryEpochMillis(long expEpochSecond) { + try { + long millis = Math.multiplyExact(expEpochSecond, 1_000L); + if (millis <= 0L) throw new ArithmeticException(); + return millis; + } catch (ArithmeticException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static void validateCompactJwt(String value) { + if (value == null + || value.isEmpty() + || value.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + throw new CandidateUnavailableException(); + } + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) throw new CandidateUnavailableException(); + } + } + + private static byte[] canonicalJson(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (canonical.length == 0 || canonical.length > 8 * 1024) { + throw new OwnerEvidenceUnavailableException(); + } + return canonical; + } catch (IOException | RuntimeException ex) { + if (ex instanceof OwnerEvidenceUnavailableException unavailable) throw unavailable; + throw new OwnerEvidenceUnavailableException(); + } + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException ex) { + throw new StorageUnavailableException(); + } + } + + private static Map object(Map parent, String field) { + Object value = parent.get(field); + if (!(value instanceof Map map)) throw new OwnerEvidenceUnavailableException(); + @SuppressWarnings("unchecked") + Map typed = (Map) map; + return typed; + } + + private static long numberValue(Object value) { + if (!(value instanceof Number number)) throw new OwnerEvidenceUnavailableException(); + try { + return Long.parseLong(number.toString()); + } catch (NumberFormatException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static Long numberFromString(Object value) { + if (!(value instanceof String text) || !text.matches("[1-9][0-9]{0,18}")) { + throw new OwnerEvidenceUnavailableException(); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw new OperationUnavailableException(); + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw new OperationUnavailableException(); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw new OperationUnavailableException(); + return value.clone(); + } + + private static long number(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number numeric)) throw new OperationUnavailableException(); + return numeric.longValue(); + } + + private static Long longValue(Record row, String field) { + Object value = row.get(field); + return value instanceof Number numeric ? numeric.longValue() : null; + } + + private static long positive(Record row, String field) { + long value = number(row, field); + if (value <= 0L) throw new OperationUnavailableException(); + return value; + } + + private static void requireV4(UUID value, String field) { + if (value == null || value.version() != 4 || !V4_UUID.matcher(value.toString()).matches()) { + throw new OperationUnavailableException(); + } + } + + private static void requireWritableAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account response-envelope storage requires a writable Account owner transaction"); + } + } + + private record PendingIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + long issuanceFence) {} + + private record CandidateIdentity( + String tokenHash, + String kid, + String signerGeneration, + GameSessionAccountDelegationRegistryRecord record) {} + + private record CommittedRecoveryIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String tokenHash, + long issuanceFence) { + private PendingIdentity pendingIdentity() { + return new PendingIdentity( + operationId, + requestId, + accountId, + callerWorkload, + callerContextId, + credentialRequestBinding, + requestDigest, + tokenJti, + issuedAtEpochSecond, + notBeforeEpochSecond, + expiresAtEpochSecond, + issuanceFence); + } + } + + /** Comparison inputs only; a caller transport must establish its authenticity separately. */ + public record CallerIdentity(String workload, UUID contextId) { + public CallerIdentity { + if (workload == null + || !GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(workload) + .matches() + || contextId == null + || contextId.version() != 4 + || contextId.variant() != 2) { + throw new IllegalArgumentException("Exact Game Session caller comparison is required"); + } + } + + @Override + public String toString() { + return "CallerIdentity[redacted]"; + } + } + + /** Non-authorizing readback metadata; no envelope or credential bytes are exposed. */ + public record SealedCandidateObservation( + UUID operationId, + UUID requestId, + String authorityEvidenceBundleSha256, + long issuanceFence, + long responseRecoveryExpiryEpochMillis, + String envelopeSha256, + int envelopeBytesLength) { + @Override + public String toString() { + return "SealedCandidateObservation[redacted]"; + } + } + + /** Pre-activation immutable identity read; it does not authenticate or authorize the caller. */ + public record RecoveryPreflight( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + String requestDigest, + UUID tokenJti, + long expiresAtEpochSecond, + long responseRecoveryExpiryEpochMillis) { + @Override + public String toString() { + return "RecoveryPreflight[non-authorizing,redacted]"; + } + } + + /** + * Exact compact JWT returned only after committed issuance activation and current owner reads. + */ + public static final class RecoveredCredential { + private final byte[] compactJwtBytes; + private final UUID accountId; + private final UUID tokenJti; + private final String tokenSha256; + private final String profile; + private final long expiresAtEpochSecond; + private final AccountAuthEvidenceBundle authEvidenceBundle; + + private RecoveredCredential( + byte[] compactJwtBytes, + UUID accountId, + UUID tokenJti, + String tokenSha256, + String profile, + long expiresAtEpochSecond, + AccountAuthEvidenceBundle authEvidenceBundle) { + this.compactJwtBytes = compactJwtBytes.clone(); + this.accountId = Objects.requireNonNull(accountId); + this.tokenJti = Objects.requireNonNull(tokenJti); + this.tokenSha256 = Objects.requireNonNull(tokenSha256); + this.profile = Objects.requireNonNull(profile); + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.authEvidenceBundle = + Objects.requireNonNull( + authEvidenceBundle, "Verified Account auth-evidence bundle is required"); + } + + public byte[] compactJwtBytes() { + return compactJwtBytes.clone(); + } + + public UUID accountId() { + return accountId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String profile() { + return profile; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public AccountAuthEvidenceBundle authEvidenceBundle() { + return authEvidenceBundle; + } + + @Override + public String toString() { + return "RecoveredCredential[secret,redacted]"; + } + } + + /** + * Transient exact plaintext readback for the Account signer retry path. This value is not a + * caller response or authorization proof and must be closed as soon as signature verification + * finishes. + */ + public static final class PendingCandidateCredential implements AutoCloseable { + private byte[] compactJwtBytes; + private final SealedCandidateObservation sealedCandidate; + + private PendingCandidateCredential( + byte[] compactJwtBytes, SealedCandidateObservation sealedCandidate) { + this.compactJwtBytes = Objects.requireNonNull(compactJwtBytes).clone(); + this.sealedCandidate = Objects.requireNonNull(sealedCandidate); + } + + public byte[] compactJwtBytes() { + if (compactJwtBytes == null) throw new StorageUnavailableException(); + return compactJwtBytes.clone(); + } + + public SealedCandidateObservation sealedCandidate() { + return sealedCandidate; + } + + @Override + public void close() { + if (compactJwtBytes != null) { + Arrays.fill(compactJwtBytes, (byte) 0); + compactJwtBytes = null; + } + } + + @Override + public String toString() { + return "PendingCandidateCredential[secret,redacted]"; + } + } + + public static final class OperationUnavailableException extends IllegalStateException { + public OperationUnavailableException() { + super("Account gameplay delegation operation is unavailable or ambiguous"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } + + public static final class CandidateUnavailableException extends IllegalStateException { + public CandidateUnavailableException() { + super("Account signed delegation candidate is unavailable or malformed"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } + + public static final class OwnerEvidenceUnavailableException extends IllegalStateException { + public OwnerEvidenceUnavailableException() { + super("Account owner evidence is unavailable, stale, or ambiguous"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } + + public static final class AuthorityChangedException extends IllegalStateException { + public AuthorityChangedException() { + super("Account gameplay delegation authority changed"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException() { + super("Account gameplay delegation response candidate conflicts with its PENDING operation"); + } + + public String errorCode() { + return "IDEMPOTENCY_CONFLICT"; + } + } + + public static final class ResponseRecoveryExpiredException extends IllegalStateException { + public ResponseRecoveryExpiredException() { + super("Account response recovery horizon has expired"); + } + + public String errorCode() { + return "RESPONSE_RECOVERY_EXPIRED"; + } + } + + public static final class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException() { + super("Account encrypted response-envelope storage is unavailable or ambiguous"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java new file mode 100644 index 0000000000..58429c57d6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java @@ -0,0 +1,245 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-row-first serialization of admission with exact-token revocation intent. Initial rows + * come only from the real SQL COMMITTED issuance writer. This is not a logout finalizer: no public + * method accepts a claimed Gateway acknowledgement or commits revocation completion. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected persistence context") +public class AccountGameplayTokenIdentityFenceRepository { + private static final String TABLE = "account_gameplay_token_identity_fences"; + private static final String COLUMNS = + "account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " + + "not_before_epoch_second, token_generation, issuance_fence, token_identity_fence, " + + "state, revocation_request_id, revocation_digest"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep the required DSLContext precondition fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayTokenIdentityFenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Must precede all authority, token, operation and admission row locks in the transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public void lockAccountForUpdate(UUID accountId) { + requireTransaction(); + Objects.requireNonNull(accountId); + if (dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId) + == null) throw new TokenFenceUnavailableException(); + } + + /** Exact current fence for reserve/finalize; a durable revocation intent denies immediately. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountGameplayTokenIdentityFence requireActiveForUpdate(TokenIdentity identity) { + requireTransaction(); + Objects.requireNonNull(identity); + lockAccountForUpdate(identity.accountId()); + AccountGameplayTokenIdentityFence fence = requireExact(identity, true); + if (fence.state() != State.ACTIVE) throw new TokenRevokedException(); + return fence; + } + + /** Package-private writer called only after the real issuance COMMITTED proof was validated. */ + AccountGameplayTokenIdentityFence registerCommittedIssuance(TokenIdentity identity) { + requireTransaction(); + lockAccountForUpdate(identity.accountId()); + dsl.execute( + "INSERT INTO " + + TABLE + + " (account_uuid, operation_id, issuance_request_id, token_hash, " + + "token_jti, not_before_epoch_second, token_generation, issuance_fence) " + + "SELECT account_uuid, operation_id, request_id, token_hash, token_jti, " + + "not_before_epoch_second, token_generation, issuance_fence " + + "FROM account_gameplay_delegation_issuance_operations " + + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? " + + "AND token_hash = ? AND token_jti = ? AND not_before_epoch_second = ? " + + "AND token_generation = ? AND issuance_fence = ? AND status = 'COMMITTED' " + + "ON CONFLICT (operation_id) DO NOTHING", + identity.operationId(), + identity.issuanceRequestId(), + identity.accountId(), + identity.tokenSha256(), + identity.tokenJti(), + identity.notBeforeEpochSecond(), + identity.tokenGeneration(), + identity.issuanceFence()); + return requireActiveForUpdate(identity); + } + + /** Independent metadata readback, including the source COMMITTED identity, never registration. */ + AccountGameplayTokenIdentityFence requireActiveReadback(TokenIdentity identity) { + AccountGameplayTokenIdentityFence fence = requireExact(identity, false); + if (fence.state() != State.ACTIVE) throw new TokenRevokedException(); + return fence; + } + + /** + * Durably starts the exact bounded revocation intent. Same request/digest replays its stored + * result, and changed requests conflict. No registry deletion or logout-success claim follows. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountGameplayTokenIdentityFence beginRevocationIntent( + TokenIdentity identity, UUID requestId, String digest) { + requireTransaction(); + Objects.requireNonNull(identity); + if (!revocationDigest(identity, requestId).equals(digest)) { + throw new IllegalArgumentException("Exact Account revocation digest required"); + } + lockAccountForUpdate(identity.accountId()); + AccountGameplayTokenIdentityFence before = requireExact(identity, true); + if (before.state() != State.ACTIVE) { + if (!requestId.equals(before.revocationRequestId()) + || !digest.equals(before.revocationDigest())) { + throw new RevocationConflictException(); + } + return before; + } + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET state = 'PENDING', token_identity_fence = 2, " + + "revocation_request_id = ?, revocation_digest = ? " + + "WHERE operation_id = ? AND state = 'ACTIVE' AND token_identity_fence = 1", + requestId, + digest, + identity.operationId()); + if (changed != 1) throw new TokenFenceUnavailableException(); + AccountGameplayTokenIdentityFence after = requireExact(identity, true); + if (after.state() != State.PENDING + || !requestId.equals(after.revocationRequestId()) + || !digest.equals(after.revocationDigest())) throw new TokenFenceUnavailableException(); + return after; + } + + public static String revocationDigest(TokenIdentity identity, UUID requestId) { + Objects.requireNonNull(identity); + if (requestId == null || requestId.version() != 4 || requestId.variant() != 2) { + throw new IllegalArgumentException("Canonical UUIDv4 revocation request required"); + } + // All fields have fixed/canonical syntax, so the domain-separated framing is unambiguous. + String input = + "account-gameplay-token-revocation-intent/v1\n" + + requestId + + "\n" + + identity.accountId() + + "\n" + + identity.operationId() + + "\n" + + identity.issuanceRequestId() + + "\n" + + identity.tokenSha256() + + "\n" + + identity.tokenJti() + + "\n" + + identity.notBeforeEpochSecond() + + "\n" + + identity.tokenGeneration() + + "\n" + + identity.issuanceFence() + + "\n"; + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(input.getBytes(StandardCharsets.US_ASCII))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private AccountGameplayTokenIdentityFence requireExact(TokenIdentity identity, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT " + + COLUMNS + + " FROM " + + TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + identity.operationId()); + if (row == null) throw new TokenFenceUnavailableException(); + AccountGameplayTokenIdentityFence fence = decode(row); + if (!identity.equals(fence.identity())) throw new TokenFenceUnavailableException(); + Record source = + dsl.fetchOne( + "SELECT operation_id FROM account_gameplay_delegation_issuance_operations " + + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? AND token_hash = ? " + + "AND token_jti = ? AND not_before_epoch_second = ? AND token_generation = ? " + + "AND issuance_fence = ? AND status = 'COMMITTED'", + identity.operationId(), + identity.issuanceRequestId(), + identity.accountId(), + identity.tokenSha256(), + identity.tokenJti(), + identity.notBeforeEpochSecond(), + identity.tokenGeneration(), + identity.issuanceFence()); + if (source == null) throw new TokenFenceUnavailableException(); + return fence; + } + + private static AccountGameplayTokenIdentityFence decode(Record row) { + try { + return new AccountGameplayTokenIdentityFence( + new TokenIdentity( + row.get("account_uuid", UUID.class), row.get("operation_id", UUID.class), + row.get("issuance_request_id", UUID.class), row.get("token_hash", String.class), + row.get("token_jti", UUID.class), row.get("not_before_epoch_second", Long.class), + row.get("token_generation", Long.class), row.get("issuance_fence", Long.class)), + row.get("token_identity_fence", Long.class), + State.valueOf(row.get("state", String.class)), + row.get("revocation_request_id", UUID.class), + row.get("revocation_digest", String.class)); + } catch (RuntimeException malformed) { + throw new TokenFenceUnavailableException(); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account transaction required"); + } + } + + public static final class TokenFenceUnavailableException extends IllegalStateException { + public TokenFenceUnavailableException() { + super("Exact Account token fence unavailable"); + } + } + + public static final class TokenRevokedException extends IllegalStateException { + public TokenRevokedException() { + super("Account token has a durable revocation fence"); + } + } + + public static final class RevocationConflictException extends IllegalStateException { + public RevocationConflictException() { + super("Account token revocation request conflicts"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java new file mode 100644 index 0000000000..baa911c7db --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ArgumentSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.CompatibilityLevel; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.KeySpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.MutationEffect; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.SupportedCoexistence; + +/** Account-owned single-key compare-and-set contract for its generation projection. */ +public final class AccountGenerationProjectionRedisContract { + public static final String SCRIPT_ID = "account.account-generation-projection.v1"; + public static final String RESOURCE_PATH = "redis/account_generation_projection_cas.lua"; + public static final String DESCRIPTOR_RESOURCE = + "/redis/scripts/account-generation-projection-cas.json"; + public static final String OWNER = "account-service"; + public static final String PRINCIPAL = "account_coord_app"; + public static final RedisRole ROLE = RedisRole.COORDINATION; + public static final ScriptCategory CATEGORY = ScriptCategory.SESSION_CAS; + public static final String KEY_PREFIX = AccountGenerationProjection.KEY_PREFIX; + public static final String RESOURCE_SHA256 = + "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507"; + + private static final List KEYS = + List.of( + new KeySpec("accountGenerationProjection", KEY_PREFIX, HashTagDeclaration.NOT_REQUIRED)); + private static final List ARGUMENTS = + List.of( + new ArgumentSpec("expectedMode"), + new ArgumentSpec("expectedBytes"), + new ArgumentSpec("candidateBytes")); + private static final List OUTCOMES = + List.of( + outcome("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + outcome("REPLAY", OutcomeCategory.REPLAY, MutationEffect.NON_MUTATING), + outcome("STALE", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + outcome("INVALID", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING), + outcome("TTL_PRESENT", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING)); + private static final ResetSensitivity RESET_SENSITIVITY = ResetSensitivity.CLUSTER; + private static final LossClass LOSS_CLASS = LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP; + private static final String TAIL_LOSS_BEHAVIOR = + "On loss, fail closed and rebuild only from Account's exact current durable source snapshot."; + private static final CompatibilityLevel COMPATIBILITY_LEVEL = + CompatibilityLevel.REQUIRES_CLUSTER_RESET; + private static final List SUPPORTED_COEXISTENCE = + List.of(new SupportedCoexistence("v1", "v1")); + private static final RedisScriptCatalog CATALOG = + RedisScriptCatalog.loadInstalled( + AccountGenerationProjectionRedisContract.class.getClassLoader()); + + private AccountGenerationProjectionRedisContract() {} + + /** Resolves and checks the catalogued descriptor before any private Redis execution. */ + public static RedisScriptDescriptor descriptor() { + RedisScriptDescriptor descriptor = CATALOG.require(SCRIPT_ID); + requireSupportedDescriptor(descriptor); + return descriptor; + } + + /** Validates the Account-local invocation shape before the private single-key CAS call. */ + static void validateInvocation( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + Objects.requireNonNull(key, "Account generation key is required"); + Objects.requireNonNull(expectedMode, "Expected generation mode is required"); + Objects.requireNonNull(expectedBytes, "Expected generation bytes are required"); + Objects.requireNonNull(candidateBytes, "Candidate generation bytes are required"); + requireCanonicalAccountKey(key); + switch (expectedMode) { + case "ABSENT" -> { + if (!expectedBytes.isEmpty() || candidateBytes.isEmpty()) { + throw new IllegalArgumentException("ABSENT projection invocation is malformed"); + } + } + case "PRESENT" -> { + if (expectedBytes.isEmpty() || candidateBytes.isEmpty()) { + throw new IllegalArgumentException("PRESENT projection invocation is malformed"); + } + } + case "VERIFY" -> { + if (expectedBytes.isEmpty() || !candidateBytes.isEmpty()) { + throw new IllegalArgumentException("VERIFY projection invocation is malformed"); + } + } + default -> throw new IllegalArgumentException("Account projection mode is unsupported"); + } + } + + static void requireSupportedDescriptor(RedisScriptDescriptor descriptor) { + if (descriptor == null + || !descriptor.equals(CATALOG.require(SCRIPT_ID)) + || !SCRIPT_ID.equals(descriptor.scriptId()) + || !OWNER.equals(descriptor.owner()) + || !RESOURCE_PATH.equals(descriptor.resourcePath()) + || !RESOURCE_SHA256.equals(descriptor.sha256()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != ROLE + || descriptor.category() != CATEGORY + || !KEYS.equals(descriptor.keys()) + || !ARGUMENTS.equals(descriptor.arguments()) + || descriptor.resetSensitivity() != RESET_SENSITIVITY + || descriptor.lossClass() != LOSS_CLASS + || !TAIL_LOSS_BEHAVIOR.equals(descriptor.tailLossBehavior()) + || descriptor.compatibilityLevel() != COMPATIBILITY_LEVEL + || !SUPPORTED_COEXISTENCE.equals(descriptor.supportedCoexistence()) + || descriptor.legacyPayloadShape() != null + || !OUTCOMES.equals(descriptor.outcomes())) { + throw new IllegalStateException( + "Account current-generation projection descriptor differs from its owner contract"); + } + } + + private static void requireCanonicalAccountKey(String key) { + if (!key.startsWith(KEY_PREFIX)) { + throw new IllegalArgumentException("Account generation key is outside its owner prefix"); + } + String accountId = key.substring(KEY_PREFIX.length()); + try { + UUID parsed = UUID.fromString(accountId); + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(accountId)) { + throw new IllegalArgumentException( + "Account generation key must use a canonical non-nil UUID"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account generation key must use a canonical non-nil UUID", malformed); + } + } + + private static OutcomeSpec outcome(String code, OutcomeCategory category, MutationEffect effect) { + return new OutcomeSpec(code, category, effect); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java new file mode 100644 index 0000000000..86e11d5e21 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.accountservice.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive Account-owned catalog contribution for its generation-projection CAS script. */ +public final class AccountGenerationProjectionRedisScriptContribution + implements RedisScriptContribution { + private static final int MAX_DESCRIPTOR_BYTES = 16 * 1024; + private static final String DESCRIPTOR_RESOURCE = + "/redis/scripts/account-generation-projection-cas.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = + AccountGenerationProjectionRedisScriptContribution.class.getResourceAsStream( + DESCRIPTOR_RESOURCE)) { + if (input == null) { + throw new IllegalStateException("Account generation projection descriptor is unavailable"); + } + byte[] bytes = input.readNBytes(MAX_DESCRIPTOR_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_DESCRIPTOR_BYTES) { + throw new IllegalStateException( + "Account generation projection descriptor exceeds its finite bound"); + } + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!"account-service".equals(descriptor.owner()) + || !AccountGenerationProjectionRedisContract.SCRIPT_ID.equals(descriptor.scriptId())) { + throw new IllegalStateException( + "Account generation projection descriptor identity is invalid"); + } + return List.of(descriptor); + } catch (IOException | RuntimeException exception) { + if (exception instanceof IllegalStateException state) throw state; + throw new IllegalStateException("Account generation projection descriptor is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java new file mode 100644 index 0000000000..ddae2cd8bd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java @@ -0,0 +1,149 @@ +package net.firedevops.firemud.accountservice.service; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; + +/** Package-private Redis mechanics shared only by Account's typed generation-projection stores. */ +final class CurrentGenerationProjectionRedisSupport { + private static final String RESOURCE_PATH = + AccountGenerationProjectionRedisContract.RESOURCE_PATH; + private static final byte[] CAS_SCRIPT_BYTES = scriptBytes(); + private static final String CAS_SCRIPT_SHA1 = digest("SHA-1", CAS_SCRIPT_BYTES); + private static final String CAS_SCRIPT_SHA256 = digest("SHA-256", CAS_SCRIPT_BYTES); + + private CurrentGenerationProjectionRedisSupport() {} + + static void verifyScriptDigest(RedisScriptDescriptor descriptor) { + requireSupportedDescriptor(descriptor); + if (!CAS_SCRIPT_SHA256.equals(descriptor.sha256())) { + throw new IllegalStateException( + "Account current-generation projection Lua resource digest differs from its registration"); + } + } + + static StoredValue readStoredValue(StringRedisTemplate template, String key) { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + return template.execute( + (RedisCallback) + connection -> { + byte[] value = connection.stringCommands().get(keyBytes); + long ttlMillis = value == null ? -2L : connection.keyCommands().pTtl(keyBytes); + return new StoredValue(value, ttlMillis); + }); + } + + static String executeRegistered( + StringRedisTemplate template, + RedisScriptDescriptor expectedDescriptor, + String key, + String expectedMode, + String expectedBytes, + String candidateBytes) { + requireSupportedDescriptor(expectedDescriptor); + AccountGenerationProjectionRedisContract.validateInvocation( + key, expectedMode, expectedBytes, candidateBytes); + verifyScriptDigest(expectedDescriptor); + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + byte[] expectedModeBytes = expectedMode.getBytes(StandardCharsets.US_ASCII); + byte[] expectedBytesUtf8 = expectedBytes.getBytes(StandardCharsets.UTF_8); + byte[] candidateBytesUtf8 = candidateBytes.getBytes(StandardCharsets.UTF_8); + return template.execute( + (RedisCallback) + connection -> { + String loadedSha = connection.scriptingCommands().scriptLoad(CAS_SCRIPT_BYTES); + if (!CAS_SCRIPT_SHA1.equals(loadedSha)) { + throw new IllegalStateException( + "Redis loaded a different Account current-generation projection script"); + } + Object result = + connection + .scriptingCommands() + .evalSha( + loadedSha, + ReturnType.INTEGER, + 1, + keyBytes, + expectedModeBytes, + expectedBytesUtf8, + candidateBytesUtf8); + return decodeScriptResult(result); + }); + } + + static String decodeScriptResult(Object result) { + final String code; + if (result instanceof byte[] bytes) { + try { + code = + StandardCharsets.US_ASCII + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalStateException("Account projection script returned non-ASCII", malformed); + } + } else if (result instanceof String text) { + code = text; + } else if (result instanceof Long number) { + code = Long.toString(number); + } else if (result instanceof Integer number) { + code = Integer.toString(number); + } else { + throw new IllegalStateException( + "Registered Account generation projection script returned an unsupported result type"); + } + return switch (code) { + case "1" -> "APPLIED"; + case "0" -> "REPLAY"; + case "-1" -> "STALE"; + case "-2" -> "INVALID"; + case "-3" -> "TTL_PRESENT"; + default -> + throw new IllegalStateException( + "Registered Account generation projection script returned an unknown outcome"); + }; + } + + static String decodeUtf8(byte[] value) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } + + private static void requireSupportedDescriptor(RedisScriptDescriptor descriptor) { + AccountGenerationProjectionRedisContract.requireSupportedDescriptor(descriptor); + } + + private static byte[] scriptBytes() { + try (var input = new ClassPathResource(RESOURCE_PATH).getInputStream()) { + return input.readAllBytes(); + } catch (IOException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + record StoredValue(byte[] bytes, long ttlMillis) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java new file mode 100644 index 0000000000..db10824751 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java @@ -0,0 +1,295 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayReadback; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.common.EmailCanonicalization; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicit Account owner for request-bound gameplay LOGIN, activated only by its protected + * default-inactive Spring composition. + * + *

Credential verification and optional one-time challenge consumption occur in the same SQL + * transaction as the immutable keyed PENDING operation. Signing, registry writes, commit, response + * recovery, and credential release run only after that transaction closes, through their existing + * owner boundaries. Construction requires the protected key source and complete issuance owners; + * The default-inactive runtime composition is outside this source intake. + */ +public final class AccountGameplayCanonicalLoginOwner { + private static final UUID DECOY_ACCOUNT_ID = + UUID.fromString("03640e49-b334-4c03-8e4f-685bfd17ce17"); + private final AccountRepository accounts; + private final AccountGameplayDelegationIssuanceRepository issuance; + private final AccountGameplayCredentialRequestDigestKeySource digestKeys; + private final AccountGameplayDelegationIssuanceCommitService commitOwner; + private final AccountGameplayDelegationResponseRecoveryOwner responseOwner; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + public AccountGameplayCanonicalLoginOwner( + AccountRepository accounts, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayCredentialRequestDigestKeySource digestKeys, + AccountGameplayDelegationIssuanceCommitService commitOwner, + AccountGameplayDelegationResponseRecoveryOwner responseOwner, + PlatformTransactionManager transactionManager, + Clock clock) { + this.accounts = Objects.requireNonNull(accounts, "Account repository is required"); + this.issuance = Objects.requireNonNull(issuance, "Account issuance owner is required"); + this.digestKeys = Objects.requireNonNull(digestKeys, "Account digest key source is required"); + this.commitOwner = Objects.requireNonNull(commitOwner, "Account commit owner is required"); + this.responseOwner = + Objects.requireNonNull(responseOwner, "Account response owner is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** + * Authenticates, prepares or replays one exact operation, then returns its verified credential + * and immutable, non-authorizing Account evidence bundle. + */ + public InitialGameplayLoginResult authenticate( + CanonicalGameplayLoginRequest request, + String verifiedGameSessionWorkload, + CredentialVerifier credentialVerifier) { + requireRequest(request, verifiedGameSessionWorkload, credentialVerifier); + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + + String normalizedEmail = EmailCanonicalization.normalize(request.email()); + LoginPreparation preparation = + accountTransaction.execute( + status -> + prepareOrReplay( + request, normalizedEmail, verifiedGameSessionWorkload, credentialVerifier)); + if (preparation == null) throw unavailable(); + if (preparation.authenticationFailure() != null) { + throw preparation.authenticationFailure(); + } + UUID accountId = preparation.accountId(); + if (accountId == null) throw unavailable(); + + // These existing owners close the signing -> durable commit -> activation -> decryption path. + // None is invoked while an Account SQL transaction or Account authority lock remains held. + commitOwner.commitPendingCandidate(request.requestId()); + RecoveredCredential recovered = + responseOwner.recoverInitialLoginResponse( + request.requestId(), + accountId, + new CallerIdentity(verifiedGameSessionWorkload, request.sourceContext().contextId())); + return InitialGameplayLoginResult.fromRecoveredCredential(recovered); + } + + private LoginPreparation prepareOrReplay( + CanonicalGameplayLoginRequest request, + String normalizedEmail, + String callerWorkload, + CredentialVerifier credentialVerifier) { + Optional existing = + issuance.readCurrentGameplayLoginReplay(request.requestId()); + if (existing.isPresent()) { + return LoginPreparation.authenticated( + requireExactReplay(request, normalizedEmail, callerWorkload, existing.orElseThrow())); + } + + Optional foundAccount = accounts.findByEmail(normalizedEmail); + if (foundAccount.isEmpty()) { + // The credential authority performs its equivalent-cost decoy verification without an + // Account or challenge write. Completion never changes the missing-Account denial. + AccountGameplayCredentialRequestDigester.bind( + currentDigestKey(), request, normalizedEmail, callerWorkload, DECOY_ACCOUNT_ID); + credentialVerifier.verifyAbsentAccountCredential(request.credential()); + throw invalidCredentials(); + } + Account found = foundAccount.orElseThrow(); + Account account = + accounts + .findByIdForUpdate(found.getId()) + .orElseThrow(AccountGameplayCanonicalLoginOwner::invalidCredentials); + if (account.getAccountUuid() == null + || !normalizedEmail.equals(EmailCanonicalization.normalize(account.getEmail()))) { + throw invalidCredentials(); + } + + // Account row serialization ensures a concurrent exact request can win and consume an OTP + // before this invocation verifies it. Re-read the idempotency owner after obtaining that lock. + existing = issuance.readCurrentGameplayLoginReplay(request.requestId()); + if (existing.isPresent()) { + return LoginPreparation.authenticated( + requireExactReplay(request, normalizedEmail, callerWorkload, existing.orElseThrow())); + } + + CredentialDigestKey key = currentDigestKey(); + AccountGameplayCredentialRequestBinding binding = + AccountGameplayCredentialRequestDigester.bind( + key, request, normalizedEmail, callerWorkload, account.getAccountUuid()); + + CredentialVerification credential; + try { + credential = + Objects.requireNonNull( + credentialVerifier.verify(account, request.credential()), + "Account credential verification result is required"); + } catch (AuthenticationException denial) { + if (!AuthenticationErrorCodes.INVALID_CREDENTIALS.equals(denial.getCode())) { + throw denial; + } + // Invalid credentials may have durably incremented or expired an OTP challenge. Return + // this denial from the callback so the owner transaction commits that evidence, then rethrow + // only after TransactionTemplate completes. No issuance intent exists yet. + return LoginPreparation.denied(denial); + } + if (!account.getAccountUuid().equals(credential.accountId())) throw unavailable(); + + GameplayLoginReplayReadback pending = + issuance.beginPendingForAccount( + request.requestId(), + account.getAccountUuid(), + callerWorkload, + request.sourceContext().contextId(), + binding); + if (pending.created() && credential.oneTimeChallengeId() != null) { + credentialVerifier.consumeOneTimeCredential(account, credential); + } + return LoginPreparation.authenticated(account.getAccountUuid()); + } + + private CredentialDigestKey currentDigestKey() { + long now = Math.floorDiv(clock.millis(), 1_000L); + long requiredExpiry; + try { + requiredExpiry = + Math.addExact(now, GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS + 2L); + } catch (ArithmeticException ex) { + throw unavailable(); + } + CredentialDigestKey key = digestKeys.currentKey(); + requireKeyRetainedThrough(key, Instant.ofEpochSecond(requiredExpiry)); + return key; + } + + private record LoginPreparation(UUID accountId, AuthenticationException authenticationFailure) { + private LoginPreparation { + if ((accountId == null) == (authenticationFailure == null)) { + throw unavailable(); + } + } + + private static LoginPreparation authenticated(UUID accountId) { + return new LoginPreparation(Objects.requireNonNull(accountId), null); + } + + private static LoginPreparation denied(AuthenticationException failure) { + return new LoginPreparation(null, Objects.requireNonNull(failure)); + } + } + + private UUID requireExactReplay( + CanonicalGameplayLoginRequest request, + String normalizedEmail, + String callerWorkload, + GameplayLoginReplayReadback replay) { + var identity = replay.identity(); + if (!identity.callerWorkload().equals(callerWorkload) + || !identity.callerContextId().equals(request.sourceContext().contextId())) { + throw conflict(); + } + CredentialDigestKey key = + digestKeys.requireKey(identity.credentialRequestBinding().digestKeyId()); + if (key == null || !identity.credentialRequestBinding().digestKeyId().equals(key.keyId())) { + throw unavailable(); + } + requireKeyRetainedThrough(key, Instant.ofEpochSecond(identity.expiresAtEpochSecond())); + AccountGameplayCredentialRequestBinding candidate = + AccountGameplayCredentialRequestDigester.bind( + key, request, normalizedEmail, callerWorkload, identity.accountId()); + if (!AccountGameplayCredentialRequestDigester.matches( + identity.credentialRequestBinding(), candidate)) { + throw conflict(); + } + if (replay.state() != GameplayLoginReplayState.PENDING + && replay.state() != GameplayLoginReplayState.COMMITTED) { + throw unavailable(); + } + return identity.accountId(); + } + + private static void requireKeyRetainedThrough(CredentialDigestKey key, Instant horizon) { + if (key == null || key.retainedUntil().isBefore(horizon)) throw unavailable(); + } + + private static void requireRequest( + CanonicalGameplayLoginRequest request, String workload, CredentialVerifier verifier) { + Objects.requireNonNull(request, "Canonical gameplay LOGIN request is required"); + Objects.requireNonNull(verifier, "Account credential verifier is required"); + if (workload == null + || !GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(workload) + .matches()) { + throw new IllegalArgumentException("Verified Game Session workload identity is required"); + } + } + + private static AuthenticationException invalidCredentials() { + return new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials"); + } + + private static IdempotencyConflictException conflict() { + return new IdempotencyConflictException(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Account gameplay LOGIN is unavailable"); + } + + /** Account's existing password/OTP authority; no credential value is retained in its result. */ + public interface CredentialVerifier { + /** + * Performs equivalent-cost credential verification against protected decoy evidence, without + * creating or consuming Account/challenge state. A successful return grants no authentication. + * The concrete password/OTP authority must supply this operation; timing parity still requires + * representative proof for its configured implementation. + */ + void verifyAbsentAccountCredential(String presentedCredential); + + CredentialVerification verify(Account account, String presentedCredential); + + void consumeOneTimeCredential(Account account, CredentialVerification verification); + } + + public record CredentialVerification(UUID accountId, Long oneTimeChallengeId) { + public CredentialVerification { + Objects.requireNonNull(accountId, "Verified Account identity is required"); + if (oneTimeChallengeId != null && oneTimeChallengeId <= 0L) { + throw new IllegalArgumentException("One-time challenge identity is malformed"); + } + } + + @Override + public String toString() { + return "CredentialVerification[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigestKeySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigestKeySource.java new file mode 100644 index 0000000000..e65849ac1a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigestKeySource.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Instant; +import java.util.Objects; +import javax.crypto.SecretKey; + +/** Account-owned source for the current and retained keyed credential-request digest keys. */ +public interface AccountGameplayCredentialRequestDigestKeySource { + CredentialDigestKey currentKey(); + + CredentialDigestKey requireKey(String keyId); + + /** Protected key material plus the horizon through which its identifier remains resolvable. */ + final class CredentialDigestKey { + private final String keyId; + private final SecretKey key; + private final Instant retainedUntil; + + public CredentialDigestKey(String keyId, SecretKey key, Instant retainedUntil) { + if (keyId == null || !keyId.matches("[A-Za-z0-9_-]{1,32}")) { + throw new IllegalArgumentException("Account credential digest key ID is malformed"); + } + this.keyId = keyId; + this.key = Objects.requireNonNull(key, "Account credential digest key is required"); + if (!"HmacSHA256".equalsIgnoreCase(key.getAlgorithm())) { + throw new IllegalArgumentException("Account credential digest key must use HmacSHA256"); + } + this.retainedUntil = + Objects.requireNonNull(retainedUntil, "Account credential digest retention is required"); + } + + public String keyId() { + return keyId; + } + + public SecretKey key() { + return key; + } + + public Instant retainedUntil() { + return retainedUntil; + } + + @Override + public String toString() { + return "CredentialDigestKey[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigester.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigester.java new file mode 100644 index 0000000000..c719597b6f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigester.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import javax.crypto.Mac; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Computes the non-reusable, Account-keyed identity of one exact gameplay LOGIN request. */ +public final class AccountGameplayCredentialRequestDigester { + private static final byte[] DOMAIN = + "account-gameplay-credential-request/v1".getBytes(StandardCharsets.US_ASCII); + + private AccountGameplayCredentialRequestDigester() {} + + public static AccountGameplayCredentialRequestBinding bind( + AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey key, + CanonicalGameplayLoginRequest request, + String normalizedEmail, + String verifiedCallerWorkload, + java.util.UUID accountId) { + Objects.requireNonNull(key, "Account credential digest key is required"); + Objects.requireNonNull(request, "Canonical gameplay LOGIN request is required"); + requireVerifiedWorkload(verifiedCallerWorkload); + Objects.requireNonNull(accountId, "Resolved Account identity is required"); + GameplayCredentialSourceContext source = request.sourceContext(); + List fields = new ArrayList<>(); + byte[] credentialBytes = request.credential().getBytes(StandardCharsets.UTF_8); + fields.add(DOMAIN.clone()); + fields.add(utf8("INITIAL_GAMEPLAY_LOGIN")); + fields.add(utf8(request.requestId().toString())); + fields.add(utf8(accountId.toString())); + fields.add(utf8(normalizedEmail)); + fields.add(utf8(verifiedCallerWorkload)); + fields.add(utf8(source.contextId().toString())); + fields.add(utf8(source.canonicalClientAddress())); + fields.add(utf8(source.transportClass())); + fields.add(credentialBytes); + int capacity = 0; + for (byte[] field : fields) capacity = Math.addExact(capacity, Integer.BYTES + field.length); + byte[] framed = new byte[capacity]; + try { + ByteBuffer buffer = ByteBuffer.wrap(framed); + for (byte[] field : fields) buffer.putInt(field.length).put(field); + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(key.key()); + byte[] digest = mac.doFinal(framed); + try { + return new AccountGameplayCredentialRequestBinding( + 1, key.keyId(), HexFormat.of().formatHex(digest)); + } finally { + java.util.Arrays.fill(digest, (byte) 0); + } + } catch (java.security.GeneralSecurityException | ArithmeticException ex) { + throw new CredentialDigestUnavailableException(); + } finally { + java.util.Arrays.fill(framed, (byte) 0); + for (byte[] field : fields) java.util.Arrays.fill(field, (byte) 0); + } + } + + public static boolean matches( + AccountGameplayCredentialRequestBinding expected, + AccountGameplayCredentialRequestBinding candidate) { + if (expected == null + || candidate == null + || expected.digestSchemaVersion() != candidate.digestSchemaVersion() + || !expected.digestKeyId().equals(candidate.digestKeyId())) { + return false; + } + return MessageDigest.isEqual( + HexFormat.of().parseHex(expected.credentialRequestDigest()), + HexFormat.of().parseHex(candidate.credentialRequestDigest())); + } + + private static byte[] utf8(String value) { + return Objects.requireNonNull(value, "Digest input field is required") + .getBytes(StandardCharsets.UTF_8); + } + + private static void requireVerifiedWorkload(String workload) { + if (workload == null + || !GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(workload) + .matches()) { + throw new IllegalArgumentException("Verified Game Session workload identity is required"); + } + } + + public static final class CredentialDigestUnavailableException extends IllegalStateException { + public CredentialDigestUnavailableException() { + super("Account credential request binding is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java index ec432eac62..bf85c73f47 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java @@ -1,22 +1,48 @@ package net.firedevops.firemud.accountservice.service.session; +import java.io.IOException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Arrays; import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; /** - * Converts exact owner-read issuer and Account source heads to their canonical projections. + * Explicit, non-authorizing Account source-head projection publisher and observer. * - *

The returned bytes are informational source projections. They do not authorize a token or - * establish freshness, publication, or admission state. + *

The SQL owner snapshot is captured and its transaction ends before Coordination Redis is + * contacted. The canonical keys are in distinct Redis Cluster hash slots, so publication uses the + * Account client's same pinned physical connection for separate one-key CAS scripts, followed by + * one WAITAOF and exact byte readback of all values. This is an asynchronous projection: it is + * neither atomic with Account SQL nor by itself a token-authorization decision. No numeric + * freshness window is declared here because the canonical owner contract supplies none. */ public final class AccountGameplayDelegationAuthorityProjection { public static final String ISSUER_KEY_PREFIX = "session:auth:generation:issuer:"; @@ -24,8 +50,637 @@ public final class AccountGameplayDelegationAuthorityProjection { public static final int MAX_PROJECTION_BYTES = 8 * 1024; private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); - private AccountGameplayDelegationAuthorityProjection() {} + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final TransactionTemplate accountTransaction; + private final AccountGameplayDelegationRedisClient coordinationRedis; + private SelectedOwner selectedOwner; + + public AccountGameplayDelegationAuthorityProjection( + AccountAuthoritySourceEvidenceRepository sourceEvidence, + PlatformTransactionManager transactionManager, + AccountGameplayDelegationRedisClient coordinationRedis) { + this( + sourceEvidence, + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")), + coordinationRedis); + } + + AccountGameplayDelegationAuthorityProjection( + AccountAuthoritySourceEvidenceRepository sourceEvidence, + TransactionTemplate accountTransaction, + AccountGameplayDelegationRedisClient coordinationRedis) { + this.sourceEvidence = + Objects.requireNonNull(sourceEvidence, "Account source evidence is required"); + this.accountTransaction = Objects.requireNonNull(accountTransaction); + this.coordinationRedis = Objects.requireNonNull(coordinationRedis); + } + + /** Real owner dependencies; no caller-supplied snapshot/currentness callback is accepted. */ + public AccountGameplayDelegationAuthorityProjection( + AccountAuthoritySourceEvidenceRepository sourceEvidence, + PlatformTransactionManager transactionManager, + AccountGameplayDelegationRedisClient coordinationRedis, + AccountAuthorityGenerationRepository generations, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountAuthorityOutboxRepository outbox, + AccountTenantAuthorityEventRepository tenantSources) { + this(sourceEvidence, transactionManager, coordinationRedis); + this.selectedOwner = + new SelectedOwner( + Objects.requireNonNull(generations), + Objects.requireNonNull(memberships), + Objects.requireNonNull(pairs), + Objects.requireNonNull(outbox), + Objects.requireNonNull(tenantSources)); + accountTransaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_REPEATABLE_READ); + accountTransaction.setReadOnly(false); + } + + /** Replays captured owner heads through pinned Redis CAS; never an admission decision. */ + public SelectedProjectionObservation publishSelectedCurrent(UUID accountId, UUID tenantId) { + requireOutsideOwnerTransaction(); + SelectedSnapshot before = readSelectedSnapshot(accountId, tenantId); + var outcome = + coordinationRedis.publishAuthorityProjections( + accountId, before.values()[0], before.values()[1]); + byte[][] redisHeads = coordinationRedis.readSelectedAuthorityHeads(accountId, tenantId); + boolean exactRetry = + outcome == AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY; + exactRetry &= + replayRetainedHistory( + before.tenantCheckpoint(), + redisHeads[0], + before.values()[2], + accountId, + tenantId, + true); + exactRetry &= + replayRetainedHistory( + before.membershipCheckpoint(), + redisHeads[1], + before.values()[3], + accountId, + tenantId, + false); + byte[][] selectedReadback = coordinationRedis.readSelectedAuthorityHeads(accountId, tenantId); + if (!Arrays.equals(selectedReadback[0], before.values()[2]) + || !Arrays.equals(selectedReadback[1], before.values()[3])) { + throw new ProjectionUnavailableException(); + } + SelectedSnapshot after = readSelectedSnapshot(accountId, tenantId); + requireSameSelectedSnapshot(before, after); + return new SelectedProjectionObservation( + after, + exactRetry + ? AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY + : AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + } + + /** + * Actual SQL owner reads surround exact Redis observation, including independent member version. + */ + public SelectedProjectionObservation observeSelectedCurrent(UUID accountId, UUID tenantId) { + requireOutsideOwnerTransaction(); + SelectedSnapshot before = readSelectedSnapshot(accountId, tenantId); + byte[][] actual = coordinationRedis.readSelectedAuthorityProjections(accountId, tenantId); + SelectedSnapshot after = readSelectedSnapshot(accountId, tenantId); + requireSameSelectedSnapshot(before, after); + if (!Arrays.deepEquals(actual, after.values())) throw new StaleProjectionException(); + return new SelectedProjectionObservation(after, null); + } + + private SelectedSnapshot readSelectedSnapshot(UUID accountId, UUID tenantId) { + requireAccountId(accountId); + requireAccountId(tenantId); + if (selectedOwner == null) throw new ProjectionUnavailableException(); + SelectedSnapshot result = + accountTransaction.execute( + status -> { + // The source and composite owners both take Account first; the composite fixes all + // four scopes. + var source = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + var composite = + selectedOwner + .generations() + .readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + accountId, + List.of(tenantId), + List.of(tenantId)); + var tenant = selectedOwner.tenantSources().readCurrentByTenant(tenantId); + var member = + selectedOwner + .memberships() + .findFreshMembershipForUpdate(accountId, tenantId) + .orElseThrow(ProjectionUnavailableException::new); + var pair = + selectedOwner + .pairs() + .readForUpdate(accountId, tenantId) + .orElseThrow(ProjectionUnavailableException::new); + String memberStream = + "account:auth-authority:v1:membership/" + accountId + "/" + tenantId; + var memberCheckpoint = + selectedOwner + .outbox() + .readCheckpoint(memberStream) + .orElseThrow(ProjectionUnavailableException::new); + String tenantStream = "account:auth-authority:v1:tenant/" + tenantId; + var tenantCheckpoint = + selectedOwner + .outbox() + .readCheckpoint(tenantStream) + .orElseThrow(ProjectionUnavailableException::new); + var memberEvent = + selectedOwner + .outbox() + .findEvent(memberStream, memberCheckpoint.outboxSequence()) + .orElseThrow(ProjectionUnavailableException::new); + var tenantEvent = + selectedOwner + .outbox() + .findEvent(tenantStream, tenantCheckpoint.outboxSequence()) + .orElseThrow(ProjectionUnavailableException::new); + var event = memberEvent; + var verified = + MembershipAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + var tenantState = composite.tenants().getFirst(); + var memberState = composite.memberships().getFirst(); + if (source.issuer().generation() != composite.issuer().generation() + || source.issuer().sourceVersion() != composite.issuer().sourceVersion() + || source.account().generation() != composite.account().generation() + || source.account().sourceVersion() != composite.account().sourceVersion() + || !source.issuanceFence().equals(composite.issuanceFence()) + || tenant.tenantAuthorityGeneration() != tenantState.generation() + || tenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion() + || !tenantId.equals(tenant.tenantId()) + || !pair.provenance() + .sourceOperationId() + .equals(tenant.sourceEvidence().operationId()) + || !pair.provenance().digest().equals(tenant.sourceEvidence().evidenceDigest()) + || !pair.membershipExists() + || pair.lastTransitionInvalidated() + || !"ACTIVE".equals(member.getLifecycleState()) + || !member.isGameplayAdmissionAllowed() + || member.getMembershipVersion() != pair.membershipVersion() + || member.getMembershipAuthorityGeneration() + != pair.membershipAuthorityGeneration() + || memberState.generation() != pair.membershipAuthorityGeneration() + || memberState.sourceVersion() != memberState.generation() + || !Long.toString(memberState.sourceVersion()) + .equals(verified.membershipAuthorityGeneration()) + || memberCheckpoint.outboxSequence() != pair.eventSequence() + || !memberCheckpoint.sourceEventId().equals(pair.eventId()) + || !memberCheckpoint.sourceEventDigest().equals(pair.eventDigest()) + || !event.eventId().equals(pair.eventId()) + || !event.eventDigest().equals(pair.eventDigest()) + || !Long.toString(memberCheckpoint.outboxSequence()) + .equals(verified.outboxSequence()) + || !memberCheckpoint.outboxStreamKey().equals(verified.outboxStreamKey()) + || tenantCheckpoint.outboxSequence() != tenant.outboxSequence() + || !tenantCheckpoint.sourceEventId().equals(tenant.eventId().toString()) + || !tenantCheckpoint.sourceEventDigest().equals(tenant.eventDigest()) + || !tenantEvent.eventId().equals(tenant.eventId().toString()) + || !tenantEvent.eventDigest().equals(tenant.eventDigest()) + || !Arrays.equals(tenantEvent.payload(), tenant.payload()) + || !Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !accountId.toString().equals(verified.accountId()) + || !tenantId.toString().equals(verified.tenantId()) + || !Long.toString(pair.membershipVersion()) + .equals(verified.membershipVersion().get(tenantId.toString())) + || !Long.toString(pair.membershipAuthorityGeneration()) + .equals(verified.membershipAuthorityGeneration()) + || !"ACTIVE".equals(verified.membershipLifecycleState()) + || !verified.gameplayAdmissionAllowed() + || verified.callerBoundAuthorityInvalidated() + || !verified.roles().contains("player")) + throw new ProjectionUnavailableException(); + // The immutable event proves this pair, not today's independent global/tenant + // sources. + // Derive today's tuple from the same locked owner read; never rewrite the historical + // event. + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(composite.issuer().generation())); + tuple.put( + "accountAuthorityGeneration", Long.toString(composite.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(tenantState.generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(memberState.generation()))); + tuple.put("privateRealmGrantVersions", List.of()); + var accountCutoff = source.account().accountSecurityCutoff(); + if (accountCutoff.isPresent()) { + var cutoff = accountCutoff.orElseThrow(); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); + } + // The explicit demo owner has positive linked billing evidence; non-paid does not + // mean absent cutoff. + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + Long.toString(tenant.tenantAuthorityGeneration()), + "tenantBillingSequence", Long.toString(tenant.tenantBillingSequence()), + "outboxStreamKey", tenant.tenantBillingStreamKey(), + "outboxSequence", Long.toString(tenant.tenantBillingSequence())))); + byte[][] initial = canonicalProjectionPair(source); + byte[] tenantProjectionBytes = + tenantProjection(tenantEvent, tenantId).canonicalBytes(); + byte[] membershipProjection = + membershipProjection(memberEvent, accountId, tenantId).canonicalBytes(); + return new SelectedSnapshot( + source, + composite, + pair, + verified.canonicalJson(), + new String(tenant.payload(), StandardCharsets.UTF_8), + canonical(tuple), + new byte[][] { + initial[0], initial[1], tenantProjectionBytes, membershipProjection + }, + tenantCheckpoint, + memberCheckpoint); + }); + if (result == null) throw new ProjectionUnavailableException(); + return result; + } + + private boolean replayRetainedHistory( + AccountAuthorityOutboxRepository.Checkpoint checkpoint, + byte[] redisHead, + byte[] expectedHead, + UUID accountId, + UUID tenantId, + boolean tenant) { + String streamKey = checkpoint.outboxStreamKey(); + if (checkpoint.outboxSequence() <= 0L || expectedHead == null || expectedHead.length == 0) { + throw new ProjectionUnavailableException(); + } + long cursor = 0L; + AccountSelectedGameplayAuthorityProjection prior = null; + AccountAuthorityOutboxRepository.Event last = null; + if (redisHead != null) { + long redisSequence; + try { + var decoded = + AccountSelectedGameplayAuthorityProjection.decode( + redisHead, tenant ? null : accountId, tenantId); + redisSequence = decoded.sequence().longValueExact(); + } catch (ArithmeticException | IllegalArgumentException invalidRedisHead) { + throw new ProjectionUnavailableException(); + } + if (redisSequence > checkpoint.outboxSequence()) throw new ProjectionUnavailableException(); + AccountAuthorityOutboxRepository.Event retainedHead = + accountTransaction.execute( + status -> + selectedOwner + .outbox() + .findEvent(streamKey, redisSequence) + .orElseThrow(ProjectionUnavailableException::new)); + if (!streamKey.equals(retainedHead.outboxStreamKey()) + || retainedHead.outboxSequence() != redisSequence) { + throw new ProjectionUnavailableException(); + } + AccountSelectedGameplayAuthorityProjection retainedProjection = + tenant + ? tenantProjection(retainedHead, tenantId) + : membershipProjection(retainedHead, accountId, tenantId); + if (!Arrays.equals(redisHead, retainedProjection.canonicalBytes())) { + throw new ProjectionUnavailableException(); + } + // A retained immutable event proves the cached prefix through this exact sequence. Resume + // after it instead of rereading the already-published prefix on every retry. + cursor = redisSequence; + prior = retainedProjection; + last = retainedHead; + } + boolean exactRetry = true; + while (cursor < checkpoint.outboxSequence()) { + long afterSequence = cursor; + List page = + accountTransaction.execute( + status -> + selectedOwner + .outbox() + .findEventPage(streamKey, afterSequence, checkpoint.outboxSequence())); + if (page == null + || page.isEmpty() + || page.size() > AccountAuthorityOutboxRepository.MAX_EVENT_HISTORY_PAGE_SIZE) { + throw new ProjectionUnavailableException(); + } + List projections = + new java.util.ArrayList<>(page.size()); + long pageCursor = cursor; + AccountSelectedGameplayAuthorityProjection pagePrior = prior; + for (AccountAuthorityOutboxRepository.Event event : page) { + long expectedSequence; + try { + expectedSequence = Math.addExact(pageCursor, 1L); + } catch (ArithmeticException overflow) { + throw new ProjectionUnavailableException(); + } + if (!streamKey.equals(event.outboxStreamKey()) + || event.outboxSequence() != expectedSequence + || event.outboxSequence() > checkpoint.outboxSequence()) { + throw new ProjectionUnavailableException(); + } + AccountSelectedGameplayAuthorityProjection projection = + tenant + ? tenantProjection(event, tenantId) + : membershipProjection(event, accountId, tenantId); + try { + projection.requireSuccessorOf(pagePrior); + } catch (IllegalArgumentException invalidHistory) { + throw new ProjectionUnavailableException(); + } + projections.add(projection); + pagePrior = projection; + pageCursor = event.outboxSequence(); + last = event; + } + var outcome = + coordinationRedis.publishSelectedAuthorityEventPage( + accountId, + tenantId, + tenant, + prior == null ? null : prior.canonicalBytes(), + projections.stream() + .map(AccountSelectedGameplayAuthorityProjection::canonicalBytes) + .toList()); + exactRetry &= + outcome == AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY; + prior = pagePrior; + cursor = pageCursor; + } + if (last == null + || last.outboxSequence() != checkpoint.outboxSequence() + || !last.eventId().equals(checkpoint.sourceEventId()) + || !last.eventDigest().equals(checkpoint.sourceEventDigest()) + || prior == null + || !Arrays.equals(prior.canonicalBytes(), expectedHead)) { + throw new ProjectionUnavailableException(); + } + return exactRetry; + } + + private static AccountSelectedGameplayAuthorityProjection membershipProjection( + AccountAuthorityOutboxRepository.Event row, UUID accountId, UUID tenantId) { + try { + var event = + MembershipAuthorityEventV1Codec.verify( + StandardCharsets.UTF_8 + .newDecoder() + .decode(ByteBuffer.wrap(row.payload())) + .toString()); + if (!row.requestId().equals(event.requestId()) + || !row.eventId().equals(event.eventId()) + || !row.eventDigest().equals(event.eventDigest()) + || !row.outboxStreamKey().equals(event.outboxStreamKey()) + || !Long.toString(row.outboxSequence()).equals(event.outboxSequence()) + || !accountId.toString().equals(event.accountId()) + || !tenantId.toString().equals(event.tenantId()) + || !Arrays.equals(row.payload(), event.canonicalJsonUtf8())) { + throw new ProjectionUnavailableException(); + } + return AccountSelectedGameplayAuthorityProjection.membership(event); + } catch (java.nio.charset.CharacterCodingException | IllegalArgumentException malformed) { + throw new ProjectionUnavailableException(); + } + } + + private static AccountSelectedGameplayAuthorityProjection tenantProjection( + AccountAuthorityOutboxRepository.Event row, UUID tenantId) { + try { + var event = TenantAuthorityEventV1Codec.verify(row.payload()); + if (!row.requestId().equals(event.requestId().toString()) + || !row.eventId().equals(event.eventId().toString()) + || !row.eventDigest().equals(event.eventDigest()) + || !row.outboxStreamKey().equals(event.outboxStreamKey()) + || row.outboxSequence() != event.outboxSequence() + || !tenantId.equals(event.tenantId()) + || !Arrays.equals(row.payload(), event.payload())) { + throw new ProjectionUnavailableException(); + } + return AccountSelectedGameplayAuthorityProjection.tenant(event); + } catch (IllegalArgumentException malformed) { + throw new ProjectionUnavailableException(); + } + } + + private static void requireSameSelectedSnapshot(SelectedSnapshot before, SelectedSnapshot after) { + if (!before.source().equals(after.source()) + || !before.composite().equals(after.composite()) + || !before.pair().equals(after.pair()) + || !before.membershipEvent().equals(after.membershipEvent()) + || !before.tenantEvent().equals(after.tenantEvent()) + || !before.tenantCheckpoint().equals(after.tenantCheckpoint()) + || !before.membershipCheckpoint().equals(after.membershipCheckpoint()) + || !Arrays.equals(before.currentTuple(), after.currentTuple()) + || !Arrays.deepEquals(before.values(), after.values())) + throw new StaleProjectionException(); + } + + private static void requireOutsideOwnerTransaction() { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) { + throw new ProjectionUnavailableException(); + } + } + + private record SelectedOwner( + AccountAuthorityGenerationRepository generations, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountAuthorityOutboxRepository outbox, + AccountTenantAuthorityEventRepository tenantSources) {} + + private record SelectedSnapshot( + IssuerAccountSourceSnapshot source, + AccountAuthorityGenerationRepository.CompositeSnapshot composite, + AccountMembershipPairAuthorityRepository.PairAuthority pair, + String membershipEvent, + String tenantEvent, + byte[] currentTuple, + byte[][] values, + AccountAuthorityOutboxRepository.Checkpoint tenantCheckpoint, + AccountAuthorityOutboxRepository.Checkpoint membershipCheckpoint) {} + + /** Owner-generated informational evidence. It cannot be fabricated as a positive caller proof. */ + public static final class SelectedProjectionObservation { + private final SelectedSnapshot snapshot; + private final AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome + publicationOutcome; + + private SelectedProjectionObservation( + SelectedSnapshot snapshot, + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome publicationOutcome) { + this.snapshot = snapshot; + this.publicationOutcome = publicationOutcome; + } + + public boolean admitting() { + return false; + } + + public long membershipVersion() { + return snapshot.pair().membershipVersion(); + } + + public long membershipAuthorityGeneration() { + return snapshot.pair().membershipAuthorityGeneration(); + } + + public byte[] canonicalCurrentAuthorityTuple() { + return snapshot.currentTuple().clone(); + } + + public Map currentAuthorityTuple() { + try { + return JSON.readValue(snapshot.currentTuple(), new TypeReference<>() {}); + } catch (RuntimeException unavailable) { + throw new ProjectionUnavailableException(); + } + } + + public long issuanceFence() { + return snapshot.composite().issuanceFence().value(); + } + + public void requireExactOwnerSnapshot( + IssuerAccountSourceSnapshot source, + AccountAuthorityGenerationRepository.CompositeSnapshot authority, + AccountMembershipPairAuthorityRepository.PairAuthority pair, + MembershipAuthorityEventV1Codec.MembershipEvent membership, + net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event tenant) { + if (!snapshot.source().equals(source) + || !snapshot.composite().equals(authority) + || !snapshot.pair().equals(pair) + || !snapshot.membershipEvent().equals(membership.canonicalJson()) + || !snapshot.tenantEvent().equals(new String(tenant.payload(), StandardCharsets.UTF_8))) + throw new StaleProjectionException(); + } + + public void requireSameSnapshot(SelectedProjectionObservation current) { + if (current == null) throw new StaleProjectionException(); + requireSameSelectedSnapshot(snapshot, current.snapshot); + } + + public Map projectionDigests() { + return Map.of( + "issuer", + sha256(snapshot.values()[0]), + "account", + sha256(snapshot.values()[1]), + "tenant", + sha256(snapshot.values()[2]), + "membership", + sha256(snapshot.values()[3])); + } + + public byte[][] canonicalProjections() { + return Arrays.stream(snapshot.values()).map(byte[]::clone).toArray(byte[][]::new); + } + + public AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome publicationOutcome() { + return publicationOutcome; + } + } + + /** + * Publishes the exact latest locked issuer/Account source heads. This method does not activate a + * token or establish freshness authority; a missing/ambiguous Redis acknowledgement fails. + */ + public PublicationObservation publishCurrent(UUID accountId) { + requireAccountId(accountId); + IssuerAccountSourceSnapshot source = readOwnerSnapshot(accountId); + byte[][] values = canonicalProjectionPair(source); + ProjectionValue issuer = + ProjectionValue.decode(values[0], "issuer", GameSessionAccountDelegationProfile.ISSUER); + ProjectionValue account = ProjectionValue.decode(values[1], "account", accountId.toString()); + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome outcome = + coordinationRedis.publishAuthorityProjections(accountId, values[0], values[1]); + IssuerAccountSourceSnapshot after = readOwnerSnapshot(accountId); + if (!source.equals(after) || !Arrays.deepEquals(values, canonicalProjectionPair(after))) { + throw new StaleProjectionException(); + } + return new PublicationObservation( + issuer.digest(), + account.digest(), + source.issuer().generation(), + source.account().generation(), + outcome); + } + + /** + * Observes a Redis projection only when both values equal two consecutive exact Account + * owner-source reads. This is informational, remains non-authorizing, and defines no elapsed-time + * freshness policy or subsequent-use race guarantee. + */ + public ProjectionObservation observeCurrent(UUID accountId) { + requireAccountId(accountId); + IssuerAccountSourceSnapshot before = readOwnerSnapshot(accountId); + byte[][] raw = coordinationRedis.readAuthorityProjections(accountId); + IssuerAccountSourceSnapshot after = readOwnerSnapshot(accountId); + if (!before.equals(after)) throw new StaleProjectionException(); + + ProjectionValue issuer = + ProjectionValue.decode(raw[0], "issuer", GameSessionAccountDelegationProfile.ISSUER); + ProjectionValue account = ProjectionValue.decode(raw[1], "account", accountId.toString()); + byte[][] expected = canonicalProjectionPair(after); + if (!Arrays.equals(issuer.canonicalBytes(), expected[0]) + || !Arrays.equals(account.canonicalBytes(), expected[1])) { + throw new StaleProjectionException(); + } + return new ProjectionObservation( + issuer.digest(), account.digest(), issuer.generation(), account.generation()); + } + + private IssuerAccountSourceSnapshot readOwnerSnapshot(UUID accountId) { + IssuerAccountSourceSnapshot snapshot = + accountTransaction.execute( + status -> + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId)); + if (snapshot == null + || !GameSessionAccountDelegationProfile.ISSUER.equals(snapshot.issuer().scope().issuerId()) + || !accountId.equals(snapshot.account().scope().accountId())) { + throw new ProjectionUnavailableException(); + } + return snapshot; + } + + private static void requireAccountId(UUID accountId) { + Objects.requireNonNull(accountId, "Canonical Account UUID is required"); + if (accountId.equals(new UUID(0L, 0L)) + || accountId.version() != 4 + || accountId.variant() != 2) { + throw new IllegalArgumentException("Canonical high-entropy Account UUID is required"); + } + } /** Encodes exact source DTOs for the two projection keys; these bytes are not authority proof. */ public static byte[][] canonicalProjectionPair(IssuerAccountSourceSnapshot source) { @@ -80,7 +735,6 @@ public static byte[][] canonicalProjectionPair(IssuerAccountSourceSnapshot sourc return new byte[][] {issuer.canonicalBytes(), account.canonicalBytes()}; } - /** Strict canonical non-authorizing value stored at one canonical authority key. */ public static final class ProjectionValue { private static final String ISSUER = "issuer"; private static final String ACCOUNT = "account"; @@ -164,12 +818,74 @@ public String toString() { } } + public record PublicationObservation( + String issuerDigest, + String accountDigest, + long issuerGeneration, + long accountGeneration, + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome redisOutcome) { + public PublicationObservation { + requireDigest(issuerDigest); + requireDigest(accountDigest); + if (issuerGeneration <= 0L || accountGeneration <= 0L) { + throw new IllegalArgumentException("Projected generations must be positive"); + } + Objects.requireNonNull(redisOutcome); + } + + @Override + public String toString() { + return "AccountAuthorityProjectionPublication[redacted]"; + } + } + + public record ProjectionObservation( + String issuerDigest, String accountDigest, long issuerGeneration, long accountGeneration) { + public ProjectionObservation { + requireDigest(issuerDigest); + requireDigest(accountDigest); + if (issuerGeneration <= 0L || accountGeneration <= 0L) { + throw new IllegalArgumentException("Observed generations must be positive"); + } + } + + @Override + public String toString() { + return "AccountAuthorityProjectionObservation[non-authorizing]"; + } + } + public static final class ProjectionUnavailableException extends IllegalStateException { public ProjectionUnavailableException() { super("Account authority projection is unavailable or inconsistent"); } } + public static final class StaleProjectionException extends IllegalStateException { + public StaleProjectionException() { + super("Account authority projection is stale or changed during observation"); + } + } + + private static void requireDigest(String digest) { + if (digest == null || !SHA256.matcher(digest).matches()) { + throw new IllegalArgumentException("Projection digest is malformed"); + } + } + + private static byte[] canonical(Object value) { + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (bytes.length == 0 || bytes.length > MAX_PROJECTION_BYTES) { + throw new ProjectionUnavailableException(); + } + return bytes; + } catch (IOException | RuntimeException ex) { + if (ex instanceof ProjectionUnavailableException unavailable) throw unavailable; + throw new ProjectionUnavailableException(); + } + } + private static String sha256(byte[] bytes) { try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java new file mode 100644 index 0000000000..434acd7214 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java @@ -0,0 +1,456 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired Account owner for the separate COMMITTED-to-ACTIVE initial LOGIN stage. + * + *

The activation operation surrounds one pinned Redis CAS/readback with independent fresh + * Account/source/envelope and current signer-owner transactions. Its returned metadata is not a + * credential, player-admission decision, response-recovery proof, or globally atomic cross-store + * snapshot. Recovery and caller currentness may use an older committed signing generation only when + * its exact original public-key fingerprint remains in the current trusted JWKS; current + * signer/trust and the exact original committed issuance are reread around recovery activation. + */ +public final class AccountGameplayDelegationCommittedIssuanceOwner { + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final AccountGameplayDelegationSigner signer; + private final AccountGameplayDelegationTokenRegistry tokenRegistry; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + public AccountGameplayDelegationCommittedIssuanceOwner( + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + PlatformTransactionManager transactionManager, + Clock clock) { + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account issuance repository is required"); + this.signer = Objects.requireNonNull(signer, "Account signer is required"); + this.tokenRegistry = + Objects.requireNonNull(tokenRegistry, "Account token registry is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** Performs one fresh informational check of an already persisted COMMITTED request. */ + public CurrentCommittedIssuanceObservation inspectCurrentCommittedIssuance(UUID requestId) { + if (requestId == null || requestId.version() != 4 || requestId.variant() != 2) { + throw unavailable(); + } + // The method owns its complete bounded transaction; it must never inherit unknown caller work. + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + CheckedObservation current = readCurrentOwnerEvidence(requestId); + if (current == null) throw unavailable(); + long observedAt = clock.millis(); + if (current.checkedAtMillis() <= 0L + || Math.floorDiv(current.checkedAtMillis(), 1_000L) + >= current.evidence().identity().expiresAtEpochSecond() + || observedAt <= 0L + || Math.floorDiv(observedAt, 1_000L) + >= current.evidence().identity().expiresAtEpochSecond()) { + throw unavailable(); + } + return new CurrentCommittedIssuanceObservation(current.evidence(), current.checkedAtMillis()); + } catch (OwnerUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + // Storage, signer, parsing, and protected-owner details are deliberately not surfaced. + throw unavailable(); + } + } + + /** + * Resolves an untrusted verified-token JTI to the current committed Account issuance and then + * requires the exact ACTIVE Redis projection after releasing every SQL lock. This is a read-only + * caller-currentness check; it never activates, repairs, or extends the registry record. + */ + public CommittedCandidateVerificationData requireCurrentActiveCommittedCandidateByJti( + UUID tokenJti) { + if (tokenJti == null || tokenJti.version() != 4 || tokenJti.variant() != 2) { + throw unavailable(); + } + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + CommittedCandidateVerificationData evidence = + accountTransaction.execute( + status -> { + CommittedCandidateVerificationData current = + issuanceRepository + .readCurrentCommittedCandidateByJti(tokenJti) + .orElseThrow(AccountGameplayDelegationCommittedIssuanceOwner::unavailable); + signer.requireCurrentCommittedRecoverySigner(current); + return current; + }); + if (evidence == null + || !tokenJti.equals(evidence.identity().tokenJti()) + || Math.floorDiv(clock.millis(), 1_000L) >= evidence.identity().expiresAtEpochSecond()) { + throw unavailable(); + } + signer.requireRetainedCommittedPublicKey(evidence); + tokenRegistry.requireExactActiveRecord(evidence); + if (Math.floorDiv(clock.millis(), 1_000L) >= evidence.identity().expiresAtEpochSecond()) { + throw unavailable(); + } + return evidence; + } catch (OwnerUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + /** + * Advances one exact committed issuance to ACTIVE, then independently rereads the Account owner + * evidence. This is a separate Redis/SQL transition, not a global cross-store transaction or a + * credential-return authorization; Authenticate and response recovery remain unwired. + */ + public ActiveCommittedIssuanceObservation activateCommittedIssuance(UUID requestId) { + requireRequestId(requestId); + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + CheckedObservation before = readCurrentRecoveryOwnerEvidence(requestId); + if (before == null) throw unavailable(); + requireUnexpired(before, clock.millis()); + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt active = + tokenRegistry.activateCommittedCandidate(before.evidence()); + requireExactActiveReceipt(active, before.evidence()); + + CheckedObservation after = readCurrentRecoveryOwnerEvidence(requestId); + if (after == null || !sameCommittedOwnerEvidence(before.evidence(), after.evidence())) { + throw unavailable(); + } + long observedAt = clock.millis(); + requireUnexpired(before, observedAt); + requireUnexpired(after, observedAt); + if (active.absoluteExpiryMillis() != after.evidence().registryAbsoluteExpiryMillis()) { + throw unavailable(); + } + return new ActiveCommittedIssuanceObservation(active, observedAt); + } catch (OwnerUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private CheckedObservation readCurrentOwnerEvidence(UUID requestId) { + return accountTransaction.execute( + status -> { + CommittedCandidateVerificationData evidence = + issuanceRepository.readCurrentCommittedCandidate(requestId); + signer.requireCurrentCommittedSigner(evidence); + return new CheckedObservation(evidence, clock.millis()); + }); + } + + /** + * Reads current Account signer/trust and the immutable issuance inside SQL, then checks the + * historical key against the trusted live JWKS only after the SQL transaction has ended. + */ + private CheckedObservation readCurrentRecoveryOwnerEvidence(UUID requestId) { + CheckedObservation checked = + accountTransaction.execute( + status -> { + CommittedCandidateVerificationData evidence = + issuanceRepository.readCurrentCommittedCandidate(requestId); + signer.requireCurrentCommittedRecoverySigner(evidence); + return new CheckedObservation(evidence, clock.millis()); + }); + if (checked == null) return null; + signer.requireRetainedCommittedPublicKey(checked.evidence()); + return checked; + } + + private void requireUnexpired(CheckedObservation checked, long observedAtMillis) { + long expiry = checked.evidence().identity().expiresAtEpochSecond(); + if (checked.checkedAtMillis() <= 0L + || Math.floorDiv(checked.checkedAtMillis(), 1_000L) >= expiry + || observedAtMillis <= 0L + || Math.floorDiv(observedAtMillis, 1_000L) >= expiry) { + throw unavailable(); + } + } + + private static void requireRequestId(UUID requestId) { + if (requestId == null || requestId.version() != 4 || requestId.variant() != 2) { + throw unavailable(); + } + } + + private static void requireExactActiveReceipt( + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt receipt, + CommittedCandidateVerificationData evidence) { + var identity = evidence.identity(); + if (receipt == null + || !receipt + .tokenKey() + .equals(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + evidence.tokenSha256()) + || !receipt.tokenHash().equals(evidence.tokenSha256()) + || !receipt.operationId().equals(identity.operationId().toString()) + || !receipt.requestId().equals(identity.requestId().toString()) + || !receipt.accountId().equals(identity.accountId().toString()) + || !receipt.commitProofSha256().equals(evidence.commitProofSha256()) + || receipt.registryVersion() != 2L + || receipt.absoluteExpiryMillis() != evidence.registryAbsoluteExpiryMillis() + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L) { + throw unavailable(); + } + } + + private static boolean sameCommittedOwnerEvidence( + CommittedCandidateVerificationData left, CommittedCandidateVerificationData right) { + return left.identity().equals(right.identity()) + && left.authoritySnapshot().equals(right.authoritySnapshot()) + && left.evidenceBundleReference().equals(right.evidenceBundleReference()) + && left.tokenSha256().equals(right.tokenSha256()) + && left.signerKid().equals(right.signerKid()) + && left.signerGeneration().equals(right.signerGeneration()) + && left.canonicalRegistryRecordSha256().equals(right.canonicalRegistryRecordSha256()) + && left.commitProofSha256().equals(right.commitProofSha256()) + && left.signerCorrespondence().equals(right.signerCorrespondence()) + && left.envelopeKeyId().equals(right.envelopeKeyId()) + && left.envelopeSha256().equals(right.envelopeSha256()) + && left.envelopeBytesLength() == right.envelopeBytesLength() + && left.responseRecoveryExpiryEpochMillis() == right.responseRecoveryExpiryEpochMillis() + && left.registryAbsoluteExpiryMillis() == right.registryAbsoluteExpiryMillis() + && left.registrationLocalAofCount() == right.registrationLocalAofCount() + && left.registrationReplicaAofCount() == right.registrationReplicaAofCount() + && left.registrationOutcome() == right.registrationOutcome(); + } + + private static OwnerUnavailableException unavailable() { + return new OwnerUnavailableException(); + } + + private record CheckedObservation( + CommittedCandidateVerificationData evidence, long checkedAtMillis) {} + + /** Exact active-store receipt plus before/after owner reread timestamps; never a credential. */ + public static final class ActiveCommittedIssuanceObservation { + private final UUID operationId; + private final UUID requestId; + private final UUID accountId; + private final String tokenSha256; + private final String activeRecordSha256; + private final String commitProofSha256; + private final long registryVersion; + private final long absoluteExpiryMillis; + private final AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome outcome; + private final long observedAtEpochMillis; + + private ActiveCommittedIssuanceObservation( + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt receipt, + long observedAtEpochMillis) { + this.operationId = UUID.fromString(receipt.operationId()); + this.requestId = UUID.fromString(receipt.requestId()); + this.accountId = UUID.fromString(receipt.accountId()); + this.tokenSha256 = receipt.tokenHash(); + this.activeRecordSha256 = receipt.canonicalActiveRecordSha256(); + this.commitProofSha256 = receipt.commitProofSha256(); + this.registryVersion = receipt.registryVersion(); + this.absoluteExpiryMillis = receipt.absoluteExpiryMillis(); + this.outcome = receipt.outcome(); + this.observedAtEpochMillis = observedAtEpochMillis; + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String activeRecordSha256() { + return activeRecordSha256; + } + + public String commitProofSha256() { + return commitProofSha256; + } + + public long registryVersion() { + return registryVersion; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome outcome() { + return outcome; + } + + public long observedAtEpochMillis() { + return observedAtEpochMillis; + } + + @Override + public String toString() { + return "ActiveCommittedIssuanceObservation[non-authorizing,redacted]"; + } + } + + /** Immutable informational result; no candidate, ciphertext, or proof bytes are exposed. */ + public static final class CurrentCommittedIssuanceObservation { + private final UUID operationId; + private final UUID requestId; + private final UUID accountId; + private final UUID tokenJti; + private final String requestDigest; + private final String tokenSha256; + private final String signerKid; + private final String signerGeneration; + private final String commitProofSha256; + private final AccountAuthoritySnapshot authoritySnapshot; + private final EvidenceBundleReference evidenceBundleReference; + private final String canonicalRegistryRecordSha256; + private final String envelopeKeyId; + private final String envelopeSha256; + private final int envelopeBytesLength; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final long responseRecoveryExpiryEpochMillis; + private final long observedAtEpochMillis; + + private CurrentCommittedIssuanceObservation( + CommittedCandidateVerificationData evidence, long observedAtEpochMillis) { + var identity = evidence.identity(); + this.operationId = identity.operationId(); + this.requestId = identity.requestId(); + this.accountId = identity.accountId(); + this.tokenJti = identity.tokenJti(); + this.requestDigest = identity.requestDigest(); + this.tokenSha256 = evidence.tokenSha256(); + this.signerKid = evidence.signerKid(); + this.signerGeneration = evidence.signerGeneration(); + this.commitProofSha256 = evidence.commitProofSha256(); + this.authoritySnapshot = evidence.authoritySnapshot(); + this.evidenceBundleReference = evidence.evidenceBundleReference(); + this.canonicalRegistryRecordSha256 = evidence.canonicalRegistryRecordSha256(); + this.envelopeKeyId = evidence.envelopeKeyId(); + this.envelopeSha256 = evidence.envelopeSha256(); + this.envelopeBytesLength = evidence.envelopeBytesLength(); + this.issuedAtEpochSecond = identity.issuedAtEpochSecond(); + this.notBeforeEpochSecond = identity.notBeforeEpochSecond(); + this.expiresAtEpochSecond = identity.expiresAtEpochSecond(); + this.responseRecoveryExpiryEpochMillis = evidence.responseRecoveryExpiryEpochMillis(); + this.observedAtEpochMillis = observedAtEpochMillis; + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public String requestDigest() { + return requestDigest; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String signerKid() { + return signerKid; + } + + public String signerGeneration() { + return signerGeneration; + } + + public String commitProofSha256() { + return commitProofSha256; + } + + public AccountAuthoritySnapshot authoritySnapshot() { + return authoritySnapshot; + } + + public EvidenceBundleReference evidenceBundleReference() { + return evidenceBundleReference; + } + + public String canonicalRegistryRecordSha256() { + return canonicalRegistryRecordSha256; + } + + public String envelopeKeyId() { + return envelopeKeyId; + } + + public String envelopeSha256() { + return envelopeSha256; + } + + public int envelopeBytesLength() { + return envelopeBytesLength; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public long responseRecoveryExpiryEpochMillis() { + return responseRecoveryExpiryEpochMillis; + } + + public long observedAtEpochMillis() { + return observedAtEpochMillis; + } + + @Override + public String toString() { + return "CurrentCommittedIssuanceObservation[non-authorizing,redacted]"; + } + } + + public static final class OwnerUnavailableException extends IllegalStateException { + public OwnerUnavailableException() { + super("Current committed Account gameplay delegation evidence is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java new file mode 100644 index 0000000000..e976050b4a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java @@ -0,0 +1,445 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.lang.reflect.RecordComponent; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedIssuanceReadback; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection.ProjectionObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection.PublicationObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationReceipt; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.CandidateOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.PendingCandidateVerificationProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Explicitly unwired, non-authorizing Account PENDING-to-COMMITTED orchestration boundary. + * + *

All protected signer, Coordination Redis, and source projection work finishes before the final + * Account SQL transaction begins. The final transaction rechecks the signer and owner rows, + * persists only bounded canonical non-secret evidence, and is followed by an independent exact + * COMMITTED readback. No compact JWT is returned, decrypted, or persisted here. + */ +public final class AccountGameplayDelegationIssuanceCommitService { + public static final String COMMIT_PROOF_SCHEMA = + "account-game-session-delegation-commit-proof/v1"; + public static final int MAX_COMMIT_PROOF_BYTES = 32 * 1024; + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AccountGameplayDelegationSigner signer; + private final AccountGameplayDelegationTokenRegistry tokenRegistry; + private final AccountGameplayDelegationAuthorityProjection authorityProjection; + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + public AccountGameplayDelegationIssuanceCommitService( + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + AccountGameplayDelegationAuthorityProjection authorityProjection, + AccountGameplayDelegationIssuanceRepository issuanceRepository, + PlatformTransactionManager accountTransactionManager, + Clock clock) { + this.signer = Objects.requireNonNull(signer, "Account gameplay signer is required"); + this.tokenRegistry = + Objects.requireNonNull(tokenRegistry, "Account pending registry is required"); + this.authorityProjection = + Objects.requireNonNull(authorityProjection, "Account authority projection is required"); + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account issuance repository is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull( + accountTransactionManager, "Account transaction manager is required")); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** + * Verifies and commits one already-persisted initial LOGIN issuance operation. This method is + * intentionally not connected to Authenticate, Spring runtime wiring, or a response endpoint. + */ + public CommitResult commitPendingCandidate(UUID requestId) { + requireRequestId(requestId); + // This method performs signer, Redis and source reads before its final SQL transaction. An + // ambient caller transaction could retain Account locks across those network operations, so + // refuse it instead of silently joining or suspending unknown work. + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + Optional prior = issuanceRepository.readCommittedProof(requestId); + if (prior.isPresent()) return CommitResult.exactRetry(prior.orElseThrow()); + + CandidateOutcome candidate = signer.signPendingCandidate(requestId); + if (candidate == null || candidate.verificationProof() == null) throw unavailable(); + PendingCandidateVerificationProof proof = candidate.verificationProof(); + long now = Math.floorDiv(clock.millis(), 1_000L); + if (!requestId.equals(proof.requestId()) + || now <= 0L + || proof.notBeforeEpochSecond() > now + || proof.expiresAtEpochSecond() <= now) { + throw unavailable(); + } + + PendingRegistrationReceipt registration = tokenRegistry.registerPending(requestId); + PublicationObservation publication = authorityProjection.publishCurrent(proof.accountId()); + ProjectionObservation projection = authorityProjection.observeCurrent(proof.accountId()); + if (projection == null + || !publication.issuerDigest().equals(projection.issuerDigest()) + || !publication.accountDigest().equals(projection.accountDigest()) + || publication.issuerGeneration() != projection.issuerGeneration() + || publication.accountGeneration() != projection.accountGeneration()) { + throw unavailable(); + } + CommitProof commitProof = CommitProof.create(proof, registration, projection); + + CommittedIssuanceReadback transactionReadback = + accountTransaction.execute( + status -> { + signer.requireCurrentCommittedSigner(proof); + return issuanceRepository.commitPendingCandidate( + requestId, proof, registration, projection, commitProof); + }); + if (transactionReadback == null + || !transactionReadback.proofSha256().equals(commitProof.sha256())) { + throw unavailable(); + } + + Optional durable = + issuanceRepository.readCommittedProof(requestId); + if (durable.isEmpty() || !durable.orElseThrow().equals(transactionReadback)) { + throw unavailable(); + } + return CommitResult.created(durable.orElseThrow()); + } catch (RuntimeException failure) { + if (failure instanceof IssuanceCommitUnavailableException unavailable) throw unavailable; + throw unavailable(); + } + } + + private static void requireRequestId(UUID requestId) { + Objects.requireNonNull(requestId, "Account issuance request ID is required"); + if (requestId.version() != 4 || requestId.variant() != 2) throw unavailable(); + } + + private static IssuanceCommitUnavailableException unavailable() { + return new IssuanceCommitUnavailableException(); + } + + /** Private-constructor immutable proof assembled only from owner-produced typed evidence. */ + public static final class CommitProof { + private final UUID operationId; + private final UUID requestId; + private final UUID accountId; + private final String requestDigest; + private final String tokenSha256; + private final String sha256; + private final byte[] canonicalBytes; + + private CommitProof( + UUID operationId, + UUID requestId, + UUID accountId, + String requestDigest, + String tokenSha256, + byte[] canonicalBytes) { + this.operationId = Objects.requireNonNull(operationId); + this.requestId = Objects.requireNonNull(requestId); + this.accountId = Objects.requireNonNull(accountId); + this.requestDigest = Objects.requireNonNull(requestDigest); + this.tokenSha256 = Objects.requireNonNull(tokenSha256); + this.canonicalBytes = canonicalBytes.clone(); + if (this.canonicalBytes.length == 0 || this.canonicalBytes.length > MAX_COMMIT_PROOF_BYTES) { + throw unavailable(); + } + this.sha256 = AccountGameplayDelegationIssuanceCommitService.sha256(this.canonicalBytes); + } + + private static CommitProof create( + PendingCandidateVerificationProof proof, + PendingRegistrationReceipt registration, + ProjectionObservation projection) { + Objects.requireNonNull(proof, "Signer-owned pending verification proof is required"); + Objects.requireNonNull(registration, "Pinned Redis registration receipt is required"); + Objects.requireNonNull(projection, "Current Account authority projection is required"); + var identity = proof.identity(); + AccountAuthoritySnapshot snapshot = proof.authoritySnapshot(); + EvidenceBundleReference bundleReference = proof.evidenceBundleReference(); + if (!identity.operationId().toString().equals(registration.operationId()) + || !identity.requestId().toString().equals(registration.requestId()) + || !identity.accountId().toString().equals(registration.accountId()) + || !identity.requestDigest().equals(registration.requestDigest()) + || !identity.tokenJti().toString().equals(registration.tokenJti()) + || !proof.tokenSha256().equals(registration.tokenHash()) + || !proof.signerKid().equals(registration.kid()) + || !proof.signerGeneration().equals(registration.signerGeneration()) + || proof.issuanceFence() != registration.issuanceFence() + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals( + registration.aclIdentity()) + || !bundleReference.equals(registration.evidenceBundleReference()) + || !proof.canonicalRegistryRecordSha256().equals(registration.canonicalRecordSha256()) + || projection.issuerGeneration() != snapshot.issuerGeneration() + || projection.accountGeneration() != snapshot.accountGeneration() + || registration.registryVersion() != 1L + || registration.localAofCount() < 1L + || registration.replicaAofCount() < 1L) { + throw unavailable(); + } + + Map root = new LinkedHashMap<>(); + root.put("schema", COMMIT_PROOF_SCHEMA); + root.put( + "identity", + Map.ofEntries( + Map.entry("operationId", identity.operationId().toString()), + Map.entry("requestId", identity.requestId().toString()), + Map.entry("accountId", identity.accountId().toString()), + Map.entry("requestDigest", identity.requestDigest()), + Map.entry("callerWorkload", identity.callerWorkload()), + Map.entry("callerContextId", identity.callerContextId().toString()), + Map.entry("tokenJti", identity.tokenJti().toString()), + Map.entry("tokenGeneration", "1"), + Map.entry("issuedAtEpochSecond", Long.toString(identity.issuedAtEpochSecond())), + Map.entry("notBeforeEpochSecond", Long.toString(identity.notBeforeEpochSecond())), + Map.entry("expiresAtEpochSecond", Long.toString(identity.expiresAtEpochSecond())), + Map.entry("tokenSha256", proof.tokenSha256()))); + root.put("tokenSha256", proof.tokenSha256()); + root.put("registryRecordSha256", proof.canonicalRegistryRecordSha256()); + root.put( + "registry", + Map.ofEntries( + Map.entry("state", "pending"), + Map.entry("registryVersion", Long.toString(registration.registryVersion())), + Map.entry("tokenKey", registration.tokenKey()), + Map.entry("tokenHash", registration.tokenHash()), + Map.entry("kid", registration.kid()), + Map.entry("signerGeneration", registration.signerGeneration()), + Map.entry("operationId", registration.operationId()), + Map.entry("requestId", registration.requestId()), + Map.entry("requestDigest", registration.requestDigest()), + Map.entry("absoluteExpiryMillis", Long.toString(registration.absoluteExpiryMillis())), + Map.entry("localAofCount", Long.toString(registration.localAofCount())), + Map.entry("replicaAofCount", Long.toString(registration.replicaAofCount())), + Map.entry("outcome", registration.outcome().name()), + Map.entry("canonicalRecordSha256", registration.canonicalRecordSha256()), + Map.entry( + "evidenceBundleSha256", registration.evidenceBundleReference().canonicalSha256()), + Map.entry("aclIdentity", registration.aclIdentity()))); + root.put("bundle", bundleReference.toMap()); + + root.put( + "authority", + Map.ofEntries( + Map.entry("issuerGeneration", Long.toString(snapshot.issuerGeneration())), + Map.entry("issuerSourceVersion", Long.toString(snapshot.issuerSourceVersion())), + Map.entry("accountGeneration", Long.toString(snapshot.accountGeneration())), + Map.entry("accountSourceVersion", Long.toString(snapshot.accountSourceVersion())), + Map.entry("issuanceFence", Long.toString(snapshot.issuanceFence())), + Map.entry( + "issuanceFenceSourceVersion", + Long.toString(snapshot.issuanceFenceSourceVersion())), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + snapshot.issuerGeneration(), + snapshot.accountGeneration(), + snapshot.accountSecurityCutoff())), + Map.entry("authoritySourceVersions", snapshot.sourceVersions()), + Map.entry("issuerProjectionGeneration", Long.toString(projection.issuerGeneration())), + Map.entry( + "accountProjectionGeneration", Long.toString(projection.accountGeneration())), + Map.entry("issuerProjectionSha256", projection.issuerDigest()), + Map.entry("accountProjectionSha256", projection.accountDigest()))); + + AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence correspondence = + proof.signerCorrespondence(); + Object canonicalCorrespondence = canonicalValue(correspondence, 0); + byte[] correspondenceBytes = canonicalJson(canonicalCorrespondence); + root.put( + "signer", + Map.of( + "promotionStatus", + correspondence.promotionStatus(), + "promotionOperationId", + correspondence.promotionOperationId().toString(), + "generationOperationId", + correspondence.generationOperationId().toString(), + "targetKid", + proof.signerKid(), + "targetGeneration", + proof.signerGeneration(), + "correspondenceSha256", + AccountGameplayDelegationIssuanceCommitService.sha256(correspondenceBytes), + "correspondence", + canonicalCorrespondence)); + + var sealed = proof.sealedCandidate(); + root.put( + "envelope", + Map.of( + "operationId", + sealed.operationId().toString(), + "requestId", + sealed.requestId().toString(), + "tokenHash", + proof.tokenSha256(), + "kid", + proof.signerKid(), + "signerGeneration", + proof.signerGeneration(), + "authorityEvidenceBundleSha256", + sealed.authorityEvidenceBundleSha256(), + "issuanceFence", + Long.toString(sealed.issuanceFence()), + "responseRecoveryExpiryEpochMillis", + Long.toString(sealed.responseRecoveryExpiryEpochMillis()), + "envelopeSha256", + sealed.envelopeSha256(), + "envelopeBytesLength", + Integer.toString(sealed.envelopeBytesLength()))); + + byte[] canonicalBytes = canonicalJson(root); + return new CommitProof( + identity.operationId(), + identity.requestId(), + identity.accountId(), + identity.requestDigest(), + proof.tokenSha256(), + canonicalBytes); + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public String requestDigest() { + return requestDigest; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String sha256() { + return sha256; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public String toString() { + return "AccountGameplayDelegationCommitProof[redacted]"; + } + } + + /** The result exposes only immutable operation identity and proof digest; never a JWT. */ + public record CommitResult( + UUID operationId, UUID requestId, UUID accountId, String proofSha256, Outcome outcome) { + public CommitResult { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(proofSha256); + Objects.requireNonNull(outcome); + } + + private static CommitResult created(CommittedIssuanceReadback readback) { + return result(readback, Outcome.COMMITTED); + } + + private static CommitResult exactRetry(CommittedIssuanceReadback readback) { + return result(readback, Outcome.EXACT_RETRY); + } + + private static CommitResult result(CommittedIssuanceReadback readback, Outcome outcome) { + return new CommitResult( + readback.operationId(), + readback.requestId(), + readback.accountId(), + readback.proofSha256(), + outcome); + } + + @Override + public String toString() { + return "AccountGameplayDelegationCommitResult[non-authorizing]"; + } + } + + public enum Outcome { + COMMITTED, + EXACT_RETRY + } + + public static final class IssuanceCommitUnavailableException extends IllegalStateException { + public IssuanceCommitUnavailableException() { + super("Account gameplay delegation commit is unavailable or ambiguous"); + } + } + + private static Object canonicalValue(Object value, int depth) { + if (depth > 8) throw unavailable(); + if (value == null) return null; + if (value instanceof Optional optional) + return canonicalValue(optional.orElse(null), depth + 1); + if (value instanceof UUID uuid) return uuid.toString(); + if (value instanceof Enum enumValue) return enumValue.name(); + if (value instanceof String || value instanceof Boolean || value instanceof Number) + return value; + if (!value.getClass().isRecord()) throw unavailable(); + RecordComponent[] components = value.getClass().getRecordComponents(); + if (components.length == 0 || components.length > 64) throw unavailable(); + Map fields = new LinkedHashMap<>(); + try { + for (RecordComponent component : components) { + fields.put( + component.getName(), canonicalValue(component.getAccessor().invoke(value), depth + 1)); + } + } catch (ReflectiveOperationException ex) { + throw unavailable(); + } + return fields; + } + + private static byte[] canonicalJson(Object value) { + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (bytes.length == 0 || bytes.length > MAX_COMMIT_PROOF_BYTES) throw unavailable(); + return bytes; + } catch (IOException ex) { + throw unavailable(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw unavailable(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java new file mode 100644 index 0000000000..283f633cbc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java @@ -0,0 +1,1753 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Private, pinned-connection Account Coordination client for issuance and source projections. + * + *

The caller must supply an Account-private connection provider. Every operation independently + * proves the live ACL identity with {@code ACL WHOAMI}; a caller-supplied label is not accepted. + * This class is deliberately not Spring-wired. Endpoint/TLS/ACL provisioning remains an external + * protected binding and is not established by this helper. + */ +public final class AccountGameplayDelegationRedisClient { + public static final String SCRIPT_ID = "account.game-session-delegation-pending-register.v1"; + public static final String ISSUER_PROJECTION_SCRIPT_ID = + "account.game-session-delegation-authority-project-issuer.v1"; + public static final String ACCOUNT_PROJECTION_SCRIPT_ID = + AccountGenerationProjectionRedisContract.SCRIPT_ID; + public static final String TENANT_PROJECTION_SCRIPT_ID = + "account.selected-tenant-generation-projection.v1"; + public static final String MEMBERSHIP_PROJECTION_SCRIPT_ID = + "account.selected-membership-generation-projection.v1"; + public static final String ACTIVE_TRANSITION_SCRIPT_ID = + "account.game-session-delegation-activate-committed.v1"; + private static final String AUTHORITY_PROJECTION_SCRIPT_RESOURCE = + "redis/lua/account-game-session-delegation-authority-project.lua"; + private static final String ACTIVE_TRANSITION_SCRIPT_RESOURCE = + "redis/lua/account-game-session-delegation-activate-committed.lua"; + public static final String TOKEN_KEY_PREFIX = "session:auth:token:"; + public static final String REQUIRED_ACL_IDENTITY = "account_coord_app"; + private static final int MAX_SCRIPT_SOURCE_BYTES = 32 * 1024; + private static final long MAX_CLEANUP_MARGIN_MILLIS = 300_000L; + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SHA1 = Pattern.compile("[0-9a-f]{40}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final tools.jackson.databind.json.JsonMapper JSON = + tools.jackson.databind.json.JsonMapper.builder().build(); + + private final AccountCoordinationPinnedConnectionProvider connectionProvider; + private final RedisScriptCatalog scriptCatalog; + private final AcknowledgementRequirements acknowledgementRequirements; + private final Clock clock; + private final int maxRecordBytes; + private final ClassLoader resourceClassLoader; + private volatile SelectedProjectionScript selectedProjectionScript; + + public AccountGameplayDelegationRedisClient( + AccountCoordinationPinnedConnectionProvider connectionProvider, + RedisScriptCatalog scriptCatalog, + AcknowledgementRequirements acknowledgementRequirements, + Clock clock, + int maxRecordBytes, + ClassLoader resourceClassLoader) { + this.connectionProvider = + Objects.requireNonNull( + connectionProvider, "Private Account Coordination provider is required"); + this.scriptCatalog = Objects.requireNonNull(scriptCatalog, "Redis script catalog is required"); + this.acknowledgementRequirements = + Objects.requireNonNull(acknowledgementRequirements, "WAITAOF requirements are required"); + this.clock = Objects.requireNonNull(clock, "Account gameplay delegation clock is required"); + if (maxRecordBytes <= 0 + || maxRecordBytes > GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES) { + throw new IllegalArgumentException("Registry byte bound exceeds the finite profile ceiling"); + } + this.maxRecordBytes = maxRecordBytes; + this.resourceClassLoader = + Objects.requireNonNull(resourceClassLoader, "Resource class loader is required"); + } + + /** + * Registers or reasserts the exact pending record and acknowledges its write on one physical + * connection. The absolute deadline is fixed by the Account caller and is never extended. + */ + public PendingRegistrationReceipt registerPending( + String tokenHash, byte[] canonicalRecordBytes, long absoluteExpiryMillis) { + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Account token hash is malformed"); + } + Objects.requireNonNull(canonicalRecordBytes, "Canonical pending record is required"); + if (canonicalRecordBytes.length == 0 || canonicalRecordBytes.length > maxRecordBytes) { + throw new IllegalArgumentException("Pending registry record exceeds its finite byte bound"); + } + if (absoluteExpiryMillis <= 0L) { + throw new IllegalArgumentException("Pending registry absolute expiry is malformed"); + } + byte[] recordBytes = canonicalRecordBytes.clone(); + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.decode(recordBytes, maxRecordBytes); + if (!"pending".equals(record.state()) || !tokenHash.equals(record.tokenHash())) { + throw new IllegalArgumentException("Pending registry identity does not match its key"); + } + long tokenExpiryMillis; + try { + tokenExpiryMillis = Math.multiplyExact(record.expiresAtEpochSecond(), 1000L); + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Pending token expiry cannot be represented"); + } + long cleanupMarginMillis = absoluteExpiryMillis - tokenExpiryMillis; + if (cleanupMarginMillis < 0L || cleanupMarginMillis > MAX_CLEANUP_MARGIN_MILLIS) { + throw new IllegalArgumentException("Pending registry cleanup margin is outside its bound"); + } + + RedisScriptDescriptor descriptor = requirePendingDescriptor(); + byte[] scriptSource = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(scriptSource))) { + throw unavailable(); + } + byte[] key = (TOKEN_KEY_PREFIX + tokenHash).getBytes(StandardCharsets.US_ASCII); + byte[] deadline = Long.toString(absoluteExpiryMillis).getBytes(StandardCharsets.US_ASCII); + + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + try { + if (!connection.isOpen()) throw unavailable(); + ClientOptions clientOptions = connection.getOptions(); + if (clientOptions == null || clientOptions.isAutoReconnect()) { + throw unavailable(); + } + RedisCommands commands = connection.sync(); + requireAccountAclIdentity(commands); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null || !SHA1.matcher(loadedSha).matches()) throw unavailable(); + String expectedSha = sha1(scriptSource); + if (!expectedSha.equals(loadedSha)) throw unavailable(); + + Long result = + commands.evalsha( + loadedSha, ScriptOutputType.INTEGER, new byte[][] {key}, recordBytes, deadline); + if (result == null || (result != 0L && result != 1L)) throw unavailable(); + + Acknowledgement acknowledgement = requireDurabilityAcknowledgement(commands); + + byte[] readback = commands.get(key); + Long observedExpiry = commands.pexpiretime(key); + if (!Arrays.equals(recordBytes, readback) + || observedExpiry == null + || observedExpiry.longValue() != absoluteExpiryMillis) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord verified = + GameSessionAccountDelegationRegistryRecord.decode(readback, maxRecordBytes); + if (!"pending".equals(verified.state()) || !tokenHash.equals(verified.tokenHash())) { + throw unavailable(); + } + return new PendingRegistrationReceipt( + verified, + sha256(recordBytes), + absoluteExpiryMillis, + result == 1L + ? PendingRegistrationOutcome.CREATED + : PendingRegistrationOutcome.EXACT_RETRY, + acknowledgement.localAofCount(), + acknowledgement.replicaAofCount()); + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** + * Applies the exact PENDING-to-ACTIVE Redis projection transition only when supplied the + * repository's typed, current COMMITTED-candidate readback. This helper is deliberately not wired + * to Authenticate, response recovery, or a runtime token validator. Its receipt proves only the + * observed Redis transition and the immutable owner facts supplied for this call; it does not + * establish freshness through a later response or player-admission decision. + */ + public ActiveRegistrationReceipt activateCommittedPending( + PendingRegistrationReceipt pendingReceipt, + CommittedCandidateVerificationData committedCandidate) { + Objects.requireNonNull(pendingReceipt, "Pinned pending-registration receipt is required"); + Objects.requireNonNull( + committedCandidate, "Repository-produced COMMITTED candidate evidence is required"); + requireOwnerReceiptCorrespondence(pendingReceipt, committedCandidate); + + RedisScriptDescriptor descriptor = requireActiveTransitionDescriptor(); + byte[] scriptSource = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(scriptSource))) throw unavailable(); + + byte[] key = ascii(pendingReceipt.tokenKey()); + byte[] deadline = + Long.toString(pendingReceipt.absoluteExpiryMillis()).getBytes(StandardCharsets.US_ASCII); + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null + || !SHA1.matcher(loadedSha).matches() + || !sha1(scriptSource).equals(loadedSha)) { + throw unavailable(); + } + + byte[] pendingBytes = commands.get(key); + Long observedExpiry = commands.pexpiretime(key); + if (!boundedRegistryRecord(pendingBytes) + || observedExpiry == null + || observedExpiry.longValue() != pendingReceipt.absoluteExpiryMillis()) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord observedRecord = + GameSessionAccountDelegationRegistryRecord.decode(pendingBytes, maxRecordBytes); + final GameSessionAccountDelegationRegistryRecord pendingRecord; + final byte[] exactPendingBytes; + final byte[] activeBytes; + if ("pending".equals(observedRecord.state()) && observedRecord.registryVersion() == 1L) { + pendingRecord = observedRecord; + exactPendingBytes = pendingBytes; + requirePendingMatchesOwner( + pendingRecord, exactPendingBytes, pendingReceipt, committedCandidate); + activeBytes = activeRecordBytes(pendingRecord); + } else if ("active".equals(observedRecord.state()) + && observedRecord.registryVersion() == 2L) { + activeBytes = pendingBytes; + exactPendingBytes = pendingRecordBytes(observedRecord); + pendingRecord = + GameSessionAccountDelegationRegistryRecord.decode(exactPendingBytes, maxRecordBytes); + requirePendingMatchesOwner( + pendingRecord, exactPendingBytes, pendingReceipt, committedCandidate); + if (!Arrays.equals(activeRecordBytes(pendingRecord), activeBytes)) throw unavailable(); + } else { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord expectedActive = + GameSessionAccountDelegationRegistryRecord.decode(activeBytes, maxRecordBytes); + if (!"active".equals(expectedActive.state()) + || expectedActive.registryVersion() != 2L + || !expectedActive.tokenHash().equals(committedCandidate.tokenSha256())) { + throw unavailable(); + } + + Long result = + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + exactPendingBytes, + activeBytes, + deadline); + if (result == null || (result != 0L && result != 1L)) throw unavailable(); + Acknowledgement acknowledgement = requireDurabilityAcknowledgement(commands); + + byte[] activeReadback = commands.get(key); + Long activeExpiry = commands.pexpiretime(key); + if (!Arrays.equals(activeBytes, activeReadback) + || activeExpiry == null + || activeExpiry.longValue() != pendingReceipt.absoluteExpiryMillis()) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord verifiedActive = + GameSessionAccountDelegationRegistryRecord.decode(activeReadback, maxRecordBytes); + if (!"active".equals(verifiedActive.state()) + || verifiedActive.registryVersion() != 2L + || !verifiedActive.tokenHash().equals(committedCandidate.tokenSha256())) { + throw unavailable(); + } + return new ActiveRegistrationReceipt( + verifiedActive, + sha256(activeReadback), + committedCandidate.commitProofSha256(), + pendingReceipt.absoluteExpiryMillis(), + result == 1L + ? ActiveRegistrationOutcome.ACTIVATED + : ActiveRegistrationOutcome.EXACT_RETRY, + acknowledgement.localAofCount(), + acknowledgement.replicaAofCount()); + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** + * Recovers the original exact registration receipt from repository-validated COMMITTED proof, + * then performs the same fenced pending-to-active CAS. The observed Redis deadline is compared to + * the immutable SQL proof; it is never used to manufacture or extend that deadline. + */ + ActiveRegistrationReceipt activateCommittedCandidate( + CommittedCandidateVerificationData committedCandidate) { + Objects.requireNonNull( + committedCandidate, "Repository-produced COMMITTED candidate evidence is required"); + PendingRegistrationReceipt registration = readCommittedRegistrationReceipt(committedCandidate); + return activateCommittedPending(registration, committedCandidate); + } + + private PendingRegistrationReceipt readCommittedRegistrationReceipt( + CommittedCandidateVerificationData committedCandidate) { + String tokenHash = committedCandidate.tokenSha256(); + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) throw unavailable(); + byte[] key = ascii(TOKEN_KEY_PREFIX + tokenHash); + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + try { + if (!connection.isOpen()) throw unavailable(); + ClientOptions clientOptions = connection.getOptions(); + if (clientOptions == null || clientOptions.isAutoReconnect()) throw unavailable(); + RedisCommands commands = connection.sync(); + requireAccountAclIdentity(commands); + byte[] currentBytes = commands.get(key); + Long observedExpiry = commands.pexpiretime(key); + if (!boundedRegistryRecord(currentBytes) + || observedExpiry == null + || observedExpiry.longValue() != committedCandidate.registryAbsoluteExpiryMillis()) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord currentRecord = + GameSessionAccountDelegationRegistryRecord.decode(currentBytes, maxRecordBytes); + final byte[] exactPendingBytes; + final GameSessionAccountDelegationRegistryRecord pendingRecord; + if ("pending".equals(currentRecord.state()) && currentRecord.registryVersion() == 1L) { + exactPendingBytes = currentBytes; + pendingRecord = currentRecord; + } else if ("active".equals(currentRecord.state()) && currentRecord.registryVersion() == 2L) { + exactPendingBytes = pendingRecordBytes(currentRecord); + pendingRecord = + GameSessionAccountDelegationRegistryRecord.decode(exactPendingBytes, maxRecordBytes); + } else { + throw unavailable(); + } + if (!committedCandidate.canonicalRegistryRecordSha256().equals(sha256(exactPendingBytes))) { + throw unavailable(); + } + PendingRegistrationReceipt reconstructed = + new PendingRegistrationReceipt( + pendingRecord, + committedCandidate.canonicalRegistryRecordSha256(), + committedCandidate.registryAbsoluteExpiryMillis(), + committedCandidate.registrationOutcome(), + committedCandidate.registrationLocalAofCount(), + committedCandidate.registrationReplicaAofCount()); + requireOwnerReceiptCorrespondence(reconstructed, committedCandidate); + requirePendingMatchesOwner( + pendingRecord, exactPendingBytes, reconstructed, committedCandidate); + return reconstructed; + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** + * Advances the two canonical Account authority projections on one private pinned connection. Each + * key uses a one-key script because issuer and Account keys intentionally have different Redis + * Cluster slots. No result is successful until one WAITAOF and exact byte readback of both + * projections completes on that same connection. + */ + public ProjectionPublicationOutcome publishAuthorityProjections( + java.util.UUID accountId, byte[] issuerProjectionBytes, byte[] accountProjectionBytes) { + return publishProjections(accountId, issuerProjectionBytes, accountProjectionBytes, null, null); + } + + public ProjectionPublicationOutcome publishSelectedAuthorityProjections( + java.util.UUID accountId, java.util.UUID tenantId, byte[][] values) { + if (TransactionSynchronizationManager.isActualTransactionActive() || tenantId == null) + throw unavailable(); + if (values == null || values.length != 4) throw unavailable(); + AccountSelectedGameplayAuthorityProjection.decode(values[2], null, tenantId); + AccountSelectedGameplayAuthorityProjection.decode(values[3], accountId, tenantId); + return publishProjections( + accountId, values[0], values[1], tenantId, new byte[][] {values[2], values[3]}); + } + + /** CASes exactly one retained selected-source event against its actual predecessor. */ + public ProjectionPublicationOutcome publishSelectedAuthorityEvent( + java.util.UUID accountId, + java.util.UUID tenantId, + boolean tenantProjection, + byte[] priorProjectionBytes, + byte[] candidateProjectionBytes) { + return publishSelectedAuthorityEventPage( + accountId, + tenantId, + tenantProjection, + priorProjectionBytes, + java.util.Collections.singletonList(candidateProjectionBytes)); + } + + /** + * Validates and applies one contiguous retained-event page on one pinned connection. Each event + * still executes its own predecessor CAS in order; durability and exact readback are acknowledged + * once for the page's final head. + */ + public ProjectionPublicationOutcome publishSelectedAuthorityEventPage( + java.util.UUID accountId, + java.util.UUID tenantId, + boolean tenantProjection, + byte[] priorProjectionBytes, + List candidateProjectionBytes) { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + requireCanonicalAccountUuid(accountId); + requireCanonicalAccountUuid(tenantId); + if (candidateProjectionBytes == null) throw unavailable(); + int candidateCount = candidateProjectionBytes.size(); + if (candidateCount <= 0 + || candidateCount > AccountAuthorityOutboxRepository.MAX_EVENT_HISTORY_PAGE_SIZE + || (priorProjectionBytes != null + && (priorProjectionBytes.length == 0 + || priorProjectionBytes.length + > AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES))) { + throw unavailable(); + } + final List candidates = new ArrayList<>(candidateCount); + final List decodedCandidates = + new ArrayList<>(candidateCount); + AccountSelectedGameplayAuthorityProjection prior; + byte[] priorBytes = priorProjectionBytes == null ? null : priorProjectionBytes.clone(); + try { + prior = + priorBytes == null + ? null + : AccountSelectedGameplayAuthorityProjection.decode( + priorBytes, tenantProjection ? null : accountId, tenantId); + String expectedKey = + tenantProjection + ? AccountSelectedGameplayAuthorityProjection.TENANT_PREFIX + tenantId + : AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_PREFIX + + accountId + + ":" + + tenantId; + if (prior != null && !expectedKey.equals(prior.key())) throw unavailable(); + for (int index = 0; index < candidateCount; index++) { + if (candidates.size() >= AccountAuthorityOutboxRepository.MAX_EVENT_HISTORY_PAGE_SIZE) + throw unavailable(); + byte[] suppliedCandidate = candidateProjectionBytes.get(index); + if (suppliedCandidate == null + || suppliedCandidate.length == 0 + || suppliedCandidate.length + > AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES) { + throw unavailable(); + } + byte[] candidateBytes = suppliedCandidate.clone(); + AccountSelectedGameplayAuthorityProjection candidate = + AccountSelectedGameplayAuthorityProjection.decode( + candidateBytes, tenantProjection ? null : accountId, tenantId); + if (!expectedKey.equals(candidate.key())) throw unavailable(); + boolean exactSingleRetry = + candidateCount == 1 && prior != null && Arrays.equals(candidateBytes, priorBytes); + if (prior != null + && !exactSingleRetry + && !candidate.sequence().equals(prior.sequence().add(BigInteger.ONE))) { + throw unavailable(); + } + candidate.requireSuccessorOf(prior); + candidates.add(candidateBytes); + decodedCandidates.add(candidate); + prior = candidate; + } + if (candidates.size() != candidateCount || candidateProjectionBytes.size() != candidateCount) + throw unavailable(); + } catch (RuntimeException invalidProjectionOrHistory) { + throw unavailable(); + } + SelectedProjectionScript selectedScript = selectedProjectionScript(tenantProjection); + byte[] scriptSource = selectedScript.source().clone(); + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null + || !SHA1.matcher(loadedSha).matches() + || !selectedScript.redisSha1().equals(loadedSha)) throw unavailable(); + boolean exactRetry = true; + AccountSelectedGameplayAuthorityProjection predecessor = + priorBytes == null + ? null + : AccountSelectedGameplayAuthorityProjection.decode( + priorBytes, tenantProjection ? null : accountId, tenantId); + byte[] predecessorBytes = priorBytes; + for (int index = 0; index < decodedCandidates.size(); index++) { + AccountSelectedGameplayAuthorityProjection candidate = decodedCandidates.get(index); + byte[] key = ascii(candidate.key()); + Long result = + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + ascii(predecessor == null ? "ABSENT" : "PRESENT"), + predecessorBytes == null ? new byte[0] : predecessorBytes, + candidates.get(index)); + requireProjectionResult(result); + exactRetry &= result == 0L; + predecessor = candidate; + predecessorBytes = candidates.get(index); + } + requireDurabilityAcknowledgement(commands); + AccountSelectedGameplayAuthorityProjection finalCandidate = decodedCandidates.getLast(); + byte[] finalCandidateBytes = candidates.getLast(); + byte[] key = ascii(finalCandidate.key()); + byte[] readback = commands.get(key); + if (!Arrays.equals(finalCandidateBytes, readback) + || !Long.valueOf(-1L).equals(commands.pttl(key))) throw unavailable(); + AccountSelectedGameplayAuthorityProjection.decode( + readback, tenantProjection ? null : accountId, tenantId); + return exactRetry + ? ProjectionPublicationOutcome.EXACT_RETRY + : ProjectionPublicationOutcome.PUBLISHED; + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + private ProjectionPublicationOutcome publishProjections( + java.util.UUID accountId, + byte[] issuerProjectionBytes, + byte[] accountProjectionBytes, + java.util.UUID tenantId, + byte[][] selected) { + Objects.requireNonNull(accountId, "Account UUID is required"); + AccountGameplayDelegationAuthorityProjection.ProjectionValue issuer = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + issuerProjectionBytes, "issuer", GameSessionAccountDelegationProfile.ISSUER); + AccountGameplayDelegationAuthorityProjection.ProjectionValue account = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + accountProjectionBytes, "account", accountId.toString()); + String issuerKeyName = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + issuer.scopeId(); + String accountKeyName = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + account.scopeId(); + if (!"issuer".equals(issuer.scope()) + || !GameSessionAccountDelegationProfile.ISSUER.equals(issuer.scopeId()) + || !(AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(issuerKeyName) + || !"account".equals(account.scope()) + || !accountId.toString().equals(account.scopeId()) + || !(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .equals(accountKeyName)) { + throw unavailable(); + } + byte[] issuerKey = ascii(issuerKeyName); + byte[] accountKey = ascii(accountKeyName); + + RedisScriptDescriptor issuerDescriptor = requireIssuerProjectionDescriptor(); + RedisScriptDescriptor accountDescriptor = requireCanonicalAccountProjectionDescriptor(); + byte[] scriptSource = readScriptSource(issuerDescriptor); + byte[] accountScriptSource = readScriptSource(accountDescriptor); + if (!issuerDescriptor.sha256().equals(sha256(scriptSource)) + || !accountDescriptor.sha256().equals(sha256(accountScriptSource))) { + throw unavailable(); + } + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null + || !SHA1.matcher(loadedSha).matches() + || !sha1(scriptSource).equals(loadedSha)) { + throw unavailable(); + } + byte[][] issuerProjectionArguments = {issuerProjectionBytes}; + Long issuerResult = + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {issuerKey}, + issuerProjectionArguments); + requireProjectionResult(issuerResult); + String accountSha = commands.scriptLoad(accountScriptSource); + if (accountSha == null || !sha1(accountScriptSource).equals(accountSha)) throw unavailable(); + byte[] priorAccountBytes = commands.get(accountKey); + if (priorAccountBytes != null) { + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + priorAccountBytes, "account", accountId.toString()); + AccountGenerationProjection incoming = + AccountGenerationProjection.parse( + new String(accountProjectionBytes, StandardCharsets.UTF_8)); + AccountGenerationProjection stored = + AccountGenerationProjection.parse( + new String(priorAccountBytes, StandardCharsets.UTF_8)); + if (incoming.generationValue().compareTo(stored.generationValue()) < 0 + || incoming.sourceVersionValue().compareTo(stored.sourceVersionValue()) < 0 + || incoming.outboxSequenceValue().compareTo(stored.outboxSequenceValue()) < 0 + || (incoming.outboxSequenceValue().equals(stored.outboxSequenceValue()) + && !incoming.equals(stored))) throw unavailable(); + } + boolean exactAccount = Arrays.equals(priorAccountBytes, accountProjectionBytes); + Long accountResult = + commands.evalsha( + accountSha, + ScriptOutputType.INTEGER, + new byte[][] {accountKey}, + ascii(priorAccountBytes == null ? "ABSENT" : exactAccount ? "VERIFY" : "PRESENT"), + priorAccountBytes == null ? new byte[0] : priorAccountBytes, + exactAccount ? new byte[0] : accountProjectionBytes); + requireProjectionResult(accountResult); + boolean selectedReplay = true; + if (selected != null) { + for (int index = 0; index < 2; index++) { + var value = + AccountSelectedGameplayAuthorityProjection.decode( + selected[index], index == 0 ? null : accountId, tenantId); + var descriptor = requireSelectedProjectionDescriptor(index == 0); + byte[] selectedScript = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(selectedScript))) throw unavailable(); + String selectedSha = commands.scriptLoad(selectedScript); + if (!sha1(selectedScript).equals(selectedSha)) throw unavailable(); + byte[] key = ascii(value.key()); + byte[] prior = commands.get(key); + value.requireSuccessorOf( + prior == null + ? null + : AccountSelectedGameplayAuthorityProjection.decode( + prior, index == 0 ? null : accountId, tenantId)); + boolean exact = Arrays.equals(prior, selected[index]); + Long result = + commands.evalsha( + selectedSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + ascii(prior == null ? "ABSENT" : exact ? "VERIFY" : "PRESENT"), + prior == null ? new byte[0] : prior, + exact ? new byte[0] : selected[index]); + requireProjectionResult(result); + selectedReplay &= result == 0L; + } + } + requireDurabilityAcknowledgement(commands); + byte[] issuerReadback = commands.get(issuerKey); + byte[] accountReadback = commands.get(accountKey); + if (!Arrays.equals(issuerProjectionBytes, issuerReadback) + || !Arrays.equals(accountProjectionBytes, accountReadback) + || !Long.valueOf(-1L).equals(commands.pttl(issuerKey)) + || !Long.valueOf(-1L).equals(commands.pttl(accountKey))) { + throw unavailable(); + } + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + issuerReadback, "issuer", GameSessionAccountDelegationProfile.ISSUER); + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + accountReadback, "account", accountId.toString()); + if (selected != null) { + for (int index = 0; index < 2; index++) { + var value = + AccountSelectedGameplayAuthorityProjection.decode( + selected[index], index == 0 ? null : accountId, tenantId); + if (!Arrays.equals(selected[index], commands.get(ascii(value.key()))) + || !Long.valueOf(-1L).equals(commands.pttl(ascii(value.key())))) throw unavailable(); + } + } + return issuerResult == 0L && accountResult == 0L && selectedReplay + ? ProjectionPublicationOutcome.EXACT_RETRY + : ProjectionPublicationOutcome.PUBLISHED; + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** Reads both exact canonical authority keys over one role-checked pinned connection. */ + public byte[][] readAuthorityProjections(java.util.UUID accountId) { + return readProjections(accountId, null); + } + + public byte[][] readSelectedAuthorityProjections( + java.util.UUID accountId, java.util.UUID tenantId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + Objects.requireNonNull(tenantId, "Selected tenant UUID is required"); + return readProjections(accountId, tenantId); + } + + /** + * Reads the exact current selected heads; absence is permitted only for replay from sequence 1. + */ + public byte[][] readSelectedAuthorityHeads(java.util.UUID accountId, java.util.UUID tenantId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + requireCanonicalAccountUuid(accountId); + requireCanonicalAccountUuid(tenantId); + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + byte[] tenantKey = ascii(AccountSelectedGameplayAuthorityProjection.TENANT_PREFIX + tenantId); + byte[] membershipKey = + ascii( + AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_PREFIX + + accountId + + ":" + + tenantId); + byte[] tenant = commands.get(tenantKey); + byte[] membership = commands.get(membershipKey); + validateSelectedHead(tenant, tenantKey, null, tenantId, commands); + validateSelectedHead(membership, membershipKey, accountId, tenantId, commands); + return new byte[][] {tenant, membership}; + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + private static void validateSelectedHead( + byte[] value, + byte[] key, + java.util.UUID accountId, + java.util.UUID tenantId, + RedisCommands commands) { + if (value == null) return; + if (value.length == 0 + || value.length > AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES + || !Long.valueOf(-1L).equals(commands.pttl(key))) throw unavailable(); + AccountSelectedGameplayAuthorityProjection projection = + AccountSelectedGameplayAuthorityProjection.decode(value, accountId, tenantId); + if (!Arrays.equals(ascii(projection.key()), key)) throw unavailable(); + } + + private byte[][] readProjections(java.util.UUID accountId, java.util.UUID tenantId) { + Objects.requireNonNull(accountId, "Account UUID is required"); + if (accountId.equals(new java.util.UUID(0L, 0L)) + || accountId.version() != 4 + || accountId.variant() != 2) { + throw new IllegalArgumentException("Canonical Account UUID is required"); + } + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + byte[] issuerKey = + ascii( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER); + byte[] accountKey = + ascii(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId); + byte[] issuer = commands.get(issuerKey); + byte[] account = commands.get(accountKey); + if (!boundedProjection(issuer) + || !boundedProjection(account) + || !Long.valueOf(-1L).equals(commands.pttl(issuerKey)) + || !Long.valueOf(-1L).equals(commands.pttl(accountKey))) { + throw unavailable(); + } + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + issuer, "issuer", GameSessionAccountDelegationProfile.ISSUER); + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + account, "account", accountId.toString()); + if (tenantId != null) { + byte[] tenantKey = + ascii(AccountSelectedGameplayAuthorityProjection.TENANT_PREFIX + tenantId); + byte[] membershipKey = + ascii( + AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_PREFIX + + accountId + + ":" + + tenantId); + byte[] tenant = commands.get(tenantKey); + byte[] membership = commands.get(membershipKey); + AccountSelectedGameplayAuthorityProjection.decode(tenant, null, tenantId); + AccountSelectedGameplayAuthorityProjection.decode(membership, accountId, tenantId); + if (!Long.valueOf(-1L).equals(commands.pttl(tenantKey)) + || !Long.valueOf(-1L).equals(commands.pttl(membershipKey))) throw unavailable(); + return new byte[][] {issuer.clone(), account.clone(), tenant.clone(), membership.clone()}; + } + return new byte[][] {issuer.clone(), account.clone()}; + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** Pure exact PENDING observation; no script, WAITAOF, registration, activation or renewal. */ + public void requirePendingRecord(String tokenHash, byte[] expected, long expectedAbsoluteExpiry) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || tokenHash == null + || !TOKEN_HASH.matcher(tokenHash).matches() + || !boundedRegistryRecord(expected) + || expectedAbsoluteExpiry <= clock.millis()) throw unavailable(); + try (var connection = connectionProvider.openPinnedConnection()) { + if (connection == null) throw unavailable(); + var commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + byte[] key = ascii(TOKEN_KEY_PREFIX + tokenHash); + if (!"string".equals(commands.type(key))) throw unavailable(); + byte[] actual = commands.get(key); + Long ttl = commands.pttl(key); + if (!Arrays.equals(actual, expected) + || !Long.valueOf(expectedAbsoluteExpiry).equals(commands.pexpiretime(key)) + || ttl == null + || ttl <= 0) throw unavailable(); + var record = GameSessionAccountDelegationRegistryRecord.decode(actual, maxRecordBytes); + if (!"pending".equals(record.state()) + || !tokenHash.equals(record.tokenHash()) + || record.expiresAtEpochSecond() <= clock.instant().getEpochSecond() + || !Arrays.equals(actual, commands.get(key)) + || !Long.valueOf(expectedAbsoluteExpiry).equals(commands.pexpiretime(key))) + throw unavailable(); + } catch (RuntimeException rejected) { + throw unavailable(); + } + } + + /** + * Reads one ACTIVE token record through Account's pinned, role-checked coordination connection. + * The returned value is deliberately metadata-only; callers must still compare it with the + * current committed Account issuance and verify the JWT signature/profile independently. + */ + public ActiveRegistryReadback readActiveRecord(String tokenHash) { + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Account token hash is malformed"); + } + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable(); + } + + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + byte[] activeBytes = null; + byte[] pendingBytes = null; + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + byte[] key = ascii(TOKEN_KEY_PREFIX + tokenHash); + activeBytes = commands.get(key); + Long absoluteExpiryMillis = commands.pexpiretime(key); + if (!boundedRegistryRecord(activeBytes) + || absoluteExpiryMillis == null + || absoluteExpiryMillis <= 0L) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord active = + GameSessionAccountDelegationRegistryRecord.decode(activeBytes, maxRecordBytes); + if (!"active".equals(active.state()) + || active.registryVersion() != 2L + || !tokenHash.equals(active.tokenHash())) { + throw unavailable(); + } + pendingBytes = pendingRecordBytes(active); + return new ActiveRegistryReadback( + active.tokenHash(), + active.accountId(), + active.jti(), + active.expiresAtEpochSecond(), + absoluteExpiryMillis, + sha256(pendingBytes)); + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + if (activeBytes != null) Arrays.fill(activeBytes, (byte) 0); + if (pendingBytes != null) Arrays.fill(pendingBytes, (byte) 0); + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + private RedisScriptDescriptor requirePendingDescriptor() { + RedisScriptDescriptor descriptor = scriptCatalog.require(SCRIPT_ID); + if (!SCRIPT_ID.equals(descriptor.scriptId()) + || !"account-service".equals(descriptor.owner()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != ScriptCategory.SESSION_CAS + || !"redis/lua/account-game-session-delegation-pending-register.lua" + .equals(descriptor.resourcePath()) + || !REQUIRED_ACL_IDENTITY.equals(descriptor.principal()) + || !canonicalSharedDescriptorMetadata(descriptor) + || descriptor.keys().size() != 1 + || !"tokenRecord".equals(descriptor.keys().getFirst().name()) + || !TOKEN_KEY_PREFIX.equals(descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || !argumentNames(descriptor) + .equals(List.of("canonicalPendingRecordUtf8", "absoluteExpiryEpochMillis"))) { + throw unavailable(); + } + return descriptor; + } + + private RedisScriptDescriptor requireActiveTransitionDescriptor() { + RedisScriptDescriptor descriptor = scriptCatalog.require(ACTIVE_TRANSITION_SCRIPT_ID); + if (!ACTIVE_TRANSITION_SCRIPT_ID.equals(descriptor.scriptId()) + || !"account-service".equals(descriptor.owner()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != ScriptCategory.SESSION_CAS + || !REQUIRED_ACL_IDENTITY.equals(descriptor.principal()) + || !canonicalSharedDescriptorMetadata(descriptor) + || !ACTIVE_TRANSITION_SCRIPT_RESOURCE.equals(descriptor.resourcePath()) + || descriptor.keys().size() != 1 + || !"tokenRecord".equals(descriptor.keys().getFirst().name()) + || !TOKEN_KEY_PREFIX.equals(descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || !argumentNames(descriptor) + .equals( + List.of( + "exactCanonicalPendingRecordUtf8", + "exactCanonicalActiveRecordUtf8", + "originalAbsoluteExpiryEpochMillis"))) { + throw unavailable(); + } + return descriptor; + } + + private void requireOwnerReceiptCorrespondence( + PendingRegistrationReceipt receipt, CommittedCandidateVerificationData committed) { + AccountGameplayDelegationPendingIdentity identity = committed.identity(); + var authority = committed.authoritySnapshot(); + var signer = committed.signerCorrespondence(); + if (!REQUIRED_ACL_IDENTITY.equals(receipt.aclIdentity()) + || !receipt.tokenKey().equals(TOKEN_KEY_PREFIX + receipt.tokenHash()) + || !receipt.operationId().equals(identity.operationId().toString()) + || !receipt.requestId().equals(identity.requestId().toString()) + || !receipt.requestDigest().equals(identity.requestDigest()) + || !receipt.accountId().equals(identity.accountId().toString()) + || !receipt.tokenJti().equals(identity.tokenJti().toString()) + || !receipt.tokenHash().equals(committed.tokenSha256()) + || !receipt.kid().equals(committed.signerKid()) + || !receipt.signerGeneration().equals(committed.signerGeneration()) + || !receipt.canonicalRecordSha256().equals(committed.canonicalRegistryRecordSha256()) + || !receipt.evidenceBundleReference().equals(committed.evidenceBundleReference()) + || receipt.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || receipt.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || receipt.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || receipt.issuanceFence() != authority.issuanceFence() + || receipt.registryVersion() != 1L + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L + || !SHA256.matcher(committed.commitProofSha256()).matches() + || !"COMMITTED".equals(signer.promotionStatus()) + || !committed.signerKid().equals(signer.targetKid()) + || !committed.signerGeneration().equals(signer.targetGeneration())) { + throw unavailable(); + } + long expiresAtMillis; + try { + expiresAtMillis = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + long cleanupMargin = Math.subtractExact(receipt.absoluteExpiryMillis(), expiresAtMillis); + if (cleanupMargin < 0L || cleanupMargin > MAX_CLEANUP_MARGIN_MILLIS) throw unavailable(); + } catch (ArithmeticException ex) { + throw unavailable(); + } + if (identity.expiresAtEpochSecond() <= clock.instant().getEpochSecond()) throw unavailable(); + PendingIntent intent = + new PendingIntent( + identity.operationId(), + identity.requestId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.tokenJti(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + authority, + identity.credentialRequestBinding()); + if (!AccountGameplayDelegationIssuanceRepository.requestDigest(intent) + .equals(identity.requestDigest())) { + throw unavailable(); + } + } + + private void requirePendingMatchesOwner( + GameSessionAccountDelegationRegistryRecord record, + byte[] canonicalBytes, + PendingRegistrationReceipt receipt, + CommittedCandidateVerificationData committed) { + AccountGameplayDelegationPendingIdentity identity = committed.identity(); + var authority = committed.authoritySnapshot(); + if (!"pending".equals(record.state()) + || record.registryVersion() != 1L + || !record.tokenHash().equals(receipt.tokenHash()) + || !record.tokenHash().equals(committed.tokenSha256()) + || !record.kid().equals(committed.signerKid()) + || !record.signerGeneration().equals(committed.signerGeneration()) + || !record.operationId().equals(identity.operationId().toString()) + || !record.requestId().equals(identity.requestId().toString()) + || !record.accountId().equals(identity.accountId().toString()) + || !record.requestDigest().equals(identity.requestDigest()) + || !record.jti().equals(identity.tokenJti().toString()) + || record.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || record.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || record.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || record.issuanceFence() != authority.issuanceFence() + || !record.evidenceBundleReference().equals(committed.evidenceBundleReference()) + || !SHA256.matcher(committed.canonicalRegistryRecordSha256()).matches() + || !committed.canonicalRegistryRecordSha256().equals(sha256(canonicalBytes)) + || !canonicalMapEquals( + record.fields().get("authorityTuple"), + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())) + || !canonicalMapEquals(record.fields().get("membershipVersion"), Map.of()) + || !canonicalMapEquals( + record.fields().get("authoritySourceVersions"), authority.sourceVersions()) + || !"1".equals(record.fields().get("tokenGeneration"))) { + throw unavailable(); + } + } + + private byte[] activeRecordBytes(GameSessionAccountDelegationRegistryRecord pendingRecord) { + if (!"pending".equals(pendingRecord.state()) || pendingRecord.registryVersion() != 1L) { + throw unavailable(); + } + Map activeFields = new LinkedHashMap<>(pendingRecord.fields()); + activeFields.put("registryVersion", 2); + activeFields.put("state", "active"); + try { + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(activeFields)); + if (!boundedRegistryRecord(canonical)) throw unavailable(); + return canonical; + } catch (IOException | RuntimeException ex) { + throw unavailable(); + } + } + + private byte[] pendingRecordBytes(GameSessionAccountDelegationRegistryRecord activeRecord) { + if (!"active".equals(activeRecord.state()) || activeRecord.registryVersion() != 2L) { + throw unavailable(); + } + Map pendingFields = new LinkedHashMap<>(activeRecord.fields()); + pendingFields.put("registryVersion", 1); + pendingFields.put("state", "pending"); + try { + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(pendingFields)); + if (!boundedRegistryRecord(canonical)) throw unavailable(); + return canonical; + } catch (IOException | RuntimeException ex) { + throw unavailable(); + } + } + + private static boolean canonicalMapEquals(Object value, Map expected) { + if (!(value instanceof Map actual)) return false; + try { + return Arrays.equals(canonicalJson(actual), canonicalJson(expected)); + } catch (RuntimeException ex) { + return false; + } + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException ex) { + throw unavailable(); + } + } + + private boolean boundedRegistryRecord(byte[] value) { + return value != null && value.length > 0 && value.length <= maxRecordBytes; + } + + private static Long exactInteger(Object value) { + if (!(value instanceof Number number)) return null; + String encoded = number.toString(); + if (!encoded.matches("0|[1-9][0-9]{0,18}")) return null; + try { + return Long.valueOf(encoded); + } catch (NumberFormatException ex) { + return null; + } + } + + private RedisScriptDescriptor requireIssuerProjectionDescriptor() { + RedisScriptDescriptor descriptor = scriptCatalog.require(ISSUER_PROJECTION_SCRIPT_ID); + if (!ISSUER_PROJECTION_SCRIPT_ID.equals(descriptor.scriptId()) + || !"account-service".equals(descriptor.owner()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != ScriptCategory.SESSION_CAS + || !REQUIRED_ACL_IDENTITY.equals(descriptor.principal()) + || !canonicalSharedDescriptorMetadata(descriptor) + || !AUTHORITY_PROJECTION_SCRIPT_RESOURCE.equals(descriptor.resourcePath()) + || descriptor.keys().size() != 1 + || !"authorityProjection".equals(descriptor.keys().getFirst().name()) + || !AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX.equals( + descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || !argumentNames(descriptor).equals(List.of("canonicalProjectionUtf8"))) { + throw unavailable(); + } + return descriptor; + } + + private RedisScriptDescriptor requireCanonicalAccountProjectionDescriptor() { + RedisScriptDescriptor expected = AccountGenerationProjectionRedisContract.descriptor(); + RedisScriptDescriptor actual = scriptCatalog.require(ACCOUNT_PROJECTION_SCRIPT_ID); + if (!actual.equals(expected)) { + throw unavailable(); + } + return actual; + } + + private RedisScriptDescriptor requireSelectedProjectionDescriptor(boolean tenant) { + RedisScriptDescriptor descriptor = + scriptCatalog.require( + tenant ? TENANT_PROJECTION_SCRIPT_ID : MEMBERSHIP_PROJECTION_SCRIPT_ID); + RedisScriptDescriptor account = AccountGenerationProjectionRedisContract.descriptor(); + if (!"account-service".equals(descriptor.owner()) + || !(tenant ? TENANT_PROJECTION_SCRIPT_ID : MEMBERSHIP_PROJECTION_SCRIPT_ID) + .equals(descriptor.scriptId()) + || !account.resourcePath().equals(descriptor.resourcePath()) + || !account.sha256().equals(descriptor.sha256()) + || !account.role().equals(descriptor.role()) + || !account.arguments().equals(descriptor.arguments()) + || !account.outcomes().equals(descriptor.outcomes()) + || !account.resetSensitivity().equals(descriptor.resetSensitivity()) + || !account.lossClass().equals(descriptor.lossClass()) + || !account.principal().equals(descriptor.principal()) + || !account.compatibilityLevel().equals(descriptor.compatibilityLevel()) + || !account.supportedCoexistence().equals(descriptor.supportedCoexistence()) + || !Objects.equals(account.legacyPayloadShape(), descriptor.legacyPayloadShape()) + || !(tenant + ? "On loss deny selected gameplay use; reapply exact Account source events without sequence gaps." + : "On loss deny selected gameplay use; reapply exact Account membership events without sequence gaps.") + .equals(descriptor.tailLossBehavior()) + || descriptor.keys().size() != 1 + || !(tenant ? "tenantGenerationProjection" : "membershipGenerationProjection") + .equals(descriptor.keys().getFirst().name()) + || !(tenant + ? AccountSelectedGameplayAuthorityProjection.TENANT_PREFIX + : AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_PREFIX) + .equals(descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || descriptor.category() != ScriptCategory.SESSION_CAS) throw unavailable(); + return descriptor; + } + + private SelectedProjectionScript selectedProjectionScript(boolean tenant) { + RedisScriptDescriptor descriptor = requireSelectedProjectionDescriptor(tenant); + SelectedProjectionScript cached = selectedProjectionScript; + if (cached == null) { + synchronized (this) { + cached = selectedProjectionScript; + if (cached == null) { + RedisScriptDescriptor tenantDescriptor = requireSelectedProjectionDescriptor(true); + RedisScriptDescriptor membershipDescriptor = requireSelectedProjectionDescriptor(false); + byte[] source = readScriptSource(tenantDescriptor); + String sourceHash = sha256(source); + if (!sourceHash.equals(tenantDescriptor.sha256()) + || !sourceHash.equals(membershipDescriptor.sha256()) + || !tenantDescriptor.resourcePath().equals(membershipDescriptor.resourcePath())) { + throw unavailable(); + } + cached = + new SelectedProjectionScript( + tenantDescriptor.resourcePath(), sourceHash, sha1(source), source.clone()); + selectedProjectionScript = cached; + } + } + } + if (!descriptor.resourcePath().equals(cached.resourcePath()) + || !descriptor.sha256().equals(cached.sha256())) throw unavailable(); + return cached; + } + + private static RedisCommands requirePinnedCommands( + StatefulRedisConnection connection) { + if (!connection.isOpen()) throw unavailable(); + ClientOptions options = connection.getOptions(); + if (options == null || options.isAutoReconnect()) throw unavailable(); + return connection.sync(); + } + + private boolean boundedProjection(byte[] value) { + return value != null + && value.length > 0 + && value.length <= AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES; + } + + private static void requireProjectionResult(Long result) { + if (result == null || (result != 0L && result != 1L)) throw unavailable(); + } + + private static List argumentNames(RedisScriptDescriptor descriptor) { + return descriptor.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList(); + } + + private static boolean canonicalSharedDescriptorMetadata(RedisScriptDescriptor descriptor) { + return descriptor.resetSensitivity() == RedisScriptDescriptor.ResetSensitivity.CLUSTER + && descriptor.lossClass() == RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP + && descriptor.compatibilityLevel() + == RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + && descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1"))) + && descriptor.legacyPayloadShape() == null; + } + + private byte[] readScriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = resourceClassLoader.getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_SOURCE_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_SCRIPT_SOURCE_BYTES) throw unavailable(); + return bytes; + } catch (IOException ex) { + throw unavailable(); + } + } + + private static void requireAccountAclIdentity(RedisCommands commands) { + String identity = commands.aclWhoami(); + if (!REQUIRED_ACL_IDENTITY.equals(identity)) { + throw unavailable(); + } + } + + private Acknowledgement requireDurabilityAcknowledgement(RedisCommands commands) { + CommandArgs arguments = + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(acknowledgementRequirements.requiredLocalAofCount()) + .add(acknowledgementRequirements.requiredReplicaAofCount()) + .add(acknowledgementRequirements.timeoutMillis()); + List counts = + commands.dispatch( + WaitAofCommand.INSTANCE, new ArrayOutput<>(ByteArrayCodec.INSTANCE), arguments); + if (counts == null || counts.size() != 2) throw unavailable(); + Object localCount = counts.get(0); + Object replicaCount = counts.get(1); + if (!(localCount instanceof Long local) + || !(replicaCount instanceof Long replicas) + || local < acknowledgementRequirements.requiredLocalAofCount() + || replicas < acknowledgementRequirements.requiredReplicaAofCount()) { + throw unavailable(); + } + return new Acknowledgement(local, replicas); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static void requireCanonicalAccountUuid(java.util.UUID value) { + if (value == null + || value.equals(new java.util.UUID(0L, 0L)) + || value.version() != 4 + || value.variant() != 2) throw unavailable(); + } + + private static String sha256(byte[] bytes) { + return digest("SHA-256", bytes); + } + + private static String sha1(byte[] bytes) { + return digest("SHA-1", bytes); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw unavailable(); + } + } + + private static AccountCoordinationRedisException unavailable() { + return new AccountCoordinationRedisException(); + } + + public enum PendingRegistrationOutcome { + CREATED, + EXACT_RETRY + } + + /** + * Exact non-authorizing proof that a PENDING registry value was written and read back after + * required WAITAOF acknowledgement on one role-checked pinned connection. The private constructor + * prevents callers from turning Redis presence, a DTO, or a configured role label into + * registration evidence. + */ + public static final class PendingRegistrationReceipt { + private final String tokenKey; + private final String canonicalRecordSha256; + private final String aclIdentity; + private final String operationId; + private final String requestId; + private final String requestDigest; + private final String accountId; + private final String tokenJti; + private final String tokenHash; + private final String kid; + private final String signerGeneration; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final long issuanceFence; + private final long registryVersion; + private final GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference + evidenceBundleReference; + private final long absoluteExpiryMillis; + private final PendingRegistrationOutcome outcome; + private final long localAofCount; + private final long replicaAofCount; + + private PendingRegistrationReceipt( + GameSessionAccountDelegationRegistryRecord record, + String canonicalRecordSha256, + long absoluteExpiryMillis, + PendingRegistrationOutcome outcome, + long localAofCount, + long replicaAofCount) { + Objects.requireNonNull(record, "Verified pending registry record is required"); + if (!"pending".equals(record.state()) + || record.registryVersion() != 1L + || !TOKEN_HASH.matcher(canonicalRecordSha256).matches() + || absoluteExpiryMillis <= 0L + || localAofCount < 1L + || replicaAofCount < 1L) { + throw unavailable(); + } + long tokenExpiryMillis; + try { + tokenExpiryMillis = Math.multiplyExact(record.expiresAtEpochSecond(), 1_000L); + long cleanupMarginMillis = Math.subtractExact(absoluteExpiryMillis, tokenExpiryMillis); + if (cleanupMarginMillis < 0L || cleanupMarginMillis > MAX_CLEANUP_MARGIN_MILLIS) { + throw unavailable(); + } + } catch (ArithmeticException ex) { + throw unavailable(); + } + this.tokenKey = TOKEN_KEY_PREFIX + record.tokenHash(); + this.canonicalRecordSha256 = canonicalRecordSha256; + this.aclIdentity = REQUIRED_ACL_IDENTITY; + this.operationId = record.operationId(); + this.requestId = record.requestId(); + this.requestDigest = record.requestDigest(); + this.accountId = record.accountId(); + this.tokenJti = record.jti(); + this.tokenHash = record.tokenHash(); + this.kid = record.kid(); + this.signerGeneration = record.signerGeneration(); + this.issuedAtEpochSecond = record.issuedAtEpochSecond(); + this.notBeforeEpochSecond = record.notBeforeEpochSecond(); + this.expiresAtEpochSecond = record.expiresAtEpochSecond(); + this.issuanceFence = record.issuanceFence(); + this.registryVersion = record.registryVersion(); + this.evidenceBundleReference = record.evidenceBundleReference(); + this.absoluteExpiryMillis = absoluteExpiryMillis; + this.outcome = Objects.requireNonNull(outcome); + this.localAofCount = localAofCount; + this.replicaAofCount = replicaAofCount; + } + + public String tokenKey() { + return tokenKey; + } + + public String canonicalRecordSha256() { + return canonicalRecordSha256; + } + + public String aclIdentity() { + return aclIdentity; + } + + public String operationId() { + return operationId; + } + + public String requestId() { + return requestId; + } + + public String requestDigest() { + return requestDigest; + } + + public String accountId() { + return accountId; + } + + public String tokenJti() { + return tokenJti; + } + + public String tokenHash() { + return tokenHash; + } + + public String kid() { + return kid; + } + + public String signerGeneration() { + return signerGeneration; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public long issuanceFence() { + return issuanceFence; + } + + public long registryVersion() { + return registryVersion; + } + + public GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference + evidenceBundleReference() { + return evidenceBundleReference; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public PendingRegistrationOutcome outcome() { + return outcome; + } + + public long localAofCount() { + return localAofCount; + } + + public long replicaAofCount() { + return replicaAofCount; + } + + @Override + public String toString() { + return "PendingRegistrationReceipt[redacted]"; + } + } + + public enum ActiveRegistrationOutcome { + ACTIVATED, + EXACT_RETRY + } + + /** + * Private-constructor metadata for an exact ACTIVE registry readback. This value is not a token + * credential and is not proof of player admission, response recovery, or current signer state + * beyond the committed owner data supplied to the transition. + */ + public static final class ActiveRegistrationReceipt { + private final String tokenKey; + private final String tokenHash; + private final String operationId; + private final String requestId; + private final String accountId; + private final String canonicalActiveRecordSha256; + private final String commitProofSha256; + private final long registryVersion; + private final long absoluteExpiryMillis; + private final ActiveRegistrationOutcome outcome; + private final long localAofCount; + private final long replicaAofCount; + + private ActiveRegistrationReceipt( + GameSessionAccountDelegationRegistryRecord record, + String canonicalActiveRecordSha256, + String commitProofSha256, + long absoluteExpiryMillis, + ActiveRegistrationOutcome outcome, + long localAofCount, + long replicaAofCount) { + Objects.requireNonNull(record, "Verified active registry record is required"); + if (!"active".equals(record.state()) + || record.registryVersion() != 2L + || !SHA256.matcher(canonicalActiveRecordSha256).matches() + || !SHA256.matcher(commitProofSha256).matches() + || absoluteExpiryMillis <= 0L + || localAofCount < 1L + || replicaAofCount < 1L) { + throw unavailable(); + } + this.tokenKey = TOKEN_KEY_PREFIX + record.tokenHash(); + this.tokenHash = record.tokenHash(); + this.operationId = record.operationId(); + this.requestId = record.requestId(); + this.accountId = record.accountId(); + this.canonicalActiveRecordSha256 = canonicalActiveRecordSha256; + this.commitProofSha256 = commitProofSha256; + this.registryVersion = record.registryVersion(); + this.absoluteExpiryMillis = absoluteExpiryMillis; + this.outcome = Objects.requireNonNull(outcome); + this.localAofCount = localAofCount; + this.replicaAofCount = replicaAofCount; + } + + public String tokenKey() { + return tokenKey; + } + + public String tokenHash() { + return tokenHash; + } + + public String operationId() { + return operationId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String canonicalActiveRecordSha256() { + return canonicalActiveRecordSha256; + } + + public String commitProofSha256() { + return commitProofSha256; + } + + public long registryVersion() { + return registryVersion; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public ActiveRegistrationOutcome outcome() { + return outcome; + } + + public long localAofCount() { + return localAofCount; + } + + public long replicaAofCount() { + return replicaAofCount; + } + + @Override + public String toString() { + return "ActiveRegistrationReceipt[redacted]"; + } + } + + private record Acknowledgement(long localAofCount, long replicaAofCount) {} + + private record SelectedProjectionScript( + String resourcePath, String sha256, String redisSha1, byte[] source) { + private SelectedProjectionScript { + source = source.clone(); + } + } + + public enum ProjectionPublicationOutcome { + PUBLISHED, + EXACT_RETRY + } + + public static final class AccountCoordinationRedisException extends IllegalStateException { + private AccountCoordinationRedisException() { + super("Account Coordination Redis operation is unavailable or ambiguous"); + } + } + + /** Metadata-only observation of a Redis ACTIVE record; it does not authenticate a caller. */ + public static final class ActiveRegistryReadback { + private final String tokenHash; + private final String accountId; + private final String jti; + private final long tokenExpiryEpochSecond; + private final long absoluteExpiryMillis; + private final String canonicalPendingRecordSha256; + + private ActiveRegistryReadback( + String tokenHash, + String accountId, + String jti, + long tokenExpiryEpochSecond, + long absoluteExpiryMillis, + String canonicalPendingRecordSha256) { + this.tokenHash = Objects.requireNonNull(tokenHash); + this.accountId = Objects.requireNonNull(accountId); + this.jti = Objects.requireNonNull(jti); + this.tokenExpiryEpochSecond = tokenExpiryEpochSecond; + this.absoluteExpiryMillis = absoluteExpiryMillis; + this.canonicalPendingRecordSha256 = Objects.requireNonNull(canonicalPendingRecordSha256); + } + + public String tokenHash() { + return tokenHash; + } + + public String accountId() { + return accountId; + } + + public String jti() { + return jti; + } + + public long tokenExpiryEpochSecond() { + return tokenExpiryEpochSecond; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public String canonicalPendingRecordSha256() { + return canonicalPendingRecordSha256; + } + + @Override + public String toString() { + return "ActiveRegistryReadback[redacted]"; + } + } + + private enum WaitAofCommand implements ProtocolKeyword { + INSTANCE; + + private static final byte[] BYTES = ascii("WAITAOF"); + + @Override + public byte[] getBytes() { + return BYTES.clone(); + } + + @Override + public String toString() { + return "WAITAOF"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java new file mode 100644 index 0000000000..0c97cb7e88 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive Account-owned catalog contribution for private issuance and projection scripts. */ +public final class AccountGameplayDelegationRedisScriptContribution + implements RedisScriptContribution { + private static final int MAX_DESCRIPTOR_BYTES = 16 * 1024; + private static final String[] DESCRIPTOR_RESOURCES = { + "/redis/scripts/account-game-session-delegation-pending-register.json", + "/redis/scripts/account-game-session-delegation-activate-committed.json", + "/redis/scripts/account-game-session-delegation-authority-project-issuer.json", + "/redis/scripts/account-selected-tenant-generation-projection.json", + "/redis/scripts/account-selected-membership-generation-projection.json" + }; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + try { + List descriptors = new ArrayList<>(DESCRIPTOR_RESOURCES.length); + for (String resource : DESCRIPTOR_RESOURCES) { + RedisScriptDescriptor descriptor; + try (InputStream input = + AccountGameplayDelegationRedisScriptContribution.class.getResourceAsStream(resource)) { + if (input == null) { + throw new IllegalStateException("Account Redis descriptor is unavailable"); + } + byte[] bytes = input.readNBytes(MAX_DESCRIPTOR_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_DESCRIPTOR_BYTES) { + throw new IllegalStateException("Account Redis descriptor exceeds its finite bound"); + } + descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + } + if (!"account-service".equals(descriptor.owner())) { + throw new IllegalStateException("Account Redis descriptor owner is invalid"); + } + descriptors.add(descriptor); + } + if (descriptors.size() != 5 + || !descriptors.stream() + .map(RedisScriptDescriptor::scriptId) + .toList() + .equals( + List.of( + AccountGameplayDelegationRedisClient.SCRIPT_ID, + AccountGameplayDelegationRedisClient.ACTIVE_TRANSITION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.ISSUER_PROJECTION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.TENANT_PROJECTION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.MEMBERSHIP_PROJECTION_SCRIPT_ID))) { + throw new IllegalStateException("Account Redis descriptor identities are invalid"); + } + return List.copyOf(descriptors); + } catch (IOException | RuntimeException ex) { + if (ex instanceof IllegalStateException state) throw state; + throw new IllegalStateException("Account Redis descriptor is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java new file mode 100644 index 0000000000..981fcec1d3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.PendingCandidateCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Explicitly constructed, unregistered Account orchestration for one exact PENDING candidate. + * + *

This service does not authenticate the supplied caller, invoke signing, reconcile a registry, + * transition lifecycle state, decrypt an envelope, or return a credential. Its result is only a + * non-authorizing metadata observation for the owning issuance workflow. + */ +public class AccountGameplayDelegationResponseEnvelopeService { + private final AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring transaction proxies require an extensible service; this constructor retains only" + + " a repository reference, with no sensitive or native partially initialized" + + " resources or finalizer") + public AccountGameplayDelegationResponseEnvelopeService( + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes) { + this.responseEnvelopes = + Objects.requireNonNull( + responseEnvelopes, "Account response-envelope repository is required"); + } + + /** Persists the exact candidate only when every immutable owner identity still matches. */ + @Transactional(propagation = Propagation.MANDATORY) + public SealedCandidateObservation sealPendingCandidate( + UUID requestId, CallerIdentity caller, String exactCompactJwt) { + return responseEnvelopes.sealPendingCandidate(requestId, caller, exactCompactJwt); + } + + /** Opens exact durable PENDING bytes only for the internal signer verification retry. */ + @Transactional(propagation = Propagation.MANDATORY) + public PendingCandidateCredential openPendingCandidate(UUID requestId, CallerIdentity caller) { + return responseEnvelopes.openPendingCandidate(requestId, caller); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java new file mode 100644 index 0000000000..1119826692 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveryPreflight; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired Account owner for response recovery after initial gameplay LOGIN issuance. + * + *

The caller must already have authenticated the exact Game Session mTLS workload and must + * confirm that the original pre-auth socket context is still open and current. The supplied UUID is + * only compared with the immutable Account operation; it is not caller authentication. This owner + * first performs a small caller/account precheck, then delegates the exact COMMITTED-to-ACTIVE + * Redis transition to {@link AccountGameplayDelegationCommittedIssuanceOwner}, and only afterward + * asks the SQL/crypto owner to read and decrypt the original response envelope. It neither signs + * nor mints a token and does not establish Game Session context or a gameplay binding. + */ +public final class AccountGameplayDelegationResponseRecoveryOwner { + private final AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes; + private final AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner; + private final TransactionTemplate accountTransaction; + + public AccountGameplayDelegationResponseRecoveryOwner( + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes, + AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner, + PlatformTransactionManager transactionManager) { + this.responseEnvelopes = + Objects.requireNonNull( + responseEnvelopes, "Account response-envelope repository is required"); + this.committedIssuanceOwner = + Objects.requireNonNull( + committedIssuanceOwner, "Account committed-issuance owner is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + } + + /** + * Returns the exact compact JWT from an already committed operation after activation and a fresh + * owner read. The caller identity is a comparison input sourced from the authenticated Game + * Session boundary; this owner does not authenticate a UUID or trust caller-supplied workload + * text as proof of mTLS. + */ + @SuppressFBWarnings( + value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", + justification = + "Keep the explicit fail-closed AUTH_UNAVAILABLE outcome if the activation owner ever violates its non-null result contract.") + public RecoveredCredential recoverInitialLoginResponse( + UUID requestId, UUID expectedAccountId, CallerIdentity caller) { + requireRequest(requestId, expectedAccountId, caller); + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + RecoveryPreflight preflight = + accountTransaction.execute( + status -> + responseEnvelopes.preflightCommittedRecovery( + requestId, expectedAccountId, caller)); + if (preflight == null + || !requestId.equals(preflight.requestId()) + || !expectedAccountId.equals(preflight.accountId()) + || !caller.workload().equals(preflight.callerWorkload()) + || !caller.contextId().equals(preflight.callerContextId())) { + throw unavailable(); + } + + // This owner performs current signer/SQL checks around the pinned Redis CAS/readback and + // WAITAOF. It deliberately runs without an Account SQL transaction held by this owner. + AccountGameplayDelegationCommittedIssuanceOwner.ActiveCommittedIssuanceObservation active = + committedIssuanceOwner.activateCommittedIssuance(requestId); + if (active == null) throw unavailable(); + + RecoveredCredential credential = + accountTransaction.execute( + status -> + responseEnvelopes.recoverCommittedResponse( + requestId, expectedAccountId, caller, active)); + if (credential == null) throw unavailable(); + return credential; + } catch (IdempotencyConflictException | ResponseRecoveryExpiredException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static void requireRequest( + UUID requestId, UUID expectedAccountId, CallerIdentity caller) { + if (!isV4(requestId) || !isV4(expectedAccountId) || caller == null) throw unavailable(); + } + + private static boolean isV4(UUID value) { + return value != null && value.version() == 4 && value.variant() == 2; + } + + private static OwnerUnavailableException unavailable() { + return new OwnerUnavailableException(); + } + + /** Retryable fail-closed result; no implementation cause or credential bytes are retained. */ + public static final class OwnerUnavailableException extends IllegalStateException { + public OwnerUnavailableException() { + super("Account gameplay delegation response recovery is unavailable"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java new file mode 100644 index 0000000000..9cb048ccf9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java @@ -0,0 +1,1556 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.BoundTokenCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingSigningIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.PendingCandidateCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.AccountJwtExactValues; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Account-internal producer for one exact pending Game Session delegation candidate. + * + *

This class is intentionally not a Spring component and declares no RPC. It re-reads the + * durable unbound issuance identity, requires Account's exact current COMMITTED signer owner + * evidence, validates the active mounted key against Account's authenticated current public + * projection, and seals that exact pending candidate for Account-owned recovery. It has no active + * registry transition or caller-facing credential response. + */ +public final class AccountGameplayDelegationSigner { + private static final Path PRIVATE_MOUNT_ROOT = privateSignerMountRoot(); + private static final Path PRIVATE_ACTIVE_BUNDLE = Path.of("current.key"); + private static final Path PUBLIC_MOUNT_ROOT = publicJwksMountRoot(); + private static final Path PUBLIC_JWKS = Path.of("jwks.json"); + private static final Duration PUBLIC_KEY_CACHE_AGE = Duration.ofSeconds(30); + private static final ExplicitRouteProfilePolicy GSA_SIGNING_POLICY = + new ExplicitRouteProfilePolicy( + "account-gameplay-delegation-signing-self-check", + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.TYPE, + GameSessionAccountDelegationProfile.ISSUER, + GameSessionAccountDelegationProfile.AUDIENCE, + GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS, + GameSessionAccountDelegationJwtProfileValidator.OPTIONAL_CLAIMS, + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS, + 5, + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES, + GameSessionAccountDelegationJwtProfileValidator::validateClaims); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The interim Account private signing key uses this architecture-defined fixed protected mount; runtime configuration cannot redirect it or add a fallback.") + private static Path privateSignerMountRoot() { + return Path.of("/var/run/secrets/firemud/jwt"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "Account signer correspondence reads this architecture-defined fixed public JWKS mount; runtime configuration cannot redirect it or add a fallback.") + private static Path publicJwksMountRoot() { + return Path.of("/var/run/secrets/firemud/jwks"); + } + + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtJwksApiBinding apiBinding; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService; + private final TransactionTemplate accountTransaction; + private final Clock clock; + private final Path privateMountRoot; + private final Path privateBundlePath; + private final Path publicMountRoot; + private final Path publicJwksPath; + + public AccountGameplayDelegationSigner( + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksApiBinding apiBinding, + AccountJwtJwksTrustedSource trustedJwksSource, + AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService, + PlatformTransactionManager transactionManager, + Clock clock) { + this( + issuanceRepository, + desiredStateRepository, + materializerTrustBinding, + apiBinding, + trustedJwksSource, + responseEnvelopeService, + transactionManager, + clock, + PRIVATE_MOUNT_ROOT, + PRIVATE_ACTIVE_BUNDLE, + PUBLIC_MOUNT_ROOT, + PUBLIC_JWKS); + } + + AccountGameplayDelegationSigner( + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksApiBinding apiBinding, + AccountJwtJwksTrustedSource trustedJwksSource, + AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService, + PlatformTransactionManager transactionManager, + Clock clock, + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath) { + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account issuance repository is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Account signer owner is required"); + this.materializerTrustBinding = + Objects.requireNonNull( + materializerTrustBinding, "Protected materializer trust is required"); + this.apiBinding = + Objects.requireNonNull(apiBinding, "Protected Account JWKS API binding is required"); + this.trustedJwksSource = + Objects.requireNonNull(trustedJwksSource, "Account authenticated JWKS source is required"); + this.responseEnvelopeService = + Objects.requireNonNull( + responseEnvelopeService, "Account response envelope owner is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + this.privateMountRoot = + Objects.requireNonNull(privateMountRoot, "Private mount root is required"); + this.privateBundlePath = + Objects.requireNonNull(privateBundlePath, "Private bundle path is required"); + this.publicMountRoot = Objects.requireNonNull(publicMountRoot, "Public mount root is required"); + this.publicJwksPath = Objects.requireNonNull(publicJwksPath, "Public JWKS path is required"); + } + + /** + * Signs and seals one Account-selected pending issuance by request ID. The result contains only + * non-authorizing candidate and encrypted-envelope metadata, never a compact JWT. + */ + CandidateOutcome signPendingCandidate(UUID requestId) { + if (requestId == null) { + throw unavailable(); + } + + byte[] transientCompactJwt = null; + byte[] firstJwksBytes = null; + byte[] finalJwksBytes = null; + AtomicReference compactTokenCapture = new AtomicReference<>(); + AtomicReference acquiredCandidate = new AtomicReference<>(); + PendingCandidateCredential openedCandidate = null; + try { + InvocationIdentity acquired = + accountTransaction.execute( + status -> { + CurrentSigner signer = currentCommittedSigner(); + PendingSigningIdentity pending = requireCurrentPendingIdentity(requestId); + requireUnexpired(pending); + PendingCandidateCredential resumed = + pending.persistedCandidate().isPresent() + ? responseEnvelopeService.openPendingCandidate( + requestId, + new CallerIdentity( + pending.identity().callerWorkload(), + pending.identity().callerContextId())) + : null; + if (resumed != null) { + PendingCandidateCredential replaced = acquiredCandidate.getAndSet(resumed); + if (replaced != null) replaced.close(); + requireOpenedCandidate(pending, resumed); + } + return new InvocationIdentity(signer, pending, resumed); + }); + openedCandidate = acquiredCandidate.getAndSet(null); + if (acquired == null) { + throw unavailable(); + } + final InvocationIdentity initial = acquired; + + SourceIdentity sourcePin = trustedJwksSource.sourceIdentity(); + PublicJwksSnapshot initialSnapshot = trustedJwksSource.load(); + firstJwksBytes = + requireExactTrustedSnapshot(initial.currentSigner(), sourcePin, initialSnapshot); + byte[] initialJwksProjection = firstJwksBytes; + AccountPublicJwksCache keyCache = + new AccountPublicJwksCache( + () -> { + PublicJwksSnapshot observed = trustedJwksSource.load(); + byte[] observedBytes = + requireExactTrustedSnapshot(initial.currentSigner(), sourcePin, observed); + try { + if (!Arrays.equals(initialJwksProjection, observedBytes)) { + throw new AccountPublicJwksCache.InvalidJwksException(); + } + return observed; + } finally { + wipe(observedBytes); + } + }, + sourcePin, + clock, + PUBLIC_KEY_CACHE_AGE); + keyCache.keyFor(initial.currentSigner().expectedIdentity().kid()); + + AccountMountedJwtSignerBundle.SignedDelegationDigest digest = null; + VerifiedCandidateIdentity candidateIdentity; + if (initial.resumedCandidate() == null) { + digest = + AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( + privateMountRoot, + privateBundlePath, + publicMountRoot, + publicJwksPath, + initial.currentSigner().expectedIdentity(), + new AccountMountedJwtSignerBundle.DelegationSigningSpec( + initial.pending().identity(), initial.pending().authoritySnapshot()), + (signed, exactCompactJwt) -> { + requireSignedIdentity(initial, signed); + byte[] transientCopy = exactCompactJwt.clone(); + if (!compactTokenCapture.compareAndSet(null, transientCopy)) { + wipe(transientCopy); + throw unavailable(); + } + }); + transientCompactJwt = compactTokenCapture.getAndSet(null); + if (transientCompactJwt == null + || !sha256(transientCompactJwt).equals(digest.compactTokenSha256())) { + throw unavailable(); + } + candidateIdentity = candidateIdentity(initial.pending(), digest); + } else { + PendingRegistryCandidate persisted = + initial + .pending() + .persistedCandidate() + .orElseThrow(AccountGameplayDelegationSigner::unavailable); + requirePersistedCandidateSigner(initial, persisted); + transientCompactJwt = initial.resumedCandidate().compactJwtBytes(); + candidateIdentity = candidateIdentity(initial.pending(), persisted); + if (!sha256(transientCompactJwt).equals(candidateIdentity.tokenSha256())) { + throw unavailable(); + } + } + String compactJwt = exactAscii(transientCompactJwt); + + VerifiedClaims verified = + new AccountAsymmetricJwtVerifier(keyCache, clock).verify(compactJwt, GSA_SIGNING_POLICY); + requireVerifiedClaims(initial, candidateIdentity, verified); + + PublicJwksSnapshot finalSnapshot = trustedJwksSource.load(); + finalJwksBytes = + requireExactTrustedSnapshot(initial.currentSigner(), sourcePin, finalSnapshot); + if (!Arrays.equals(firstJwksBytes, finalJwksBytes)) { + throw unavailable(); + } + + AccountMountedJwtSignerBundle.SignedDelegationDigest signedDigest = digest; + VerifiedCandidateIdentity verifiedCandidateIdentity = candidateIdentity; + CandidateOutcome outcome = + accountTransaction.execute( + status -> + initial.resumedCandidate() == null + ? bindAndSealWithinTransaction( + requestId, + compactJwt, + initial, + verifiedCandidateIdentity, + signedDigest, + sourcePin) + : resumeAndReadbackWithinTransaction( + requestId, initial, verifiedCandidateIdentity, sourcePin)); + if (outcome == null) { + throw unavailable(); + } + return outcome; + } catch (RuntimeException failure) { + // Never preserve implementation, parser, API, or JWT-bearing causes across this boundary. + throw unavailable(); + } finally { + wipe(transientCompactJwt); + wipe(compactTokenCapture.getAndSet(null)); + wipe(firstJwksBytes); + wipe(finalJwksBytes); + if (openedCandidate != null) openedCandidate.close(); + PendingCandidateCredential untransferredCandidate = acquiredCandidate.getAndSet(null); + if (untransferredCandidate != null) untransferredCandidate.close(); + } + } + + /** + * Revalidates signer-owned candidate evidence inside the caller's writable Account transaction. + * This method performs no signing, external JWKS/API request, mutation, or authorization effect. + */ + void requireCurrentCommittedSigner(PendingCandidateVerificationProof proof) { + if (proof == null + || !TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable(); + } + VerifiedPendingIdentity identity = proof.identity(); + long now = Math.floorDiv(clock.millis(), 1_000L); + long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; + if (now <= 0L + || identity.notBeforeEpochSecond() > now + || identity.issuedAtEpochSecond() > latestIssuedAt + || identity.expiresAtEpochSecond() <= now) { + throw unavailable(); + } + + CurrentSigner current = currentCommittedSigner(); + SourceIdentity originalSourceIdentity = proof.signerCorrespondence().publicJwksSourceIdentity(); + requireCurrentSourceIdentity(current, originalSourceIdentity); + if (!signerCorrespondence(current, originalSourceIdentity) + .equals(proof.signerCorrespondence())) { + throw unavailable(); + } + } + + /** + * Revalidates the exact signer correspondence captured by durable COMMITTED evidence inside a + * caller-owned writable Account transaction. It neither verifies a fabricated DTO nor signs, + * fetches public response data, mutates the operation, or authorizes token use. + */ + void requireCurrentCommittedSigner(CommittedCandidateVerificationData committed) { + if (committed == null + || !TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence original = requireCommittedCandidateIdentity(committed); + + CurrentSigner current = currentCommittedSigner(); + SourceIdentity sourceIdentity = original.publicJwksSourceIdentity(); + requireCurrentSourceIdentity(current, sourceIdentity); + if (!signerCorrespondence(current, sourceIdentity).equals(original)) throw unavailable(); + } + + /** + * Revalidates COMMITTED signer metadata while allowing its generation to be historical for + * bounded response recovery. The current Account owner must still have one coherent COMMITTED + * ACTIVE signer under the exact original protected trust/API/source identity. The historical + * token key is checked separately against today's owner/readback-proved JWKS outside SQL. + */ + void requireCurrentCommittedRecoverySigner(CommittedCandidateVerificationData committed) { + if (committed == null + || !TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence original = requireCommittedCandidateIdentity(committed); + + CurrentSigner current = currentCommittedSigner(); + requireCurrentSourceIdentity(current, original.publicJwksSourceIdentity()); + if (!current.binding().equals(original.binding()) + || !current.trust().equals(original.trustFence()) + || !current.api().bindingDigest().equals(original.apiBindingDigest()) + || !current.api().configRevision().equals(original.apiConfigRevision())) { + throw unavailable(); + } + } + + /** Confirms the original committed key has not been pruned or substituted in current JWKS. */ + void requireRetainedCommittedPublicKey(CommittedCandidateVerificationData committed) { + if (committed == null || TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence original = requireCommittedCandidateIdentity(committed); + Optional currentFingerprint; + try { + if (!original.publicJwksSourceIdentity().equals(trustedJwksSource.sourceIdentity())) { + throw unavailable(); + } + PublicJwksSnapshot currentJwks = trustedJwksSource.load(); + currentFingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint( + currentJwks, original.publicJwksSourceIdentity(), original.targetKid()); + } catch (RuntimeException unavailableSource) { + throw unavailable(); + } + if (currentFingerprint.isEmpty() + || !original.targetPublicKeyFingerprint().equals(currentFingerprint.orElseThrow())) { + throw unavailable(); + } + } + + private AuthenticatedSignerCorrespondence requireCommittedCandidateIdentity( + CommittedCandidateVerificationData committed) { + var identity = committed.identity(); + long now = Math.floorDiv(clock.millis(), 1_000L); + long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; + long expectedEnvelopeExpiry; + try { + expectedEnvelopeExpiry = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException invalidExpiry) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence original = committed.signerCorrespondence(); + if (now <= 0L + || identity.notBeforeEpochSecond() > now + || identity.issuedAtEpochSecond() > latestIssuedAt + || identity.expiresAtEpochSecond() <= now + || !identity.accountId().equals(committed.authoritySnapshot().accountId()) + || !committed.evidenceBundleReference().canonicalSha256().matches("[0-9a-f]{64}") + || !committed.tokenSha256().matches("[0-9a-f]{64}") + || !committed.canonicalRegistryRecordSha256().matches("[0-9a-f]{64}") + || !committed.commitProofSha256().matches("[0-9a-f]{64}") + || !committed.envelopeSha256().matches("[0-9a-f]{64}") + || committed.envelopeBytesLength() < 1 + || committed.envelopeBytesLength() > 65_610 + || committed.envelopeKeyId() == null + || !committed.envelopeKeyId().matches("[A-Za-z0-9_-]{1,32}") + || expectedEnvelopeExpiry != committed.responseRecoveryExpiryEpochMillis() + || !committed.signerKid().equals(original.targetKid()) + || !committed.signerGeneration().equals(original.targetGeneration()) + || !"COMMITTED".equals(original.promotionStatus()) + || !original.privatePromotionDispatched() + || !original.promotionOperationId().equals(original.privatePromotionOperationId()) + || !original.promotionOperationId().equals(original.publicPromotionOperationId()) + || !original + .generationOperationId() + .equals(original.privatePromotionGenerationOperationId()) + || !"RS256".equals(original.targetAlgorithm()) + || !original.targetPublicKeyFingerprint().matches("[0-9a-f]{64}") + || original + .durableActive() + .filter( + active -> + active.generation().equals(committed.signerGeneration()) + && active.kid().equals(committed.signerKid())) + .isEmpty() + || original + .publishedActive() + .filter( + active -> + active.generation().equals(committed.signerGeneration()) + && active.kid().equals(committed.signerKid())) + .isEmpty()) { + throw unavailable(); + } + return original; + } + + private static void requireCurrentSourceIdentity( + CurrentSigner currentSigner, SourceIdentity sourceIdentity) { + if (sourceIdentity == null + || !currentSigner.binding().environmentId().equals(sourceIdentity.environmentId()) + || !currentSigner.binding().clusterId().equals(sourceIdentity.clusterId()) + || !currentSigner.binding().namespace().equals(sourceIdentity.namespace()) + || !currentSigner + .trust() + .expectedClusterIncarnationUid() + .equals(sourceIdentity.clusterIncarnationUid()) + || !currentSigner.trust().expectedNamespaceUid().equals(sourceIdentity.namespaceUid()) + || !currentSigner.api().configRevision().equals(sourceIdentity.bindingRevision()) + || !currentSigner.api().apiServer().toString().equals(sourceIdentity.apiServerOrigin()) + || !currentSigner.api().servingCaSha256().equals(sourceIdentity.servingCaSha256()) + || !currentSigner + .evidence() + .promotion() + .publicConfigMapUid() + .equals(sourceIdentity.configMapUid()) + || !currentSigner + .evidence() + .publicReceipt() + .configMapUid() + .equals(sourceIdentity.configMapUid())) { + throw unavailable(); + } + } + + private CandidateOutcome bindAndSealWithinTransaction( + UUID requestId, + String compactJwt, + InvocationIdentity initial, + VerifiedCandidateIdentity candidateIdentity, + AccountMountedJwtSignerBundle.SignedDelegationDigest digest, + SourceIdentity sourceIdentity) { + CurrentSigner currentBeforePersist = currentCommittedSigner(); + PendingSigningIdentity pendingBeforePersist = requireCurrentPendingIdentity(requestId); + requireUnexpired(pendingBeforePersist); + requireSameCommittedSigner(initial.currentSigner(), currentBeforePersist); + requireSamePendingIdentity(initial.pending(), pendingBeforePersist); + + BoundTokenCandidate bound = + issuanceRepository.bindSignedCandidate(requestId, compactJwt, digest.signerGeneration()); + requireBoundCandidate(requestId, candidateIdentity, bound); + + PendingRegistryCandidate persisted = issuanceRepository.readPendingRegistryCandidate(requestId); + requirePersistedCandidate(initial, candidateIdentity, persisted); + + SealedCandidateObservation sealed = + responseEnvelopeService.sealPendingCandidate( + requestId, + new CallerIdentity( + pendingBeforePersist.identity().callerWorkload(), + pendingBeforePersist.identity().callerContextId()), + compactJwt); + requireSealedCandidate(requestId, pendingBeforePersist, sealed); + + PendingRegistryCandidate finalReadback = + issuanceRepository.readPendingRegistryCandidate(requestId); + requirePersistedCandidate(initial, candidateIdentity, finalReadback); + CurrentSigner currentAfterPersist = currentCommittedSigner(); + requireSameCommittedSigner(initial.currentSigner(), currentAfterPersist); + + PendingCandidateVerificationProof verificationProof = + createVerificationProof( + pendingBeforePersist, + candidateIdentity, + finalReadback, + sealed, + currentAfterPersist, + sourceIdentity); + + return new CandidateOutcome( + pendingBeforePersist.identity().operationId(), + requestId, + candidateIdentity.tokenSha256(), + candidateIdentity.signerGeneration(), + candidateIdentity.kid(), + sealed, + verificationProof); + } + + private CandidateOutcome resumeAndReadbackWithinTransaction( + UUID requestId, + InvocationIdentity initial, + VerifiedCandidateIdentity candidateIdentity, + SourceIdentity sourceIdentity) { + CurrentSigner currentBeforePersist = currentCommittedSigner(); + PendingSigningIdentity pendingBeforePersist = requireCurrentPendingIdentity(requestId); + requireUnexpired(pendingBeforePersist); + requireSameCommittedSigner(initial.currentSigner(), currentBeforePersist); + requireSamePendingIdentity(initial.pending(), pendingBeforePersist); + + PendingRegistryCandidate persisted = issuanceRepository.readPendingRegistryCandidate(requestId); + requirePersistedCandidate(initial, candidateIdentity, persisted); + PendingCandidateCredential revalidatedEnvelope = + responseEnvelopeService.openPendingCandidate( + requestId, + new CallerIdentity( + pendingBeforePersist.identity().callerWorkload(), + pendingBeforePersist.identity().callerContextId())); + final SealedCandidateObservation sealed; + try { + sealed = revalidatedEnvelope.sealedCandidate(); + if (!sealed.equals(initial.resumedCandidate().sealedCandidate())) throw unavailable(); + } finally { + revalidatedEnvelope.close(); + } + + PendingRegistryCandidate finalReadback = + issuanceRepository.readPendingRegistryCandidate(requestId); + requirePersistedCandidate(initial, candidateIdentity, finalReadback); + CurrentSigner currentAfterPersist = currentCommittedSigner(); + requireSameCommittedSigner(initial.currentSigner(), currentAfterPersist); + + PendingCandidateVerificationProof verificationProof = + createVerificationProof( + pendingBeforePersist, + candidateIdentity, + finalReadback, + sealed, + currentAfterPersist, + sourceIdentity); + + return new CandidateOutcome( + pendingBeforePersist.identity().operationId(), + requestId, + candidateIdentity.tokenSha256(), + candidateIdentity.signerGeneration(), + candidateIdentity.kid(), + sealed, + verificationProof); + } + + private static PendingCandidateVerificationProof createVerificationProof( + PendingSigningIdentity pending, + VerifiedCandidateIdentity candidateIdentity, + PendingRegistryCandidate persisted, + SealedCandidateObservation sealed, + CurrentSigner currentSigner, + SourceIdentity sourceIdentity) { + byte[] canonicalRecord = persisted.canonicalRecordBytes(); + final String recordSha256; + try { + recordSha256 = sha256(canonicalRecord); + } finally { + wipe(canonicalRecord); + } + VerifiedPendingIdentity identity = + new VerifiedPendingIdentity( + persisted.identity().operationId(), + persisted.identity().requestId(), + persisted.identity().accountId(), + persisted.identity().callerWorkload(), + persisted.identity().callerContextId(), + persisted.identity().requestDigest(), + persisted.identity().tokenJti(), + persisted.identity().issuedAtEpochSecond(), + persisted.identity().notBeforeEpochSecond(), + persisted.identity().expiresAtEpochSecond()); + if (!identity.requestId().equals(candidateIdentity.requestId()) + || !identity.operationId().equals(candidateIdentity.operationId()) + || !identity.tokenJti().equals(candidateIdentity.jti()) + || candidateIdentity.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || candidateIdentity.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || candidateIdentity.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || persisted.authoritySnapshot() == null + || !persisted + .evidenceBundleReference() + .canonicalSha256() + .equals(pending.evidenceBundle().canonicalSha256()) + || !persisted.tokenHash().equals(candidateIdentity.tokenSha256()) + || !persisted.kid().equals(candidateIdentity.kid()) + || !persisted.signerGeneration().equals(candidateIdentity.signerGeneration())) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence correspondence = + signerCorrespondence(currentSigner, sourceIdentity); + if (!persisted.authoritySnapshot().equals(pending.authoritySnapshot()) + || !correspondence + .generationOperationId() + .equals(UUID.fromString(currentSigner.expectedIdentity().operationId())) + || !correspondence.targetGeneration().equals(candidateIdentity.signerGeneration()) + || !correspondence.targetKid().equals(candidateIdentity.kid()) + || !correspondence + .targetPublicKeyFingerprint() + .equals(currentSigner.expectedIdentity().publicKeyFingerprint())) { + throw unavailable(); + } + return new PendingCandidateVerificationProof( + identity, + persisted.authoritySnapshot(), + persisted.evidenceBundleReference(), + persisted.tokenHash(), + recordSha256, + correspondence, + sealed); + } + + private static AuthenticatedSignerCorrespondence signerCorrespondence( + CurrentSigner currentSigner, SourceIdentity sourceIdentity) { + CommittedSignerEvidence evidence = currentSigner.evidence(); + var promotion = evidence.promotion(); + var generation = evidence.generationResult(); + var desiredState = evidence.desiredState(); + var privateReceipt = evidence.privateReceipt(); + var publicReceipt = evidence.publicReceipt(); + if (sourceIdentity == null + || !promotion.publicConfigMapUid().equals(sourceIdentity.configMapUid()) + || !promotion.apiBindingDigest().equals(currentSigner.api().bindingDigest()) + || !promotion.apiConfigRevision().equals(currentSigner.api().configRevision()) + || !publicReceipt.configMapUid().equals(sourceIdentity.configMapUid()) + || !privateReceipt.promotionOperationId().equals(promotion.operationId()) + || !privateReceipt.generationOperationId().equals(generation.operationId()) + || !publicReceipt.promotionOperationId().equals(promotion.operationId()) + || !generation.operationId().equals(promotion.generationOperationId()) + || !promotion.privatePromotionDispatched() + || promotion + .privatePromotionObservedResourceVersion() + .filter(privateReceipt.observedResourceVersion()::equals) + .isEmpty() + || promotion + .privatePromotionReceiptDigest() + .filter(privateReceipt.receiptDigest()::equals) + .isEmpty() + || promotion + .activeJwksObservedResourceVersion() + .filter(publicReceipt.observedResourceVersion()::equals) + .isEmpty() + || promotion + .activeJwksPublicDataDigest() + .filter(publicReceipt.publicDataDigest()::equals) + .isEmpty() + || promotion + .activeJwksReceiptDigest() + .filter(publicReceipt.receiptDigest()::equals) + .isEmpty()) { + throw unavailable(); + } + return new AuthenticatedSignerCorrespondence( + currentSigner.binding(), + currentSigner.trust(), + currentSigner.api().bindingDigest(), + currentSigner.api().configRevision(), + sourceIdentity, + desiredState.recordVersion(), + desiredState.durableActive(), + desiredState.publishedActive(), + promotion.operationId(), + promotion.requestDigest(), + promotion.expectedRecordVersion(), + promotion.expectedPreviousActive(), + promotion.expectedPreviousPublicKeyFingerprint(), + promotion.expectedPublishedActive(), + promotion.status(), + promotion.generationOperationId(), + promotion.generationOperationDigest(), + promotion.generationReceiptDigest(), + generation.desiredStateVersion(), + generation.privateSecretName(), + generation.secretUid(), + generation.expectedPriorResourceVersion(), + generation.observedResourceVersion(), + generation.targetGeneration(), + generation.targetKid(), + generation.targetAlgorithm(), + generation.publicKeyFingerprint(), + privateReceipt.observedResourceVersion(), + privateReceipt.receiptDigest(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + publicReceipt.priorResourceVersion(), + publicReceipt.observedResourceVersion(), + publicReceipt.publicDataDigest(), + publicReceipt.receiptDigest(), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.privatePromotionDispatched(), + privateReceipt.promotionOperationId(), + privateReceipt.generationOperationId(), + publicReceipt.promotionOperationId(), + promotion.privatePromotionObservedResourceVersion(), + promotion.privatePromotionReceiptDigest(), + promotion.activeJwksObservedResourceVersion(), + promotion.activeJwksPublicDataDigest(), + promotion.activeJwksReceiptDigest()); + } + + private byte[] requireExactTrustedSnapshot( + CurrentSigner currentSigner, SourceIdentity sourceIdentity, PublicJwksSnapshot snapshot) { + if (sourceIdentity == null + || snapshot == null + || !sourceIdentity.equals(snapshot.sourceIdentity()) + || !currentSigner.binding().environmentId().equals(sourceIdentity.environmentId()) + || !currentSigner.binding().clusterId().equals(sourceIdentity.clusterId()) + || !currentSigner.binding().namespace().equals(sourceIdentity.namespace()) + || !currentSigner + .trust() + .expectedClusterIncarnationUid() + .equals(sourceIdentity.clusterIncarnationUid()) + || !currentSigner.trust().expectedNamespaceUid().equals(sourceIdentity.namespaceUid()) + || !currentSigner + .evidence() + .promotion() + .publicConfigMapUid() + .equals(sourceIdentity.configMapUid()) + || !currentSigner + .evidence() + .publicReceipt() + .configMapUid() + .equals(sourceIdentity.configMapUid()) + || !currentSigner.api().configRevision().equals(sourceIdentity.bindingRevision()) + || !currentSigner.api().servingCaSha256().equals(sourceIdentity.servingCaSha256()) + || !currentSigner.api().apiServer().toString().equals(sourceIdentity.apiServerOrigin())) { + throw unavailable(); + } + byte[] jwksBytes = snapshot.jwksBytes(); + if (jwksBytes == null + || jwksBytes.length == 0 + || jwksBytes.length > AccountPublicJwksCache.MAX_JWKS_BYTES) { + wipe(jwksBytes); + throw unavailable(); + } + return jwksBytes; + } + + private PendingSigningIdentity requireCurrentPendingIdentity(UUID requestId) { + PendingSigningIdentity pending = issuanceRepository.readPendingSigningIdentity(requestId); + if (pending == null + || pending.identity() == null + || pending.authoritySnapshot() == null + || pending.evidenceBundle() == null + || !requestId.equals(pending.identity().requestId()) + || !pending.identity().accountId().equals(pending.authoritySnapshot().accountId()) + || !GameSessionAccountDelegationProfile.PROFILE.equals( + pending.evidenceBundle().fields().get("profile")) + || !GameSessionAccountDelegationProfile.AUDIENCE.equals( + pending.evidenceBundle().fields().get("audience"))) { + throw unavailable(); + } + return pending; + } + + private CurrentSigner currentCommittedSigner() { + AccountJwtSignerMaterializerTrustBinding.Binding materializer = + materializerTrustBinding + .current() + .orElseThrow(AccountGameplayDelegationSigner::unavailable); + AccountJwtJwksApiBinding.ParsedBinding api = apiBinding.current(); + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid())) { + throw unavailable(); + } + + AccountJwtSignerDesiredStateRepository.Binding binding = + new AccountJwtSignerDesiredStateRepository.Binding( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + TrustFence trust = + new TrustFence( + materializer.expectedClusterIncarnationUid(), + materializer.expectedNamespaceUid(), + materializer.bindingDigest(), + materializer.configRevision()); + CommittedSignerEvidence evidence = + desiredStateRepository + .readCurrentCommittedSigner(binding, trust, api.bindingDigest(), api.configRevision()) + .orElseThrow(AccountGameplayDelegationSigner::unavailable); + return verifiedCurrentSigner(binding, trust, api, evidence); + } + + private static CurrentSigner verifiedCurrentSigner( + AccountJwtSignerDesiredStateRepository.Binding binding, + TrustFence trust, + AccountJwtJwksApiBinding.ParsedBinding api, + CommittedSignerEvidence evidence) { + var promotion = evidence.promotion(); + var generation = evidence.generationResult(); + ActiveSigner target = new ActiveSigner(generation.targetGeneration(), generation.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !binding.equals(promotion.binding()) + || !binding.equals(generation.binding()) + || !trust.equals(promotion.trustFence()) + || !trust.equals(generation.trustFence()) + || !promotion.generationOperationId().equals(generation.operationId()) + || !promotion.targetGeneration().equals(generation.targetGeneration()) + || !promotion.targetKid().equals(generation.targetKid()) + || !promotion.targetAlgorithm().equals("RS256") + || !generation.targetAlgorithm().equals("RS256") + || !promotion.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint()) + || evidence.desiredState().durableActive().filter(target::equals).isEmpty() + || evidence.desiredState().publishedActive().filter(target::equals).isEmpty() + || evidence.desiredState().preparedOperationId().isPresent() + || !evidence.privateReceipt().promotionOperationId().equals(promotion.operationId()) + || !evidence.publicReceipt().promotionOperationId().equals(promotion.operationId())) { + throw unavailable(); + } + AccountMountedJwtSignerBundle.ExpectedIdentity expected = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + generation.operationId().toString(), + generation.targetGeneration(), + generation.targetKid(), + generation.publicKeyFingerprint()); + return new CurrentSigner(binding, trust, api, evidence, expected); + } + + private static void requireSameCommittedSigner(CurrentSigner expected, CurrentSigner observed) { + if (!expected.equals(observed)) { + throw unavailable(); + } + } + + private void requireUnexpired(PendingSigningIdentity pending) { + long now = Math.floorDiv(clock.millis(), 1000L); + long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; + if (now <= 0L + || pending.identity().notBeforeEpochSecond() > now + || pending.identity().issuedAtEpochSecond() > latestIssuedAt + || pending.identity().expiresAtEpochSecond() <= now) { + throw unavailable(); + } + } + + private static void requireSignedIdentity( + InvocationIdentity initial, AccountMountedJwtSignerBundle.SignedDelegationDigest digest) { + PendingSigningIdentity pending = initial.pending(); + AccountMountedJwtSignerBundle.ExpectedIdentity signer = + initial.currentSigner().expectedIdentity(); + if (!digest.issuanceOperationId().equals(pending.identity().operationId()) + || !digest.requestId().equals(pending.identity().requestId()) + || !digest.jti().equals(pending.identity().tokenJti()) + || !digest.signerOperationId().equals(signer.operationId()) + || !digest.signerGeneration().equals(signer.generation()) + || !digest.kid().equals(signer.kid()) + || !digest.publicKeyFingerprint().equals(signer.publicKeyFingerprint()) + || digest.issuedAtEpochSecond() != pending.identity().issuedAtEpochSecond() + || digest.notBeforeEpochSecond() != pending.identity().notBeforeEpochSecond() + || digest.expiresAtEpochSecond() != pending.identity().expiresAtEpochSecond()) { + throw unavailable(); + } + } + + private static void requireVerifiedClaims( + InvocationIdentity initial, VerifiedCandidateIdentity candidate, VerifiedClaims verified) { + PendingSigningIdentity pending = initial.pending(); + AccountMountedJwtSignerBundle.ExpectedIdentity signer = + initial.currentSigner().expectedIdentity(); + Map claims = verified.claims(); + Object authorityTuple = claims.get("authorityTuple"); + Object expectedAuthorityTuple = + GameSessionAccountDelegationProfile.authorityTuple( + pending.authoritySnapshot().issuerGeneration(), + pending.authoritySnapshot().accountGeneration(), + pending.authoritySnapshot().accountSecurityCutoff()); + if (!GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) + || !GameSessionAccountDelegationProfile.TYPE.equals(verified.tokenType()) + || !signer.kid().equals(verified.keyId()) + || !candidate.kid().equals(signer.kid()) + || !candidate.signerGeneration().equals(signer.generation()) + || !pending.identity().accountId().toString().equals(claims.get("sub")) + || !pending.identity().accountId().toString().equals(claims.get("accountId")) + || !pending.identity().tokenJti().toString().equals(claims.get("jti")) + || decimalCounterClaim(claims, "tokenGeneration") != 1L + || numberClaim(claims, "iat") != pending.identity().issuedAtEpochSecond() + || numberClaim(claims, "nbf") != pending.identity().notBeforeEpochSecond() + || numberClaim(claims, "exp") != pending.identity().expiresAtEpochSecond() + || decimalCounterClaim(claims, "issuanceFence") + != pending.authoritySnapshot().issuanceFence() + || !(claims.get("membershipVersion") instanceof Map membershipVersion) + || !membershipVersion.isEmpty() + || !(authorityTuple instanceof Map) + || !authorityTuple.equals(expectedAuthorityTuple) + || claims.containsKey("globalRoles") + || claims.containsKey("scopedRoles") + || !candidate.operationId().equals(pending.identity().operationId()) + || !candidate.requestId().equals(pending.identity().requestId()) + || !candidate.jti().equals(pending.identity().tokenJti()) + || candidate.issuedAtEpochSecond() != pending.identity().issuedAtEpochSecond() + || candidate.notBeforeEpochSecond() != pending.identity().notBeforeEpochSecond() + || candidate.expiresAtEpochSecond() != pending.identity().expiresAtEpochSecond() + || !candidate.tokenSha256().matches("[0-9a-f]{64}")) { + throw unavailable(); + } + } + + private static long numberClaim(Map claims, String field) { + Object value = claims.get(field); + if (!(value instanceof Number number)) { + throw unavailable(); + } + try { + return new java.math.BigDecimal(number.toString()).longValueExact(); + } catch (ArithmeticException | NumberFormatException malformed) { + throw unavailable(); + } + } + + private static long decimalCounterClaim(Map claims, String field) { + try { + return AccountJwtExactValues.positiveDecimalCounter(claims.get(field)).longValueExact(); + } catch (IllegalArgumentException | ArithmeticException malformed) { + throw unavailable(); + } + } + + private static void requireSamePendingIdentity( + PendingSigningIdentity expected, PendingSigningIdentity observed) { + if (!expected.identity().equals(observed.identity()) + || !expected.authoritySnapshot().equals(observed.authoritySnapshot()) + || !expected + .evidenceBundle() + .canonicalSha256() + .equals(observed.evidenceBundle().canonicalSha256()) + || !Arrays.equals( + expected.evidenceBundle().canonicalBytes(), observed.evidenceBundle().canonicalBytes()) + || !samePersistedCandidate(expected.persistedCandidate(), observed.persistedCandidate())) { + throw unavailable(); + } + } + + private static void requireBoundCandidate( + UUID requestId, VerifiedCandidateIdentity candidate, BoundTokenCandidate bound) { + if (bound == null + || !bound.requestId().equals(requestId) + || !bound.tokenHash().equals(candidate.tokenSha256()) + || !bound.signerGeneration().equals(candidate.signerGeneration()) + || !bound.kid().equals(candidate.kid())) { + throw unavailable(); + } + } + + private static void requirePersistedCandidate( + InvocationIdentity initial, + VerifiedCandidateIdentity candidateIdentity, + PendingRegistryCandidate persisted) { + if (persisted == null + || !persisted.identity().equals(initial.pending().identity()) + || !persisted.authoritySnapshot().equals(initial.pending().authoritySnapshot()) + || !persisted.tokenHash().equals(candidateIdentity.tokenSha256()) + || !persisted.kid().equals(candidateIdentity.kid()) + || !persisted.signerGeneration().equals(candidateIdentity.signerGeneration()) + || !persisted.identity().tokenJti().equals(candidateIdentity.jti()) + || persisted.identity().issuedAtEpochSecond() != candidateIdentity.issuedAtEpochSecond() + || persisted.identity().notBeforeEpochSecond() != candidateIdentity.notBeforeEpochSecond() + || persisted.expiresAtEpochSecond() != candidateIdentity.expiresAtEpochSecond() + || (initial.pending().persistedCandidate().isPresent() + && !samePersistedCandidate( + initial.pending().persistedCandidate(), Optional.of(persisted))) + || !matchesEvidenceBundleReference( + initial.pending(), persisted.evidenceBundleReference())) { + throw unavailable(); + } + } + + private static boolean samePersistedCandidate( + Optional expected, Optional observed) { + if (expected.isEmpty() || observed.isEmpty()) return expected.isEmpty() && observed.isEmpty(); + PendingRegistryCandidate left = expected.orElseThrow(); + PendingRegistryCandidate right = observed.orElseThrow(); + return left.identity().equals(right.identity()) + && left.tokenHash().equals(right.tokenHash()) + && left.kid().equals(right.kid()) + && left.signerGeneration().equals(right.signerGeneration()) + && left.expiresAtEpochSecond() == right.expiresAtEpochSecond() + && left.authoritySnapshot().equals(right.authoritySnapshot()) + && left.evidenceBundleReference().equals(right.evidenceBundleReference()) + && Arrays.equals(left.canonicalRecordBytes(), right.canonicalRecordBytes()); + } + + private static void requireOpenedCandidate( + PendingSigningIdentity pending, PendingCandidateCredential opened) { + PendingRegistryCandidate persisted = + pending.persistedCandidate().orElseThrow(AccountGameplayDelegationSigner::unavailable); + SealedCandidateObservation sealed = opened.sealedCandidate(); + long expectedExpiryMillis; + try { + expectedExpiryMillis = Math.multiplyExact(persisted.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException invalidExpiry) { + throw unavailable(); + } + if (!persisted.identity().operationId().equals(sealed.operationId()) + || !persisted.identity().requestId().equals(sealed.requestId()) + || !persisted + .evidenceBundleReference() + .canonicalSha256() + .equals(sealed.authorityEvidenceBundleSha256()) + || persisted.authoritySnapshot().issuanceFence() != sealed.issuanceFence() + || expectedExpiryMillis != sealed.responseRecoveryExpiryEpochMillis()) { + throw unavailable(); + } + } + + private static void requirePersistedCandidateSigner( + InvocationIdentity initial, PendingRegistryCandidate persisted) { + AccountMountedJwtSignerBundle.ExpectedIdentity signer = + initial.currentSigner().expectedIdentity(); + PendingSigningIdentity pending = initial.pending(); + if (!persisted.identity().equals(pending.identity()) + || !persisted.authoritySnapshot().equals(pending.authoritySnapshot()) + || !persisted + .evidenceBundleReference() + .canonicalSha256() + .equals(pending.evidenceBundle().canonicalSha256()) + || !persisted.kid().equals(signer.kid()) + || !persisted.signerGeneration().equals(signer.generation()) + || !persisted.tokenHash().matches("[0-9a-f]{64}") + || persisted.expiresAtEpochSecond() != pending.identity().expiresAtEpochSecond()) { + throw unavailable(); + } + } + + private static VerifiedCandidateIdentity candidateIdentity( + PendingSigningIdentity pending, AccountMountedJwtSignerBundle.SignedDelegationDigest digest) { + if (!digest.issuanceOperationId().equals(pending.identity().operationId()) + || !digest.requestId().equals(pending.identity().requestId()) + || !digest.jti().equals(pending.identity().tokenJti())) { + throw unavailable(); + } + return new VerifiedCandidateIdentity( + digest.issuanceOperationId(), + digest.requestId(), + digest.jti(), + digest.kid(), + digest.signerGeneration(), + digest.issuedAtEpochSecond(), + digest.notBeforeEpochSecond(), + digest.expiresAtEpochSecond(), + digest.compactTokenSha256()); + } + + private static VerifiedCandidateIdentity candidateIdentity( + PendingSigningIdentity pending, PendingRegistryCandidate persisted) { + if (!persisted.identity().equals(pending.identity())) throw unavailable(); + return new VerifiedCandidateIdentity( + persisted.identity().operationId(), + persisted.identity().requestId(), + persisted.identity().tokenJti(), + persisted.kid(), + persisted.signerGeneration(), + persisted.identity().issuedAtEpochSecond(), + persisted.identity().notBeforeEpochSecond(), + persisted.expiresAtEpochSecond(), + persisted.tokenHash()); + } + + private static boolean matchesEvidenceBundleReference( + PendingSigningIdentity pending, EvidenceBundleReference actual) { + Object referenceValue = pending.evidenceBundle().fields().get("bundleRef"); + if (!(referenceValue instanceof Map reference)) { + return false; + } + return Objects.equals(reference.get("bundleVersion"), actual.bundleVersion()) + && Objects.equals(reference.get("sourceVersion"), actual.sourceVersion()) + && Objects.equals(reference.get("sourceFence"), actual.sourceFence()) + && Objects.equals(reference.get("linearization"), actual.linearization()) + && pending.evidenceBundle().canonicalSha256().equals(actual.canonicalSha256()); + } + + private static void requireSealedCandidate( + UUID requestId, PendingSigningIdentity pending, SealedCandidateObservation sealed) { + final long immutableExpiryMillis; + try { + immutableExpiryMillis = Math.multiplyExact(pending.identity().expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException invalidExpiry) { + throw unavailable(); + } + if (sealed == null + || !sealed.requestId().equals(requestId) + || !sealed.operationId().equals(pending.identity().operationId()) + || !sealed + .authorityEvidenceBundleSha256() + .equals(pending.evidenceBundle().canonicalSha256()) + || sealed.issuanceFence() != pending.authoritySnapshot().issuanceFence() + || sealed.responseRecoveryExpiryEpochMillis() != immutableExpiryMillis) { + throw unavailable(); + } + } + + private static String exactAscii(byte[] compactJwt) { + if (compactJwt == null + || compactJwt.length == 0 + || compactJwt.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + throw unavailable(); + } + String value = new String(compactJwt, StandardCharsets.US_ASCII); + if (!Arrays.equals(compactJwt, value.getBytes(StandardCharsets.US_ASCII))) { + throw unavailable(); + } + return value; + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw AccountGameplayDelegationSigner.unavailable(); + } + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + private static SigningUnavailableException unavailable() { + return new SigningUnavailableException(); + } + + private record CurrentSigner( + AccountJwtSignerDesiredStateRepository.Binding binding, + TrustFence trust, + AccountJwtJwksApiBinding.ParsedBinding api, + CommittedSignerEvidence evidence, + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity) {} + + private record InvocationIdentity( + CurrentSigner currentSigner, + PendingSigningIdentity pending, + PendingCandidateCredential resumedCandidate) { + @Override + public String toString() { + return "InvocationIdentity[redacted]"; + } + } + + private record VerifiedCandidateIdentity( + UUID operationId, + UUID requestId, + UUID jti, + String kid, + String signerGeneration, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String tokenSha256) { + private VerifiedCandidateIdentity { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(jti); + Objects.requireNonNull(kid); + Objects.requireNonNull(signerGeneration); + Objects.requireNonNull(tokenSha256); + if (!tokenSha256.matches("[0-9a-f]{64}")) throw unavailable(); + } + } + + /** + * Signer-produced evidence that one exact pending candidate passed local cryptographic and + * profile validation, was durably bound, sealed, and read back under unchanged owner fences. This + * is neither an issuance receipt nor authority to transition the registry to COMMITTED. + */ + public static final class PendingCandidateVerificationProof { + private final VerifiedPendingIdentity identity; + private final AccountAuthoritySnapshot authoritySnapshot; + private final EvidenceBundleReference evidenceBundleReference; + private final String tokenSha256; + private final String canonicalRegistryRecordSha256; + private final AuthenticatedSignerCorrespondence signerCorrespondence; + private final SealedCandidateObservation sealedCandidate; + + private PendingCandidateVerificationProof( + VerifiedPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + EvidenceBundleReference evidenceBundleReference, + String tokenSha256, + String canonicalRegistryRecordSha256, + AuthenticatedSignerCorrespondence signerCorrespondence, + SealedCandidateObservation sealedCandidate) { + this.identity = Objects.requireNonNull(identity); + this.authoritySnapshot = Objects.requireNonNull(authoritySnapshot); + this.evidenceBundleReference = Objects.requireNonNull(evidenceBundleReference); + this.tokenSha256 = Objects.requireNonNull(tokenSha256); + this.canonicalRegistryRecordSha256 = Objects.requireNonNull(canonicalRegistryRecordSha256); + this.signerCorrespondence = Objects.requireNonNull(signerCorrespondence); + this.sealedCandidate = Objects.requireNonNull(sealedCandidate); + final long immutableExpiryMillis; + try { + immutableExpiryMillis = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException invalidExpiry) { + throw unavailable(); + } + if (!identity.operationId().equals(sealedCandidate.operationId()) + || !identity.requestId().equals(sealedCandidate.requestId()) + || !identity.accountId().equals(authoritySnapshot.accountId()) + || !evidenceBundleReference + .canonicalSha256() + .equals(sealedCandidate.authorityEvidenceBundleSha256()) + || authoritySnapshot.issuanceFence() != sealedCandidate.issuanceFence() + || immutableExpiryMillis != sealedCandidate.responseRecoveryExpiryEpochMillis() + || !"COMMITTED".equals(signerCorrespondence.promotionStatus()) + || !signerCorrespondence.privatePromotionDispatched() + || !signerCorrespondence + .promotionOperationId() + .equals(signerCorrespondence.privatePromotionOperationId()) + || !signerCorrespondence + .promotionOperationId() + .equals(signerCorrespondence.publicPromotionOperationId()) + || !signerCorrespondence + .generationOperationId() + .equals(signerCorrespondence.privatePromotionGenerationOperationId()) + || signerCorrespondence + .durableActive() + .filter( + active -> + active.generation().equals(signerCorrespondence.targetGeneration()) + && active.kid().equals(signerCorrespondence.targetKid())) + .isEmpty() + || signerCorrespondence + .publishedActive() + .filter( + active -> + active.generation().equals(signerCorrespondence.targetGeneration()) + && active.kid().equals(signerCorrespondence.targetKid())) + .isEmpty() + || signerCorrespondence + .promotionPrivateObservedResourceVersion() + .filter(signerCorrespondence.privatePromotionObservedResourceVersion()::equals) + .isEmpty() + || signerCorrespondence + .promotionPrivateReceiptDigest() + .filter(signerCorrespondence.privatePromotionReceiptDigest()::equals) + .isEmpty() + || signerCorrespondence + .activeJwksObservedResourceVersion() + .filter(signerCorrespondence.observedPublicResourceVersion()::equals) + .isEmpty() + || signerCorrespondence + .activeJwksPublicDataDigest() + .filter(signerCorrespondence.publicDataDigest()::equals) + .isEmpty() + || signerCorrespondence + .activeJwksReceiptDigest() + .filter(signerCorrespondence.publicReceiptDigest()::equals) + .isEmpty() + || !signerCorrespondence + .publicConfigMapUid() + .equals(signerCorrespondence.publicJwksSourceIdentity().configMapUid()) + || !tokenSha256.matches("[0-9a-f]{64}") + || !canonicalRegistryRecordSha256.matches("[0-9a-f]{64}") + || !evidenceBundleReference.canonicalSha256().matches("[0-9a-f]{64}")) { + throw unavailable(); + } + } + + public VerifiedPendingIdentity identity() { + return identity; + } + + public UUID operationId() { + return identity.operationId(); + } + + public UUID requestId() { + return identity.requestId(); + } + + public UUID accountId() { + return identity.accountId(); + } + + public UUID tokenJti() { + return identity.tokenJti(); + } + + public long issuedAtEpochSecond() { + return identity.issuedAtEpochSecond(); + } + + public long notBeforeEpochSecond() { + return identity.notBeforeEpochSecond(); + } + + public long expiresAtEpochSecond() { + return identity.expiresAtEpochSecond(); + } + + public long issuanceFence() { + return authoritySnapshot.issuanceFence(); + } + + public AccountAuthoritySnapshot authoritySnapshot() { + return authoritySnapshot; + } + + public UUID signerOperationId() { + return signerCorrespondence.generationOperationId(); + } + + public String signerKid() { + return signerCorrespondence.targetKid(); + } + + public String signerGeneration() { + return signerCorrespondence.targetGeneration(); + } + + public EvidenceBundleReference evidenceBundleReference() { + return evidenceBundleReference; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String canonicalRegistryRecordSha256() { + return canonicalRegistryRecordSha256; + } + + public AuthenticatedSignerCorrespondence signerCorrespondence() { + return signerCorrespondence; + } + + public SealedCandidateObservation sealedCandidate() { + return sealedCandidate; + } + + @Override + public String toString() { + return "PendingCandidateVerificationProof[redacted]"; + } + } + + /** Exact immutable pending identity read back from Account's issuance owner. */ + public record VerifiedPendingIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + public VerifiedPendingIdentity { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(callerWorkload); + Objects.requireNonNull(callerContextId); + Objects.requireNonNull(requestDigest); + Objects.requireNonNull(tokenJti); + } + + @Override + public String toString() { + return "VerifiedPendingIdentity[redacted]"; + } + } + + /** Public, byte-free projection of the exact authenticated committed signer source evidence. */ + public record AuthenticatedSignerCorrespondence( + AccountJwtSignerDesiredStateRepository.Binding binding, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + SourceIdentity publicJwksSourceIdentity, + long desiredStateRecordVersion, + java.util.Optional durableActive, + java.util.Optional publishedActive, + UUID promotionOperationId, + String promotionRequestDigest, + long promotionExpectedRecordVersion, + java.util.Optional expectedPreviousActive, + java.util.Optional expectedPreviousPublicKeyFingerprint, + java.util.Optional expectedPublishedActive, + String promotionStatus, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + long generationDesiredStateVersion, + String privateSecretName, + String secretUid, + String expectedPriorSecretResourceVersion, + String observedSecretResourceVersion, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + String privatePromotionObservedResourceVersion, + String privatePromotionReceiptDigest, + String promotionApiBindingDigest, + String promotionApiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String priorPublicResourceVersion, + String observedPublicResourceVersion, + String publicDataDigest, + String publicReceiptDigest, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + boolean privatePromotionDispatched, + UUID privatePromotionOperationId, + UUID privatePromotionGenerationOperationId, + UUID publicPromotionOperationId, + java.util.Optional promotionPrivateObservedResourceVersion, + java.util.Optional promotionPrivateReceiptDigest, + java.util.Optional activeJwksObservedResourceVersion, + java.util.Optional activeJwksPublicDataDigest, + java.util.Optional activeJwksReceiptDigest) { + public AuthenticatedSignerCorrespondence { + Objects.requireNonNull(binding); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(apiBindingDigest); + Objects.requireNonNull(apiConfigRevision); + Objects.requireNonNull(publicJwksSourceIdentity); + Objects.requireNonNull(durableActive); + Objects.requireNonNull(publishedActive); + Objects.requireNonNull(promotionOperationId); + Objects.requireNonNull(expectedPreviousActive); + Objects.requireNonNull(expectedPreviousPublicKeyFingerprint); + Objects.requireNonNull(expectedPublishedActive); + Objects.requireNonNull(generationOperationId); + Objects.requireNonNull(privatePromotionOperationId); + Objects.requireNonNull(privatePromotionGenerationOperationId); + Objects.requireNonNull(publicPromotionOperationId); + Objects.requireNonNull(promotionPrivateObservedResourceVersion); + Objects.requireNonNull(promotionPrivateReceiptDigest); + Objects.requireNonNull(activeJwksObservedResourceVersion); + Objects.requireNonNull(activeJwksPublicDataDigest); + Objects.requireNonNull(activeJwksReceiptDigest); + } + + @Override + public String toString() { + return "AuthenticatedSignerCorrespondence[redacted]"; + } + } + + /** Non-authorizing metadata returned after the candidate and sealed envelope commit. */ + record CandidateOutcome( + UUID operationId, + UUID requestId, + String tokenSha256, + String signerGeneration, + String signerKid, + SealedCandidateObservation sealedCandidate, + PendingCandidateVerificationProof verificationProof) { + CandidateOutcome { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(tokenSha256); + Objects.requireNonNull(signerGeneration); + Objects.requireNonNull(signerKid); + Objects.requireNonNull(sealedCandidate); + Objects.requireNonNull(verificationProof); + if (!operationId.equals(verificationProof.operationId()) + || !requestId.equals(verificationProof.requestId()) + || !tokenSha256.equals(verificationProof.tokenSha256()) + || !signerGeneration.equals(verificationProof.signerGeneration()) + || !signerKid.equals(verificationProof.signerKid()) + || !sealedCandidate.equals(verificationProof.sealedCandidate())) { + throw unavailable(); + } + } + + @Override + public String toString() { + return "CandidateOutcome[redacted]"; + } + } + + static final class SigningUnavailableException extends IllegalStateException { + private SigningUnavailableException() { + super("Account gameplay delegation candidate is unavailable or ambiguous"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java new file mode 100644 index 0000000000..9f50020a50 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java @@ -0,0 +1,257 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.common.security.AccountJwtExactValues; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired Account Coordination Redis boundary for non-authorizing Game Session delegation records. + * + *

This registry writes the exact PENDING projection read from Account's durable issuance + * repository and exposes a separate package-scoped COMMITTED-to-ACTIVE transition for the committed + * owner. Both use the pinned Account Coordination client and exact readback/WAITAOF. It is not a + * token validator, Authenticate/HMAC path, signer-promotion, readiness, or response-recovery API; + * active owner metadata does not itself authorize player access or expose a credential. + */ +public final class AccountGameplayDelegationTokenRegistry { + private static final long MAX_CLEANUP_MARGIN_MILLIS = 300_000L; + + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final TransactionTemplate pendingCandidateReadTransaction; + private final AccountGameplayDelegationRedisClient coordinationRedis; + private final Clock clock; + private final long maxEncodedBytes; + private final long cleanupMarginMillis; + + public AccountGameplayDelegationTokenRegistry( + AccountGameplayDelegationIssuanceRepository issuanceRepository, + PlatformTransactionManager transactionManager, + AccountGameplayDelegationRedisClient coordinationRedis, + Clock clock, + long maxEncodedBytes, + long cleanupMarginMillis) { + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account issuance repository is required"); + this.pendingCandidateReadTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.coordinationRedis = + Objects.requireNonNull(coordinationRedis, "Account Coordination Redis client is required"); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + if (maxEncodedBytes <= 0L + || maxEncodedBytes > GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES) { + throw new IllegalArgumentException("Registry byte bound exceeds the finite profile ceiling"); + } + if (cleanupMarginMillis < 0L || cleanupMarginMillis > MAX_CLEANUP_MARGIN_MILLIS) { + throw new IllegalArgumentException("Registry cleanup margin is outside its finite bound"); + } + this.maxEncodedBytes = maxEncodedBytes; + this.cleanupMarginMillis = cleanupMarginMillis; + } + + /** + * CAS-writes the exact pending projection loaded from committed Account SQL state and reads it + * back byte-for-byte. The signed JWT is never accepted here, logged, returned, or stored. + */ + public AccountGameplayDelegationRedisClient.PendingRegistrationReceipt registerPending( + UUID requestId) { + Objects.requireNonNull(requestId, "Request ID is required"); + requireNoAccountTransaction( + "Pending registry work must not join an ambient Account transaction"); + PendingRegistryCandidate candidate = + pendingCandidateReadTransaction.execute( + status -> issuanceRepository.readPendingRegistryCandidate(requestId)); + requireNoAccountTransaction("Pending candidate SQL transaction must close before Redis work"); + if (candidate == null) { + throw new IllegalStateException("Durable pending registry candidate is unavailable"); + } + var identity = candidate.identity(); + byte[] recordBytes = candidate.canonicalRecordBytes(); + if (recordBytes.length == 0 || recordBytes.length > maxEncodedBytes) { + throw new IllegalArgumentException("Pending registry record exceeds its finite byte bound"); + } + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.decode(recordBytes, maxEncodedBytes); + if (!"pending".equals(record.state()) + || !requestId.toString().equals(record.requestId()) + || !candidate.tokenHash().equals(record.tokenHash()) + || !candidate.kid().equals(record.kid()) + || !candidate.signerGeneration().equals(record.signerGeneration()) + || !identity.operationId().toString().equals(record.operationId()) + || !identity.requestId().toString().equals(record.requestId()) + || !identity.requestDigest().equals(record.requestDigest()) + || !identity.accountId().toString().equals(record.accountId()) + || !identity.tokenJti().toString().equals(record.jti()) + || identity.issuedAtEpochSecond() != record.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != record.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != record.expiresAtEpochSecond() + || candidate.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || !candidate.authoritySnapshot().accountId().equals(identity.accountId()) + || record.issuanceFence() != candidate.authoritySnapshot().issuanceFence() + || !candidate.evidenceBundleReference().equals(record.evidenceBundleReference()) + || !authorityTupleMatches(record.fields(), candidate) + || !authoritySourceVersionsMatch(record.fields(), candidate)) { + throw new IllegalStateException( + "Durable pending registry candidate does not match its record"); + } + + long nowMillis = clock.millis(); + if (nowMillis < 0L) throw new IllegalStateException("Clock returned a negative instant"); + long expiryMillis; + try { + expiryMillis = Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L); + expiryMillis = Math.addExact(expiryMillis, cleanupMarginMillis); + if (Math.subtractExact(expiryMillis, nowMillis) <= 0L) { + throw new IllegalArgumentException("Pending token is expired"); + } + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Pending registry TTL cannot be represented"); + } + + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt receipt = + coordinationRedis.registerPending(candidate.tokenHash(), recordBytes, expiryMillis); + requireExactReceipt(receipt, candidate, recordBytes, expiryMillis); + return receipt; + } + + /** + * Requires the exact ACTIVE Redis projection for an already-current COMMITTED Account owner read. + * This read grants no authority by itself and performs no registry activation. + */ + public AccountGameplayDelegationRedisClient.ActiveRegistryReadback requireExactActiveRecord( + CommittedCandidateVerificationData committedCandidate) { + Objects.requireNonNull(committedCandidate, "Current COMMITTED Account evidence is required"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Active registry reads must not run under Account SQL locks"); + } + AccountGameplayDelegationRedisClient.ActiveRegistryReadback active = + coordinationRedis.readActiveRecord(committedCandidate.tokenSha256()); + var identity = committedCandidate.identity(); + if (!committedCandidate.tokenSha256().equals(active.tokenHash()) + || !identity.accountId().toString().equals(active.accountId()) + || !identity.tokenJti().toString().equals(active.jti()) + || identity.expiresAtEpochSecond() != active.tokenExpiryEpochSecond() + || committedCandidate.registryAbsoluteExpiryMillis() != active.absoluteExpiryMillis() + || !committedCandidate + .canonicalRegistryRecordSha256() + .equals(active.canonicalPendingRecordSha256())) { + throw new IllegalStateException( + "ACTIVE registry state differs from the exact current COMMITTED Account issuance"); + } + return active; + } + + /** + * Performs the committed owner's exact Redis transition without holding Account SQL locks. The + * caller must obtain this repository-issued value in its own bounded transaction and revalidate + * current Account/signer ownership after this network operation. + */ + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt activateCommittedCandidate( + CommittedCandidateVerificationData committedCandidate) { + Objects.requireNonNull( + committedCandidate, "Repository-produced COMMITTED candidate evidence is required"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account transaction must not span Coordination Redis work"); + } + var identity = committedCandidate.identity(); + long nowMillis = clock.millis(); + if (nowMillis <= 0L + || Math.floorDiv(nowMillis, 1_000L) >= identity.expiresAtEpochSecond() + || committedCandidate.registryAbsoluteExpiryMillis() <= nowMillis) { + throw new IllegalStateException("Committed Account issuance is expired or unavailable"); + } + return coordinationRedis.activateCommittedCandidate(committedCandidate); + } + + private static void requireExactReceipt( + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt receipt, + PendingRegistryCandidate candidate, + byte[] canonicalRecordBytes, + long absoluteExpiryMillis) { + var identity = candidate.identity(); + if (receipt == null + || !receipt + .tokenKey() + .equals(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + candidate.tokenHash()) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals(receipt.aclIdentity()) + || !receipt.canonicalRecordSha256().equals(sha256(canonicalRecordBytes)) + || !receipt.operationId().equals(identity.operationId().toString()) + || !receipt.requestId().equals(identity.requestId().toString()) + || !receipt.requestDigest().equals(identity.requestDigest()) + || !receipt.accountId().equals(identity.accountId().toString()) + || !receipt.tokenJti().equals(identity.tokenJti().toString()) + || !receipt.tokenHash().equals(candidate.tokenHash()) + || !receipt.kid().equals(candidate.kid()) + || !receipt.signerGeneration().equals(candidate.signerGeneration()) + || receipt.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || receipt.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || receipt.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || receipt.issuanceFence() != candidate.authoritySnapshot().issuanceFence() + || receipt.registryVersion() != 1L + || !receipt.evidenceBundleReference().equals(candidate.evidenceBundleReference()) + || receipt.absoluteExpiryMillis() != absoluteExpiryMillis + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L) { + throw new IllegalStateException("Account pending registration receipt is inconsistent"); + } + } + + private static void requireNoAccountTransaction(String message) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(message); + } + } + + private static boolean authorityTupleMatches( + Map fields, PendingRegistryCandidate candidate) { + Object value = fields.get("authorityTuple"); + if (!(value instanceof Map tuple)) return false; + Map expected = + GameSessionAccountDelegationProfile.authorityTuple( + candidate.authoritySnapshot().issuerGeneration(), + candidate.authoritySnapshot().accountGeneration(), + candidate.authoritySnapshot().accountSecurityCutoff()); + return expected.equals(tuple) + && fields.get("membershipVersion") instanceof Map membershipVersion + && membershipVersion.isEmpty(); + } + + private static boolean authoritySourceVersionsMatch( + Map fields, PendingRegistryCandidate candidate) { + Object value = fields.get("authoritySourceVersions"); + if (!(value instanceof Map versions)) return false; + return positive(versions.get("issuerSourceVersion")) + == candidate.authoritySnapshot().issuerSourceVersion() + && positive(versions.get("accountSourceVersion")) + == candidate.authoritySnapshot().accountSourceVersion() + && positive(versions.get("issuanceFenceSourceVersion")) + == candidate.authoritySnapshot().issuanceFenceSourceVersion(); + } + + private static long positive(Object value) { + try { + return AccountJwtExactValues.positiveDecimalCounter(value).longValueExact(); + } catch (IllegalArgumentException | ArithmeticException ex) { + return -1L; + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySource.java new file mode 100644 index 0000000000..7aa2ed2439 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySource.java @@ -0,0 +1,335 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +/** + * Reads Account's dedicated mounted LOGIN request-digest keyring without activating it as a bean. + * The supplied mount path is a trust root and is never used for writes. + */ +public final class AccountMountedGameplayCredentialDigestKeySource + implements AccountGameplayCredentialRequestDigestKeySource { + static final int KEY_BYTES = 32; + static final int MAX_MANIFEST_BYTES = 16 * 1024; + static final int MAX_RETAINED_KEYS = 8; + private static final String MANIFEST_HEADER = + "firemud-account-credential-request-digest-keyring-v1"; + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,32}"); + + private final Path mountRoot; + private final Clock clock; + + public AccountMountedGameplayCredentialDigestKeySource(Path mountRoot, Clock clock) { + this.mountRoot = Objects.requireNonNull(mountRoot, "Account digest-key mount path is required"); + if (!mountRoot.isAbsolute()) { + throw new IllegalArgumentException("Account digest-key mount path must be absolute"); + } + this.clock = Objects.requireNonNull(clock, "Account digest-key clock is required"); + } + + /** + * Reloads the mounted manifest for each lookup and requires the active key's horizon to be live. + */ + @Override + public CredentialDigestKey currentKey() { + try (Snapshot snapshot = readCurrent()) { + return snapshot.currentKey(clock.instant()); + } + } + + /** Reloads the mounted manifest and resolves exactly the requested live active or retained ID. */ + @Override + public CredentialDigestKey requireKey(String keyId) { + try (Snapshot snapshot = readCurrent()) { + return snapshot.requireKey(keyId, clock.instant()); + } + } + + private Snapshot readCurrent() { + byte[] contents = null; + try { + Path resolvedRoot = mountRoot.toRealPath(); + if (!Files.isDirectory(resolvedRoot, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + // Kubernetes projected Secrets use key -> ..data/key and ..data -> .. symlinks. + // Follow that projection only when its resolved regular file stays inside this trust root. + Path manifest = resolvedRoot.resolve("keyring").toRealPath(); + if (!manifest.startsWith(resolvedRoot) + || !Files.isRegularFile(manifest, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + contents = readBounded(manifest); + return parse(contents); + } catch (KeyUnavailableException ex) { + throw ex; + } catch (Exception ex) { + throw unavailable(); + } finally { + wipe(contents); + } + } + + private static byte[] readBounded(Path path) throws IOException { + byte[] snapshot = new byte[MAX_MANIFEST_BYTES + 1]; + try { + int total = 0; + try (SeekableByteChannel channel = + Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { + ByteBuffer buffer = ByteBuffer.wrap(snapshot); + while (true) { + int count = channel.read(buffer); + if (count < 0) { + break; + } + if (count == 0) { + continue; + } + if (count > MAX_MANIFEST_BYTES - total) { + throw unavailable(); + } + total += count; + } + } + return Arrays.copyOf(snapshot, total); + } finally { + wipe(snapshot); + } + } + + private static Snapshot parse(byte[] contents) { + if (contents.length == 0 || contents.length > MAX_MANIFEST_BYTES) { + throw unavailable(); + } + String text; + try { + text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(contents)) + .toString(); + } catch (CharacterCodingException ex) { + throw unavailable(); + } + if (text.indexOf('\r') >= 0 || text.indexOf('\0') >= 0 || text.startsWith("\uFEFF")) { + throw unavailable(); + } + for (int index = 0; index < text.length(); index++) { + char value = text.charAt(index); + if (value > 0x7e || (value < 0x20 && value != '\n')) { + throw unavailable(); + } + } + + String normalized = text.endsWith("\n") ? text.substring(0, text.length() - 1) : text; + if (normalized.isEmpty() || normalized.endsWith("\n")) { + throw unavailable(); + } + String[] lines = normalized.split("\n", -1); + if (!MANIFEST_HEADER.equals(lines[0]) || lines.length < 2) { + throw unavailable(); + } + + Map keys = new HashMap<>(); + Set seenIds = new HashSet<>(); + KeyEntry active = null; + int retainedCount = 0; + try { + for (int index = 1; index < lines.length; index++) { + String[] fields = lines[index].split(" ", -1); + if (fields.length != 4) { + throw unavailable(); + } + boolean isActive = "active".equals(fields[0]); + boolean isRetained = "retained".equals(fields[0]); + if (!isActive && !isRetained) { + throw unavailable(); + } + if (isActive) { + if (active != null || index != 1) { + throw unavailable(); + } + } else { + if (active == null || ++retainedCount > MAX_RETAINED_KEYS) { + throw unavailable(); + } + } + + Instant retainedUntil = parseEpochMillis(fields[2]); + KeyEntry entry = parseEntry(fields[1], fields[3], retainedUntil); + if (!seenIds.add(entry.keyId())) { + entry.destroy(); + throw unavailable(); + } + keys.put(entry.keyId(), entry); + if (isActive) { + active = entry; + } + } + if (active == null) { + throw unavailable(); + } + return new Snapshot(active, keys); + } catch (RuntimeException ex) { + keys.values().forEach(KeyEntry::destroy); + throw ex instanceof KeyUnavailableException ? ex : unavailable(); + } + } + + private static Instant parseEpochMillis(String value) { + if (value == null || !value.matches("[1-9][0-9]{0,18}")) { + throw unavailable(); + } + try { + return Instant.ofEpochMilli(Long.parseLong(value)); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + + private static KeyEntry parseEntry(String keyId, String encodedKey, Instant retainedUntil) { + if (keyId == null || !KEY_ID.matcher(keyId).matches() || encodedKey == null) { + throw unavailable(); + } + byte[] keyMaterial = null; + try { + keyMaterial = Base64.getUrlDecoder().decode(encodedKey); + if (keyMaterial.length != KEY_BYTES + || !Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(keyMaterial) + .equals(encodedKey)) { + throw unavailable(); + } + return new KeyEntry(keyId, keyMaterial, retainedUntil); + } catch (IllegalArgumentException ex) { + throw unavailable(); + } finally { + wipe(keyMaterial); + } + } + + private static KeyUnavailableException unavailable() { + return new KeyUnavailableException(); + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + @Override + public String toString() { + return "AccountMountedGameplayCredentialDigestKeySource[redacted]"; + } + + private static final class Snapshot implements AutoCloseable { + private final KeyEntry active; + private final Map keys; + + private Snapshot(KeyEntry active, Map keys) { + this.active = active; + this.keys = Map.copyOf(keys); + } + + private CredentialDigestKey currentKey(Instant now) { + if (!now.isBefore(active.retainedUntil())) { + throw unavailable(); + } + return active.toCredentialDigestKey(); + } + + private CredentialDigestKey requireKey(String keyId, Instant now) { + KeyEntry key = keyId == null ? null : keys.get(keyId); + if (key == null || !now.isBefore(key.retainedUntil())) { + throw unavailable(); + } + return key.toCredentialDigestKey(); + } + + @Override + public void close() { + keys.values().forEach(KeyEntry::destroy); + } + + @Override + public String toString() { + return "AccountMountedGameplayCredentialDigestKeySource.Snapshot[redacted]"; + } + } + + private static final class KeyEntry { + private final String keyId; + private final byte[] keyMaterial; + private final Instant retainedUntil; + + private KeyEntry(String keyId, byte[] keyMaterial, Instant retainedUntil) { + this.keyId = keyId; + this.keyMaterial = keyMaterial.clone(); + this.retainedUntil = retainedUntil; + } + + private String keyId() { + return keyId; + } + + private Instant retainedUntil() { + return retainedUntil; + } + + private CredentialDigestKey toCredentialDigestKey() { + byte[] keyCopy = keyMaterial.clone(); + try { + SecretKey key = new SecretKeySpec(keyCopy, "HmacSHA256"); + return new CredentialDigestKey(keyId, key, retainedUntil); + } finally { + wipe(keyCopy); + } + } + + private void destroy() { + wipe(keyMaterial); + } + + @Override + public String toString() { + return "AccountMountedGameplayCredentialDigestKeySource.KeyEntry[keyId=" + + keyId + + ", material=redacted]"; + } + } + + /** Retryable failure for absent, withdrawn, malformed, expired, or unreadable mounted keys. */ + public static final class KeyUnavailableException extends IllegalStateException { + private KeyUnavailableException() { + super("Account credential-request digest keyring is unavailable"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java new file mode 100644 index 0000000000..76e9a6e4cd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java @@ -0,0 +1,250 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Closed non-authorizing projections for the selected public-gameplay Account owner path. */ +public final class AccountSelectedGameplayAuthorityProjection { + public static final String TENANT_SCHEMA = "account-auth-tenant-generation-projection/v1"; + public static final String MEMBERSHIP_SCHEMA = "account-auth-membership-generation-projection/v1"; + public static final String TENANT_PREFIX = "session:auth:generation:tenant:"; + public static final String MEMBERSHIP_PREFIX = "session:auth:generation:membership:"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private final Map fields; + private final byte[] bytes; + + private AccountSelectedGameplayAuthorityProjection(Map fields) { + this.fields = Map.copyOf(fields); + this.bytes = canonical(fields); + if (bytes.length > AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES) { + throw new IllegalArgumentException("Selected Account authority projection exceeds its bound"); + } + } + + static AccountSelectedGameplayAuthorityProjection tenant( + TenantAuthorityEventV1Codec.Event event) { + Map value = + base( + TENANT_SCHEMA, + event.tenantId().toString(), + Long.toString(event.tenantAuthoritySourceVersion()), + event.outboxStreamKey(), + Long.toString(event.outboxSequence()), + new String(event.payload(), StandardCharsets.UTF_8)); + value.put("tenantAuthorityGeneration", Long.toString(event.tenantAuthorityGeneration())); + return decode(canonical(value), null, event.tenantId()); + } + + static AccountSelectedGameplayAuthorityProjection membership( + MembershipAuthorityEventV1Codec.MembershipEvent event) { + Objects.requireNonNull(event, "Canonical membership event is required"); + final long historicalSourceVersion; + try { + historicalSourceVersion = Long.parseLong(event.membershipAuthorityGeneration()); + } catch (NumberFormatException malformed) { + throw invalid(); + } + return membership(event, historicalSourceVersion); + } + + static AccountSelectedGameplayAuthorityProjection membership( + MembershipAuthorityEventV1Codec.MembershipEvent event, long sourceVersion) { + Map value = + base( + MEMBERSHIP_SCHEMA, + event.tenantId(), + Long.toString(sourceVersion), + event.outboxStreamKey(), + event.outboxSequence(), + event.canonicalJson()); + value.put("accountId", event.accountId()); + value.put("membershipAuthorityGeneration", event.membershipAuthorityGeneration()); + value.put("membershipVersion", event.membershipVersion().get(event.tenantId())); + return decode( + canonical(value), UUID.fromString(event.accountId()), UUID.fromString(event.tenantId())); + } + + /** Strict, no-alias parsing; the complete independently verified event is retained unchanged. */ + public static AccountSelectedGameplayAuthorityProjection decode( + byte[] bytes, UUID accountId, UUID tenantId) { + if (bytes == null + || bytes.length == 0 + || bytes.length > AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES) + throw invalid(); + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + Map fields = JSON.readValue(json, new TypeReference<>() {}); + boolean member = accountId != null; + Set expected = + member + ? Set.of( + "schemaVersion", + "accountId", + "tenantId", + "membershipAuthorityGeneration", + "membershipVersion", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent") + : Set.of( + "schemaVersion", + "tenantId", + "tenantAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + if (!fields.keySet().equals(expected) + || !Arrays.equals(bytes, canonical(fields)) + || !(member ? MEMBERSHIP_SCHEMA : TENANT_SCHEMA).equals(fields.get("schemaVersion")) + || !tenantId.toString().equals(fields.get("tenantId"))) throw invalid(); + positive(fields, "sourceVersion"); + positive(fields, "outboxSequence"); + if (member) { + positive(fields, "membershipAuthorityGeneration"); + positive(fields, "membershipVersion"); + var event = MembershipAuthorityEventV1Codec.verify(text(fields, "sourceEvent")); + if (!accountId.toString().equals(fields.get("accountId")) + || !event.canonicalJson().equals(fields.get("sourceEvent")) + || !event.accountId().equals(fields.get("accountId")) + || !event.tenantId().equals(fields.get("tenantId")) + || !event + .membershipAuthorityGeneration() + .equals(fields.get("membershipAuthorityGeneration")) + || !event + .membershipVersion() + .get(event.tenantId()) + .equals(fields.get("membershipVersion")) + // Account initializes these paired counters to 1 and the owning database guard + // requires them to advance together. The retained canonical event carries the + // historical generation, so it is the only source for this historical sourceVersion. + || !event.membershipAuthorityGeneration().equals(fields.get("sourceVersion")) + || !event.outboxStreamKey().equals(fields.get("outboxStreamKey")) + || !event.outboxSequence().equals(fields.get("outboxSequence"))) throw invalid(); + } else { + positive(fields, "tenantAuthorityGeneration"); + var event = + TenantAuthorityEventV1Codec.verify( + text(fields, "sourceEvent").getBytes(StandardCharsets.UTF_8)); + if (!event.tenantId().equals(tenantId) + || !Long.toString(event.tenantAuthorityGeneration()) + .equals(fields.get("tenantAuthorityGeneration")) + || !Long.toString(event.tenantAuthoritySourceVersion()) + .equals(fields.get("sourceVersion")) + || !event.outboxStreamKey().equals(fields.get("outboxStreamKey")) + || !Long.toString(event.outboxSequence()).equals(fields.get("outboxSequence"))) + throw invalid(); + } + return new AccountSelectedGameplayAuthorityProjection(fields); + } catch (java.nio.charset.CharacterCodingException | RuntimeException failure) { + throw invalid(); + } + } + + public String key() { + return fields.containsKey("accountId") + ? MEMBERSHIP_PREFIX + fields.get("accountId") + ":" + fields.get("tenantId") + : TENANT_PREFIX + fields.get("tenantId"); + } + + public byte[] canonicalBytes() { + return bytes.clone(); + } + + public BigInteger sequence() { + return positive(fields, "outboxSequence"); + } + + public BigInteger sourceVersion() { + return positive(fields, "sourceVersion"); + } + + public BigInteger generation() { + return positive( + fields, + fields.containsKey("accountId") + ? "membershipAuthorityGeneration" + : "tenantAuthorityGeneration"); + } + + public BigInteger membershipVersion() { + return positive(fields, "membershipVersion"); + } + + /** A source gap is not healed by installing an arbitrary latest-head value. */ + public void requireSuccessorOf(AccountSelectedGameplayAuthorityProjection prior) { + if (prior == null) { + if (!sequence().equals(BigInteger.ONE)) throw invalid(); + return; + } + if (!key().equals(prior.key())) throw invalid(); + if (Arrays.equals(bytes, prior.bytes)) return; + if (!sequence().equals(prior.sequence().add(BigInteger.ONE))) throw invalid(); + if (fields.containsKey("accountId")) { + BigInteger generationAdvance = generation().subtract(prior.generation()); + if (generationAdvance.signum() < 0 + || generationAdvance.compareTo(BigInteger.ONE) > 0 + || !sourceVersion().equals(generation()) + || !membershipVersion().equals(prior.membershipVersion().add(BigInteger.ONE))) + throw invalid(); + } else if (!generation().equals(prior.generation().add(BigInteger.ONE)) + || !sourceVersion().equals(prior.sourceVersion().add(BigInteger.ONE))) { + throw invalid(); + } + } + + private static Map base( + String schema, String tenant, String source, String stream, String sequence, String event) { + Map value = new LinkedHashMap<>(); + value.put("schemaVersion", schema); + value.put("tenantId", tenant); + value.put("sourceVersion", source); + value.put("outboxStreamKey", stream); + value.put("outboxSequence", sequence); + value.put("sourceEvent", event); + return value; + } + + private static BigInteger positive(Map fields, String key) { + String value = text(fields, key); + if (!value.matches("[1-9][0-9]*")) throw invalid(); + return new BigInteger(value); + } + + private static String text(Map fields, String key) { + if (!(fields.get(key) instanceof String value)) throw invalid(); + return value; + } + + private static byte[] canonical(Map fields) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields)); + } catch (Exception failure) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Selected Account authority projection is unavailable or contradictory"); + } +} diff --git a/services/account-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution b/services/account-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution new file mode 100644 index 0000000000..3e5dfa2660 --- /dev/null +++ b/services/account-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution @@ -0,0 +1,2 @@ +net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisScriptContribution +net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution diff --git a/services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql b/services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql new file mode 100644 index 0000000000..058ed771b4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql @@ -0,0 +1,273 @@ +-- Account-owned non-authorizing LOGIN issuance intent. This deliberately has no COMMITTED state: +-- the Account signer-promotion and current-authority projection proof required for activation do +-- not yet exist. The only mutable transition binds an exact signed-token identity once. +CREATE TABLE account_gameplay_delegation_issuance_operations ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid) ON DELETE RESTRICT, + caller_workload VARCHAR(256) NOT NULL, + caller_context_id UUID NOT NULL, + request_digest_version SMALLINT NOT NULL, + request_digest VARCHAR(64) NOT NULL, + token_jti UUID NOT NULL UNIQUE, + token_generation BIGINT NOT NULL DEFAULT 1, + issued_at_epoch_second BIGINT NOT NULL, + not_before_epoch_second BIGINT NOT NULL, + expires_at_epoch_second BIGINT NOT NULL, + authority_issuer_generation BIGINT NOT NULL, + authority_issuer_source_version BIGINT NOT NULL, + authority_account_generation BIGINT NOT NULL, + authority_account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + issuance_fence_source_version BIGINT NOT NULL, + authority_tuple_canonical_bytes BYTEA NOT NULL, + membership_version_canonical_bytes BYTEA NOT NULL, + authority_source_versions_canonical_bytes BYTEA NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'PENDING', + token_hash VARCHAR(64), + signer_kid VARCHAR(64), + signer_generation VARCHAR(19), + pending_registry_candidate_bytes BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_delegation_operation_ids_check + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND caller_context_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND caller_context_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND token_jti <> '00000000-0000-0000-0000-000000000000'::UUID + AND token_jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_gameplay_delegation_caller_check + CHECK (caller_workload ~ '^spiffe://firemud/ns/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$'), + CONSTRAINT account_gameplay_delegation_digest_check + CHECK (request_digest_version = 1 AND request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_gameplay_delegation_time_check + CHECK (token_generation = 1 AND issued_at_epoch_second > 0 + AND not_before_epoch_second > 0 AND not_before_epoch_second <= issued_at_epoch_second + AND expires_at_epoch_second > issued_at_epoch_second + AND expires_at_epoch_second - issued_at_epoch_second <= 300), + CONSTRAINT account_gameplay_delegation_authority_check + CHECK (authority_issuer_generation > 0 AND authority_issuer_source_version > 0 + AND authority_account_generation > 0 AND authority_account_source_version > 0 + AND issuance_fence > 0 AND issuance_fence_source_version > 0), + CONSTRAINT account_gameplay_delegation_profile_bytes_check + CHECK (octet_length(authority_tuple_canonical_bytes) BETWEEN 1 AND 4096 + AND convert_from(membership_version_canonical_bytes, 'UTF8') = '{}' + AND octet_length(authority_source_versions_canonical_bytes) BETWEEN 1 AND 4096), + CONSTRAINT account_gameplay_delegation_status_check CHECK (status = 'PENDING'), + CONSTRAINT account_gameplay_delegation_candidate_shape_check + CHECK ((token_hash IS NULL AND signer_kid IS NULL AND signer_generation IS NULL + AND pending_registry_candidate_bytes IS NULL) + OR (token_hash IS NOT NULL AND token_hash ~ '^[0-9a-f]{64}$' + AND signer_kid IS NOT NULL AND signer_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND signer_generation IS NOT NULL AND signer_generation ~ '^[1-9][0-9]{0,18}$' + AND pending_registry_candidate_bytes IS NOT NULL + AND octet_length(pending_registry_candidate_bytes) BETWEEN 1 AND 16384)) +); + +-- Insert and post-sign bind both lock and compare the existing Account authority sources. This +-- is intentionally the same issuer/account/fence model used by AccountAuthorityGenerationRepository. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_delegation_authority_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + source_issuer_generation BIGINT; + source_issuer_source_version BIGINT; + current_issuer_sequence BIGINT; + current_issuer_stream VARCHAR(2048); + current_account_generation BIGINT; + current_account_source_version BIGINT; + source_account_generation BIGINT; + source_account_source_version BIGINT; + current_account_sequence BIGINT; + current_account_stream VARCHAR(2048); + current_account_cutoff_generation BIGINT; + current_account_cutoff_stream VARCHAR(2048); + current_account_cutoff_sequence BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + expected_authority_tuple TEXT; +BEGIN + -- Keep the owner lock order: Account row, issuer/account generations and fence, then the + -- source rows whose exact optional cutoff is carried by the immutable pending intent. + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account gameplay delegation Account source is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence + INTO current_issuer_stream, source_issuer_generation, source_issuer_source_version, + current_issuer_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:issuer/firemud-account-service' + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence, + cutoff_generation, cutoff_stream_key, cutoff_sequence + INTO current_account_stream, source_account_generation, source_account_source_version, + current_account_sequence, current_account_cutoff_generation, + current_account_cutoff_stream, current_account_cutoff_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + FOR UPDATE; + + IF current_account_sequence = 0 + AND current_account_cutoff_generation IS NULL + AND current_account_cutoff_stream IS NULL + AND current_account_cutoff_sequence IS NULL THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":' || source_account_generation::TEXT + || ',"issuerAuthGeneration":' || source_issuer_generation::TEXT + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + ELSIF current_account_sequence > 0 + AND current_account_cutoff_generation = source_account_generation + AND current_account_cutoff_stream = current_account_stream + AND current_account_cutoff_sequence = current_account_sequence THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":' || source_account_generation::TEXT + || ',"accountSecurityCutoff":{"accountAuthorityGeneration":"' + || current_account_cutoff_generation::TEXT || '","outboxSequence":"' + || current_account_cutoff_sequence::TEXT || '","outboxStreamKey":"' + || current_account_cutoff_stream || '"},"issuerAuthGeneration":' + || source_issuer_generation::TEXT + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + END IF; + + IF current_issuer_generation IS NULL OR current_account_generation IS NULL + OR current_issuance_fence IS NULL OR current_issuer_stream IS NULL + OR current_account_stream IS NULL OR current_issuer_sequence IS NULL + OR current_account_sequence IS NULL OR source_issuer_generation IS NULL + OR source_issuer_source_version IS NULL OR source_account_generation IS NULL + OR source_account_source_version IS NULL OR current_fence_source_version IS NULL + OR expected_authority_tuple IS NULL + OR current_issuer_stream <> 'account:auth-authority:v1:issuer/firemud-account-service' + OR current_account_stream <> 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + OR source_issuer_generation <> current_issuer_generation + OR source_issuer_source_version <> current_issuer_source_version + OR source_account_generation <> current_account_generation + OR source_account_source_version <> current_account_source_version + OR source_issuer_generation <> source_issuer_source_version + OR source_issuer_generation <> current_issuer_sequence + 1 + OR source_account_generation <> source_account_source_version + OR source_account_generation <> current_account_sequence + 1 + OR current_issuance_fence <> current_account_sequence + 1 + OR current_fence_source_version <> current_account_sequence + 1 + OR NEW.authority_issuer_generation <> current_issuer_generation + OR NEW.authority_issuer_source_version <> current_issuer_source_version + OR NEW.authority_account_generation <> current_account_generation + OR NEW.authority_account_source_version <> current_account_source_version + OR NEW.issuance_fence <> current_issuance_fence + OR NEW.issuance_fence_source_version <> current_fence_source_version + OR convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8') <> + expected_authority_tuple + OR convert_from(NEW.membership_version_canonical_bytes, 'UTF8') <> '{}' + OR convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8') <> + '{"accountSourceVersion":' || current_account_source_version::text + || ',"issuanceFenceSourceVersion":' || current_fence_source_version::text + || ',"issuerSourceVersion":' || current_issuer_source_version::text || '}' THEN + RAISE EXCEPTION 'Account gameplay delegation authority snapshot is stale or missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_authority_guard + BEFORE INSERT OR UPDATE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_authority_guard(); + +CREATE FUNCTION account_gameplay_delegation_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account gameplay delegation issuance evidence cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.caller_context_id IS DISTINCT FROM OLD.caller_context_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_jti IS DISTINCT FROM OLD.token_jti + OR NEW.token_generation IS DISTINCT FROM OLD.token_generation + OR NEW.issued_at_epoch_second IS DISTINCT FROM OLD.issued_at_epoch_second + OR NEW.not_before_epoch_second IS DISTINCT FROM OLD.not_before_epoch_second + OR NEW.expires_at_epoch_second IS DISTINCT FROM OLD.expires_at_epoch_second + OR NEW.authority_issuer_generation IS DISTINCT FROM OLD.authority_issuer_generation + OR NEW.authority_issuer_source_version IS DISTINCT FROM OLD.authority_issuer_source_version + OR NEW.authority_account_generation IS DISTINCT FROM OLD.authority_account_generation + OR NEW.authority_account_source_version IS DISTINCT FROM OLD.authority_account_source_version + OR NEW.issuance_fence IS DISTINCT FROM OLD.issuance_fence + OR NEW.issuance_fence_source_version IS DISTINCT FROM OLD.issuance_fence_source_version + OR NEW.authority_tuple_canonical_bytes IS DISTINCT FROM OLD.authority_tuple_canonical_bytes + OR NEW.membership_version_canonical_bytes IS DISTINCT FROM OLD.membership_version_canonical_bytes + OR NEW.authority_source_versions_canonical_bytes IS DISTINCT FROM OLD.authority_source_versions_canonical_bytes + OR NEW.status IS DISTINCT FROM OLD.status + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Account gameplay delegation intent is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + IF OLD.token_hash IS NOT NULL OR OLD.signer_kid IS NOT NULL + OR OLD.signer_generation IS NOT NULL OR OLD.pending_registry_candidate_bytes IS NOT NULL + OR NEW.token_hash IS NULL OR NEW.signer_kid IS NULL + OR NEW.signer_generation IS NULL OR NEW.pending_registry_candidate_bytes IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation token identity may be bound exactly once' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_candidate_one_way'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_operation_guard + BEFORE UPDATE OR DELETE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_operation_guard(); + +CREATE FUNCTION account_gameplay_delegation_operation_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_gameplay_delegation_issuance_operations) THEN + RAISE EXCEPTION 'Account gameplay delegation issuance evidence cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_operation_no_truncate + BEFORE TRUNCATE ON account_gameplay_delegation_issuance_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_delegation_operation_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V148__account_auth_evidence_bundles.sql b/services/account-service/src/main/resources/db/migration/V148__account_auth_evidence_bundles.sql new file mode 100644 index 0000000000..8760d48546 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V148__account_auth_evidence_bundles.sql @@ -0,0 +1,374 @@ +-- Strict, immutable, non-authorizing evidence snapshots for exact Account-owned issuance rows. +-- This table does not introduce COMMITTED/ACTIVE state or provide credential response recovery. +CREATE TABLE account_gameplay_auth_evidence_source_fence ( + allocator_id BOOLEAN PRIMARY KEY DEFAULT TRUE, + last_source_fence BIGINT NOT NULL, + last_operation_id UUID, + last_transaction_id VARCHAR(20), + CONSTRAINT account_gameplay_auth_evidence_source_fence_singleton + CHECK (allocator_id), + CONSTRAINT account_gameplay_auth_evidence_source_fence_state + CHECK ((last_source_fence = 0 AND last_operation_id IS NULL AND last_transaction_id IS NULL) + OR (last_source_fence > 0 AND last_operation_id IS NOT NULL + AND last_transaction_id IS NOT NULL + AND last_transaction_id ~ '^[1-9][0-9]{0,19}$' + AND last_transaction_id::numeric <= 18446744073709551615)), + CONSTRAINT account_gameplay_auth_evidence_source_fence_operation_fk + FOREIGN KEY (last_operation_id) + REFERENCES account_gameplay_delegation_issuance_operations(operation_id) + ON DELETE RESTRICT +); +INSERT INTO account_gameplay_auth_evidence_source_fence (allocator_id, last_source_fence) +VALUES (TRUE, 0); + +CREATE TABLE account_gameplay_delegation_auth_evidence_bundles ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL, + bundle_schema VARCHAR(64) NOT NULL, + bundle_version VARCHAR(19) NOT NULL, + source_version VARCHAR(20) NOT NULL, + source_fence VARCHAR(19) NOT NULL, + issuance_fence VARCHAR(19) NOT NULL, + linearization VARCHAR(20) NOT NULL, + canonical_sha256 VARCHAR(64) NOT NULL, + canonical_bundle_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_auth_evidence_schema_check + CHECK (bundle_schema = 'account-auth-evidence-bundle/v1'), + CONSTRAINT account_gameplay_auth_evidence_positive_values_check + CHECK (bundle_version ~ '^[1-9][0-9]{0,18}$' + AND bundle_version::numeric <= 9223372036854775807 + AND source_version ~ '^[1-9][0-9]{0,19}$' + AND source_version::numeric <= 18446744073709551615 + AND source_fence ~ '^[1-9][0-9]{0,18}$' + AND source_fence::numeric <= 9223372036854775807 + AND issuance_fence ~ '^[1-9][0-9]{0,18}$' + AND issuance_fence::numeric <= 9223372036854775807 + AND linearization ~ '^[1-9][0-9]{0,19}$' + AND linearization::numeric <= 18446744073709551615), + CONSTRAINT account_gameplay_auth_evidence_source_fence_unique UNIQUE (source_fence), + CONSTRAINT account_gameplay_auth_evidence_digest_check + CHECK (canonical_sha256 ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_gameplay_auth_evidence_size_check + CHECK (octet_length(canonical_bundle_bytes) BETWEEN 1 AND 8192), + CONSTRAINT account_gameplay_auth_evidence_json_check + CHECK (jsonb_typeof(convert_from(canonical_bundle_bytes, 'UTF8')::jsonb) = 'object'), + CONSTRAINT account_gameplay_auth_evidence_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_gameplay_delegation_issuance_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_gameplay_auth_evidence_request_fk + FOREIGN KEY (request_id) + REFERENCES account_gameplay_delegation_issuance_operations(request_id) + ON DELETE RESTRICT, + CONSTRAINT account_gameplay_auth_evidence_account_fk + FOREIGN KEY (account_uuid) + REFERENCES accounts(account_uuid) + ON DELETE RESTRICT +); + +-- SQL binds the snapshot to the exact immutable pending operation, current owner rows, Account +-- identity, and existing positive outbox event identities. A zero checkpoint is only a closed +-- encoding for an owner-proved initialized empty stream; this trigger can check the stored shape, +-- but cannot prove its exhaustive-history provenance. The Account repository additionally has to +-- validate event payload contracts and cutoff applicability before it can insert. A +-- sequence/high-water mark alone is never accepted as source evidence. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_auth_evidence_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; + account_row RECORD; + bundle JSONB; + checkpoint JSONB; + expected_account_stream TEXT; + expected_issuer_stream TEXT := 'account:auth-authority:v1:issuer/firemud-account-service'; + capture_transaction_id TEXT; + allocated_source_fence BIGINT; + allocated_operation_id UUID; + allocated_transaction_id TEXT; + checkpoint_count INTEGER; + matched_account_checkpoint BOOLEAN := FALSE; + matched_issuer_checkpoint BOOLEAN := FALSE; + checkpoint_sequence BIGINT; + stream_sequence BIGINT; + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + current_account_generation BIGINT; + current_account_source_version BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + event_row RECORD; +BEGIN + bundle := convert_from(NEW.canonical_bundle_bytes, 'UTF8')::jsonb; + capture_transaction_id := pg_current_xact_id()::text; + + SELECT last_source_fence, last_operation_id, last_transaction_id + INTO allocated_source_fence, allocated_operation_id, allocated_transaction_id + FROM account_gameplay_auth_evidence_source_fence + WHERE allocator_id = TRUE + FOR UPDATE; + IF allocated_source_fence IS NULL + OR allocated_source_fence <= 0 + OR NEW.source_fence IS DISTINCT FROM allocated_source_fence::text + OR allocated_operation_id IS DISTINCT FROM NEW.operation_id + OR allocated_transaction_id IS DISTINCT FROM capture_transaction_id + OR NEW.source_version IS DISTINCT FROM capture_transaction_id + OR NEW.linearization IS DISTINCT FROM capture_transaction_id THEN + RAISE EXCEPTION 'Account auth-evidence bundle reference is not the exact persisted capture allocation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_capture_reference'; + END IF; + + -- Match the Account owner lock order used by source snapshots and issuance: Account row, + -- issuer/account generations, issuance fence, then the operation row. The Account identity is + -- read-only here, so FOR SHARE also avoids upgrading the source reader's existing lock. + SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + INTO account_row + FROM accounts + WHERE account_uuid = NEW.account_uuid + FOR SHARE; + IF account_row.id IS NULL + OR account_row.id <> account_row.account_uuid_source_numeric_id + OR account_row.account_uuid_provenance NOT IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') + OR bundle#>>'{accountIdentitySource,sourceRowId}' IS DISTINCT FROM account_row.id::text + OR bundle#>>'{accountIdentitySource,sourceNumericId}' IS DISTINCT FROM account_row.account_uuid_source_numeric_id::text + OR bundle#>>'{accountIdentitySource,provenance}' IS DISTINCT FROM account_row.account_uuid_provenance THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the Account identity row' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_identity_match'; + END IF; + + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + + SELECT * INTO operation_row + FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF operation_row.operation_id IS NULL + OR operation_row.request_id <> NEW.request_id + OR operation_row.account_uuid <> NEW.account_uuid + OR operation_row.status <> 'PENDING' + OR bundle->>'schema' IS DISTINCT FROM NEW.bundle_schema + OR bundle->>'profile' IS DISTINCT FROM 'game-session-account-delegation' + OR bundle->>'issuer' IS DISTINCT FROM 'firemud-account-service' + OR bundle->>'audience' IS DISTINCT FROM 'account-service' + OR bundle#>>'{bundleRef,bundleVersion}' IS DISTINCT FROM NEW.bundle_version + OR bundle#>>'{bundleRef,sourceVersion}' IS DISTINCT FROM NEW.source_version + OR bundle#>>'{bundleRef,sourceFence}' IS DISTINCT FROM NEW.source_fence + OR bundle#>>'{bundleRef,linearization}' IS DISTINCT FROM NEW.linearization + OR bundle#>>'{scope,kind}' IS DISTINCT FROM 'account' + OR bundle#>>'{scope,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR jsonb_typeof(bundle#>'{scope,tenantIds}') IS DISTINCT FROM 'array' + OR COALESCE(jsonb_array_length(bundle#>'{scope,tenantIds}'), -1) <> 0 + OR bundle#>>'{operation,operationId}' IS DISTINCT FROM NEW.operation_id::text + OR bundle#>>'{operation,requestId}' IS DISTINCT FROM NEW.request_id::text + OR bundle#>>'{operation,requestDigest}' IS DISTINCT FROM operation_row.request_digest + OR bundle#>>'{operation,callerWorkload}' IS DISTINCT FROM operation_row.caller_workload + OR bundle#>>'{operation,callerContextId}' IS DISTINCT FROM operation_row.caller_context_id::text + OR bundle#>>'{operation,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR bundle#>>'{tokenIdentity,jti}' IS DISTINCT FROM operation_row.token_jti::text + OR bundle#>>'{tokenIdentity,tokenGeneration}' IS DISTINCT FROM operation_row.token_generation::text + OR bundle#>>'{tokenIdentity,iat}' IS DISTINCT FROM operation_row.issued_at_epoch_second::text + OR bundle#>>'{tokenIdentity,nbf}' IS DISTINCT FROM operation_row.not_before_epoch_second::text + OR bundle#>>'{tokenIdentity,exp}' IS DISTINCT FROM operation_row.expires_at_epoch_second::text + OR bundle->'authorityTuple' IS DISTINCT FROM + convert_from(operation_row.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR bundle->'membershipVersion' IS DISTINCT FROM + convert_from(operation_row.membership_version_canonical_bytes, 'UTF8')::jsonb + OR bundle->>'issuanceFence' IS DISTINCT FROM operation_row.issuance_fence::text + OR bundle->'authoritySourceVersions' IS DISTINCT FROM + jsonb_build_object( + 'issuerSourceVersion', operation_row.authority_issuer_source_version::text, + 'accountSourceVersion', operation_row.authority_account_source_version::text, + 'issuanceFenceSourceVersion', operation_row.issuance_fence_source_version::text) + OR NEW.issuance_fence <> operation_row.issuance_fence::text THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the exact pending operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_operation_match'; + END IF; + + IF current_issuer_generation IS NULL + OR current_account_generation IS NULL + OR current_issuance_fence IS NULL + OR operation_row.authority_issuer_generation <> current_issuer_generation + OR operation_row.authority_issuer_source_version <> current_issuer_source_version + OR operation_row.authority_account_generation <> current_account_generation + OR operation_row.authority_account_source_version <> current_account_source_version + OR operation_row.issuance_fence <> current_issuance_fence + OR operation_row.issuance_fence_source_version <> current_fence_source_version THEN + RAISE EXCEPTION 'Account auth-evidence bundle is stale against current authority' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_current_authority'; + END IF; + + expected_account_stream := 'account:auth-authority:v1:account/' || NEW.account_uuid::text; + IF jsonb_typeof(bundle->'outboxCheckpoints') <> 'array' + OR jsonb_array_length(bundle->'outboxCheckpoints') <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle requires exact issuer and Account checkpoints' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT count(*) INTO checkpoint_count FROM jsonb_array_elements(bundle->'outboxCheckpoints'); + IF checkpoint_count <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are ambiguous' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + FOR checkpoint IN SELECT value FROM jsonb_array_elements(bundle->'outboxCheckpoints') LOOP + IF checkpoint->>'outboxStreamKey' = expected_account_stream THEN + matched_account_checkpoint := TRUE; + ELSIF checkpoint->>'outboxStreamKey' = expected_issuer_stream THEN + matched_issuer_checkpoint := TRUE; + ELSE + RAISE EXCEPTION 'Account auth-evidence bundle has an out-of-scope checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF COALESCE(checkpoint->>'outboxSequence', '') !~ '^(0|[1-9][0-9]{0,18})$' THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint sequence is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + checkpoint_sequence := (checkpoint->>'outboxSequence')::BIGINT; + SELECT last_sequence INTO stream_sequence + FROM account_authority_outbox_streams + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + FOR SHARE; + IF checkpoint_sequence = 0 THEN + IF jsonb_object_length(checkpoint) <> 2 + OR checkpoint ? 'sourceEventId' + OR checkpoint ? 'sourceEventDigest' + OR stream_sequence IS DISTINCT FROM 0 + OR EXISTS ( + SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey') THEN + RAISE EXCEPTION 'Account zero checkpoint is not an exact initialized empty stream' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + ELSE + IF jsonb_object_length(checkpoint) <> 4 + OR checkpoint->>'sourceEventId' IS NULL + OR checkpoint->>'sourceEventDigest' IS NULL THEN + RAISE EXCEPTION 'Account positive checkpoint is missing exact event identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT event_id, event_digest INTO event_row + FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + AND outbox_sequence = checkpoint_sequence; + IF stream_sequence IS DISTINCT FROM checkpoint_sequence + OR event_row.event_id IS NULL + OR checkpoint->>'sourceEventId' <> event_row.event_id + OR checkpoint->>'sourceEventDigest' <> event_row.event_digest THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not match a current stored event' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + END IF; + END LOOP; + IF NOT matched_account_checkpoint OR NOT matched_issuer_checkpoint THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF bundle#>'{authorityTuple,accountSecurityCutoff}' IS NOT NULL THEN + IF bundle#>>'{authorityTuple,accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM expected_account_stream + OR bundle#>>'{authorityTuple,accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM + operation_row.authority_account_generation::text + OR COALESCE(bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}', '') !~ '^[1-9][0-9]{0,18}$' THEN + RAISE EXCEPTION 'Account auth-evidence security cutoff is malformed or out of scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + IF (bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}')::BIGINT > ( + SELECT (item->>'outboxSequence')::BIGINT + FROM jsonb_array_elements(bundle->'outboxCheckpoints') AS item + WHERE item->>'outboxStreamKey' = expected_account_stream) THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not cover its cutoff' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_auth_evidence_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account auth-evidence bundle is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_immutable'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_gameplay_auth_evidence_source_fence_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.allocator_id IS DISTINCT FROM OLD.allocator_id + OR NEW.last_source_fence <> OLD.last_source_fence + 1 + OR NEW.last_operation_id IS NULL + OR NEW.last_transaction_id IS DISTINCT FROM pg_current_xact_id()::text THEN + RAISE EXCEPTION 'Account auth-evidence source fence must advance exactly once in its capture transaction' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_source_fence_monotonic'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_auth_evidence_source_fence_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account auth-evidence source fence allocator cannot be inserted, deleted, or truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_source_fence_immutable'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_gameplay_auth_evidence_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_gameplay_delegation_auth_evidence_bundles) THEN + RAISE EXCEPTION 'Account auth-evidence bundles cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_immutable'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_gameplay_auth_evidence_insert + BEFORE INSERT ON account_gameplay_delegation_auth_evidence_bundles + FOR EACH ROW EXECUTE FUNCTION account_gameplay_auth_evidence_insert_guard(); +CREATE TRIGGER account_gameplay_auth_evidence_update_delete + BEFORE UPDATE OR DELETE ON account_gameplay_delegation_auth_evidence_bundles + FOR EACH ROW EXECUTE FUNCTION account_gameplay_auth_evidence_immutable_guard(); +CREATE TRIGGER account_gameplay_auth_evidence_truncate + BEFORE TRUNCATE ON account_gameplay_delegation_auth_evidence_bundles + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_auth_evidence_no_truncate(); +CREATE TRIGGER account_gameplay_auth_evidence_source_fence_update + BEFORE UPDATE ON account_gameplay_auth_evidence_source_fence + FOR EACH ROW EXECUTE FUNCTION account_gameplay_auth_evidence_source_fence_update_guard(); +CREATE TRIGGER account_gameplay_auth_evidence_source_fence_insert_delete + BEFORE INSERT OR DELETE ON account_gameplay_auth_evidence_source_fence + FOR EACH ROW EXECUTE FUNCTION account_gameplay_auth_evidence_source_fence_immutable_guard(); +CREATE TRIGGER account_gameplay_auth_evidence_source_fence_truncate + BEFORE TRUNCATE ON account_gameplay_auth_evidence_source_fence + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_auth_evidence_source_fence_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V149__account_gameplay_delegation_encrypted_response.sql b/services/account-service/src/main/resources/db/migration/V149__account_gameplay_delegation_encrypted_response.sql new file mode 100644 index 0000000000..c0f450fcc5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V149__account_gameplay_delegation_encrypted_response.sql @@ -0,0 +1,124 @@ +-- Exact compact delegation candidates are separately Account-encrypted and remain PENDING. +-- This table stores no plaintext JWT and introduces no COMMITTED/ACTIVE state or recovery API. +CREATE TABLE account_gameplay_delegation_response_envelopes ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + token_hash VARCHAR(64) NOT NULL, + signer_kid VARCHAR(64) NOT NULL, + signer_generation VARCHAR(19) NOT NULL, + authority_evidence_bundle_sha256 VARCHAR(64) NOT NULL, + issuance_fence BIGINT NOT NULL, + response_recovery_expiry_epoch_ms BIGINT NOT NULL, + envelope_sha256 VARCHAR(64) NOT NULL, + envelope_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_delegation_response_candidate_check + CHECK (token_hash ~ '^[0-9a-f]{64}$' + AND signer_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND signer_generation ~ '^[1-9][0-9]{0,18}$'), + CONSTRAINT account_gameplay_delegation_response_evidence_check + CHECK (authority_evidence_bundle_sha256 ~ '^[0-9a-f]{64}$' + AND issuance_fence > 0), + CONSTRAINT account_gameplay_delegation_response_expiry_check + CHECK (response_recovery_expiry_epoch_ms > 0 + AND response_recovery_expiry_epoch_ms % 1000 = 0), + CONSTRAINT account_gameplay_delegation_response_hash_check + CHECK (envelope_sha256 ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_gameplay_delegation_response_size_check + CHECK (octet_length(envelope_bytes) BETWEEN 1 AND 65610), + CONSTRAINT account_gameplay_delegation_response_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_gameplay_delegation_issuance_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_gameplay_delegation_response_request_fk + FOREIGN KEY (request_id) + REFERENCES account_gameplay_delegation_issuance_operations(request_id) + ON DELETE RESTRICT +); + +-- The trigger binds only immutable ciphertext metadata to the exact PENDING operation and the +-- already-persisted owner bundle. Java additionally checks current locked generations, canonical +-- bytes, the transient JWT hash, and exact readback. Neither layer claims signature validity, +-- completed external postconditions, or permission to recover plaintext. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_delegation_response_envelope_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; + bundle_row RECORD; + bundle JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Account gameplay delegation response envelope is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_immutable'; + END IF; + + SELECT * INTO operation_row + FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF operation_row.operation_id IS NULL + OR operation_row.request_id <> NEW.request_id + OR operation_row.status <> 'PENDING' + OR operation_row.token_hash IS NULL + OR operation_row.token_hash <> NEW.token_hash + OR operation_row.signer_kid <> NEW.signer_kid + OR operation_row.signer_generation <> NEW.signer_generation + OR operation_row.issuance_fence <> NEW.issuance_fence + OR NEW.response_recovery_expiry_epoch_ms / 1000 <> operation_row.expires_at_epoch_second + OR NEW.response_recovery_expiry_epoch_ms % 1000 <> 0 THEN + RAISE EXCEPTION 'Account gameplay delegation response has no exact PENDING candidate' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_operation_match'; + END IF; + + SELECT request_id, account_uuid, bundle_schema, issuance_fence, canonical_sha256, + canonical_bundle_bytes + INTO bundle_row + FROM account_gameplay_delegation_auth_evidence_bundles + WHERE operation_id = NEW.operation_id; + IF bundle_row.request_id IS NULL + OR bundle_row.request_id <> NEW.request_id + OR bundle_row.account_uuid <> operation_row.account_uuid + OR bundle_row.bundle_schema <> 'account-auth-evidence-bundle/v1' + OR bundle_row.issuance_fence <> operation_row.issuance_fence::text + OR bundle_row.canonical_sha256 <> NEW.authority_evidence_bundle_sha256 + OR octet_length(bundle_row.canonical_bundle_bytes) > 8192 THEN + RAISE EXCEPTION 'Account gameplay delegation response has no exact owner evidence bundle' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_evidence_match'; + END IF; + bundle := convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb; + IF bundle->>'schema' IS DISTINCT FROM bundle_row.bundle_schema + OR bundle#>>'{operation,operationId}' IS DISTINCT FROM NEW.operation_id::text + OR bundle#>>'{operation,requestId}' IS DISTINCT FROM NEW.request_id::text + OR bundle#>>'{tokenIdentity,jti}' IS DISTINCT FROM operation_row.token_jti::text + OR bundle#>>'{operation,requestDigest}' IS DISTINCT FROM operation_row.request_digest + OR bundle->>'issuanceFence' IS DISTINCT FROM operation_row.issuance_fence::text THEN + RAISE EXCEPTION 'Account gameplay delegation response evidence does not match its operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_evidence_match'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_delegation_response_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_gameplay_delegation_response_envelopes) THEN + RAISE EXCEPTION 'Account gameplay delegation response envelopes cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_immutable'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_response_envelope_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_gameplay_delegation_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_response_envelope_guard(); +CREATE TRIGGER account_gameplay_delegation_response_no_truncate + BEFORE TRUNCATE ON account_gameplay_delegation_response_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_delegation_response_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V150__account_gameplay_delegation_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V150__account_gameplay_delegation_committed_issuance.sql new file mode 100644 index 0000000000..22f833342c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V150__account_gameplay_delegation_committed_issuance.sql @@ -0,0 +1,352 @@ +-- A signed candidate becomes durably COMMITTED only after Account has verified the signer-owned +-- candidate proof, exact pinned Coordination Redis receipt, current authority projection and +-- current source/evidence rows. COMMITTED remains non-authorizing; this migration adds no active +-- registry state or token recovery surface. +ALTER TABLE account_gameplay_delegation_issuance_operations + DROP CONSTRAINT account_gameplay_delegation_status_check; + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD COLUMN commit_proof_version SMALLINT, + ADD COLUMN commit_proof_sha256 VARCHAR(64), + ADD COLUMN commit_proof_canonical_bytes BYTEA, + ADD COLUMN committed_at TIMESTAMPTZ; + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD CONSTRAINT account_gameplay_delegation_status_check + CHECK (status IN ('PENDING', 'COMMITTED')); + +-- [jooq ignore start] +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD CONSTRAINT account_gameplay_delegation_commit_proof_check + CHECK ( + (status = 'PENDING' + AND commit_proof_version IS NULL + AND commit_proof_sha256 IS NULL + AND commit_proof_canonical_bytes IS NULL + AND committed_at IS NULL) + OR + (status = 'COMMITTED' + AND commit_proof_version IS NOT NULL + AND commit_proof_version = 1 + AND commit_proof_sha256 IS NOT NULL + AND commit_proof_sha256 ~ '^[0-9a-f]{64}$' + AND commit_proof_canonical_bytes IS NOT NULL + AND octet_length(commit_proof_canonical_bytes) BETWEEN 1 AND 32768 + AND committed_at IS NOT NULL + AND jsonb_typeof(convert_from(commit_proof_canonical_bytes, 'UTF8')::jsonb) = 'object' + AND (convert_from(commit_proof_canonical_bytes, 'UTF8')::jsonb) ?& ARRAY[ + 'schema', 'identity', 'tokenSha256', 'registryRecordSha256', + 'registry', 'bundle', 'authority', 'signer', 'envelope'] + AND convert_from(commit_proof_canonical_bytes, 'UTF8')::jsonb->>'schema' = + 'account-game-session-delegation-commit-proof/v1') + ); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_delegation_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + proof JSONB; + bundle_row RECORD; + envelope_row RECORD; + identity_proof JSONB; + registry JSONB; + bundle JSONB; + authority JSONB; + signer JSONB; + envelope JSONB; + proof_key_count INTEGER; + identity_key_count INTEGER; + registry_key_count INTEGER; + bundle_key_count INTEGER; + authority_key_count INTEGER; + signer_key_count INTEGER; + envelope_key_count INTEGER; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.token_hash IS NOT NULL + OR NEW.signer_kid IS NOT NULL + OR NEW.signer_generation IS NOT NULL + OR NEW.pending_registry_candidate_bytes IS NOT NULL + OR NEW.commit_proof_version IS NOT NULL + OR NEW.commit_proof_sha256 IS NOT NULL + OR NEW.commit_proof_canonical_bytes IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account gameplay delegation issuance must begin as unbound PENDING intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_initial_pending_only'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account gameplay delegation issuance evidence cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.caller_context_id IS DISTINCT FROM OLD.caller_context_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_jti IS DISTINCT FROM OLD.token_jti + OR NEW.token_generation IS DISTINCT FROM OLD.token_generation + OR NEW.issued_at_epoch_second IS DISTINCT FROM OLD.issued_at_epoch_second + OR NEW.not_before_epoch_second IS DISTINCT FROM OLD.not_before_epoch_second + OR NEW.expires_at_epoch_second IS DISTINCT FROM OLD.expires_at_epoch_second + OR NEW.authority_issuer_generation IS DISTINCT FROM OLD.authority_issuer_generation + OR NEW.authority_issuer_source_version IS DISTINCT FROM OLD.authority_issuer_source_version + OR NEW.authority_account_generation IS DISTINCT FROM OLD.authority_account_generation + OR NEW.authority_account_source_version IS DISTINCT FROM OLD.authority_account_source_version + OR NEW.issuance_fence IS DISTINCT FROM OLD.issuance_fence + OR NEW.issuance_fence_source_version IS DISTINCT FROM OLD.issuance_fence_source_version + OR NEW.authority_tuple_canonical_bytes IS DISTINCT FROM OLD.authority_tuple_canonical_bytes + OR NEW.membership_version_canonical_bytes IS DISTINCT FROM OLD.membership_version_canonical_bytes + OR NEW.authority_source_versions_canonical_bytes IS DISTINCT FROM OLD.authority_source_versions_canonical_bytes + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Account gameplay delegation intent is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + + IF OLD.status = 'COMMITTED' + OR OLD.commit_proof_version IS NOT NULL + OR OLD.commit_proof_sha256 IS NOT NULL + OR OLD.commit_proof_canonical_bytes IS NOT NULL + OR OLD.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account gameplay delegation commit evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_immutable'; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.commit_proof_version IS NOT NULL + OR NEW.commit_proof_sha256 IS NOT NULL + OR NEW.commit_proof_canonical_bytes IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Pending issuance cannot carry commit proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + IF OLD.token_hash IS NOT NULL OR OLD.signer_kid IS NOT NULL + OR OLD.signer_generation IS NOT NULL OR OLD.pending_registry_candidate_bytes IS NOT NULL + OR NEW.token_hash IS NULL OR NEW.signer_kid IS NULL + OR NEW.signer_generation IS NULL OR NEW.pending_registry_candidate_bytes IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation token identity may be bound exactly once' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_candidate_one_way'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status IS DISTINCT FROM 'COMMITTED' OR OLD.status IS DISTINCT FROM 'PENDING' + OR OLD.token_hash IS NULL OR OLD.signer_kid IS NULL + OR OLD.signer_generation IS NULL OR OLD.pending_registry_candidate_bytes IS NULL + OR NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.signer_kid IS DISTINCT FROM OLD.signer_kid + OR NEW.signer_generation IS DISTINCT FROM OLD.signer_generation + OR NEW.pending_registry_candidate_bytes IS DISTINCT FROM OLD.pending_registry_candidate_bytes + OR NEW.commit_proof_version IS DISTINCT FROM 1 + OR NEW.commit_proof_sha256 IS NULL + OR NEW.commit_proof_sha256 !~ '^[0-9a-f]{64}$' + OR NEW.commit_proof_canonical_bytes IS NULL + OR NEW.committed_at IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation COMMITTED transition is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + + proof := convert_from(NEW.commit_proof_canonical_bytes, 'UTF8')::jsonb; + IF jsonb_typeof(proof) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof is not a canonical object' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + SELECT count(*) INTO proof_key_count FROM jsonb_object_keys(proof); + IF proof_key_count <> 9 THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has unknown or missing fields' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + + identity_proof := proof->'identity'; + registry := proof->'registry'; + bundle := proof->'bundle'; + authority := proof->'authority'; + signer := proof->'signer'; + envelope := proof->'envelope'; + + IF jsonb_typeof(identity_proof) IS DISTINCT FROM 'object' + OR jsonb_typeof(registry) IS DISTINCT FROM 'object' + OR jsonb_typeof(bundle) IS DISTINCT FROM 'object' + OR jsonb_typeof(authority) IS DISTINCT FROM 'object' + OR jsonb_typeof(signer) IS DISTINCT FROM 'object' + OR jsonb_typeof(envelope) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof fields must be objects' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + SELECT count(*) INTO identity_key_count FROM jsonb_object_keys(identity_proof); + SELECT count(*) INTO registry_key_count FROM jsonb_object_keys(registry); + SELECT count(*) INTO bundle_key_count FROM jsonb_object_keys(bundle); + SELECT count(*) INTO authority_key_count FROM jsonb_object_keys(authority); + SELECT count(*) INTO signer_key_count FROM jsonb_object_keys(signer); + SELECT count(*) INTO envelope_key_count FROM jsonb_object_keys(envelope); + + IF identity_key_count <> 12 + OR NOT (identity_proof ?& ARRAY[ + 'operationId', 'requestId', 'accountId', 'requestDigest', 'callerWorkload', + 'callerContextId', 'tokenJti', 'tokenGeneration', 'issuedAtEpochSecond', + 'notBeforeEpochSecond', 'expiresAtEpochSecond', 'tokenSha256']) + OR registry_key_count <> 16 + OR NOT (registry ?& ARRAY[ + 'state', 'registryVersion', 'tokenKey', 'tokenHash', 'kid', 'signerGeneration', + 'operationId', 'requestId', 'requestDigest', 'absoluteExpiryMillis', + 'localAofCount', 'replicaAofCount', 'outcome', 'canonicalRecordSha256', + 'evidenceBundleSha256', 'aclIdentity']) + OR bundle_key_count <> 4 + OR NOT (bundle ?& ARRAY['bundleVersion', 'sourceVersion', 'linearization', 'canonicalSha256']) + OR authority_key_count <> 12 + OR NOT (authority ?& ARRAY[ + 'issuerGeneration', 'issuerSourceVersion', 'accountGeneration', + 'accountSourceVersion', 'issuanceFence', 'issuanceFenceSourceVersion', + 'authorityTuple', 'authoritySourceVersions', 'issuerProjectionGeneration', + 'accountProjectionGeneration', 'issuerProjectionSha256', 'accountProjectionSha256']) + OR signer_key_count <> 7 + OR NOT (signer ?& ARRAY[ + 'promotionStatus', 'promotionOperationId', 'generationOperationId', + 'targetKid', 'targetGeneration', 'correspondenceSha256', 'correspondence']) + OR envelope_key_count <> 10 + OR NOT (envelope ?& ARRAY[ + 'operationId', 'requestId', 'tokenHash', 'kid', 'signerGeneration', + 'authorityEvidenceBundleSha256', 'issuanceFence', + 'responseRecoveryExpiryEpochMillis', 'envelopeSha256', 'envelopeBytesLength']) + OR proof->>'tokenSha256' IS DISTINCT FROM NEW.token_hash + OR proof->>'registryRecordSha256' IS DISTINCT FROM registry->>'canonicalRecordSha256' + OR identity_proof->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR identity_proof->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR identity_proof->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR identity_proof->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR identity_proof->>'callerWorkload' IS DISTINCT FROM NEW.caller_workload + OR identity_proof->>'callerContextId' IS DISTINCT FROM NEW.caller_context_id::TEXT + OR identity_proof->>'tokenJti' IS DISTINCT FROM NEW.token_jti::TEXT + OR identity_proof->>'tokenGeneration' IS DISTINCT FROM NEW.token_generation::TEXT + OR identity_proof->>'issuedAtEpochSecond' IS DISTINCT FROM NEW.issued_at_epoch_second::TEXT + OR identity_proof->>'notBeforeEpochSecond' IS DISTINCT FROM NEW.not_before_epoch_second::TEXT + OR identity_proof->>'expiresAtEpochSecond' IS DISTINCT FROM NEW.expires_at_epoch_second::TEXT + OR identity_proof->>'tokenSha256' IS DISTINCT FROM NEW.token_hash + OR registry->>'state' IS DISTINCT FROM 'pending' + OR registry->>'registryVersion' IS DISTINCT FROM '1' + OR registry->>'tokenKey' IS DISTINCT FROM ('session:auth:token:' || NEW.token_hash) + OR registry->>'tokenHash' IS DISTINCT FROM NEW.token_hash + OR registry->>'kid' IS DISTINCT FROM NEW.signer_kid + OR registry->>'signerGeneration' IS DISTINCT FROM NEW.signer_generation + OR registry->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR registry->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR registry->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR registry->>'aclIdentity' IS DISTINCT FROM 'account_coord_app' + OR registry->>'absoluteExpiryMillis' IS NULL + OR registry->>'absoluteExpiryMillis' !~ '^[1-9][0-9]{0,18}$' + OR registry->>'localAofCount' IS NULL + OR registry->>'localAofCount' !~ '^[1-9][0-9]{0,3}$' + OR registry->>'replicaAofCount' IS NULL + OR registry->>'replicaAofCount' !~ '^[1-9][0-9]{0,3}$' + OR registry->>'outcome' IS NULL + OR registry->>'outcome' NOT IN ('CREATED', 'EXACT_RETRY') + OR registry->>'canonicalRecordSha256' IS NULL + OR registry->>'canonicalRecordSha256' !~ '^[0-9a-f]{64}$' + OR registry->>'evidenceBundleSha256' IS DISTINCT FROM bundle->>'canonicalSha256' + OR bundle->>'canonicalSha256' IS NULL + OR bundle->>'canonicalSha256' !~ '^[0-9a-f]{64}$' + OR authority->>'issuerGeneration' IS DISTINCT FROM NEW.authority_issuer_generation::TEXT + OR authority->>'issuerSourceVersion' IS DISTINCT FROM NEW.authority_issuer_source_version::TEXT + OR authority->>'accountGeneration' IS DISTINCT FROM NEW.authority_account_generation::TEXT + OR authority->>'accountSourceVersion' IS DISTINCT FROM NEW.authority_account_source_version::TEXT + OR authority->>'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::TEXT + OR authority->>'issuanceFenceSourceVersion' IS DISTINCT FROM NEW.issuance_fence_source_version::TEXT + OR authority->'authorityTuple' IS DISTINCT FROM + convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR authority->'authoritySourceVersions' IS DISTINCT FROM + convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8')::jsonb + OR authority->>'issuerProjectionGeneration' IS DISTINCT FROM NEW.authority_issuer_generation::TEXT + OR authority->>'accountProjectionGeneration' IS DISTINCT FROM NEW.authority_account_generation::TEXT + OR authority->>'issuerProjectionSha256' IS NULL + OR authority->>'issuerProjectionSha256' !~ '^[0-9a-f]{64}$' + OR authority->>'accountProjectionSha256' IS NULL + OR authority->>'accountProjectionSha256' !~ '^[0-9a-f]{64}$' + OR signer->>'promotionStatus' IS DISTINCT FROM 'COMMITTED' + OR signer->>'promotionOperationId' IS NULL + OR signer->>'promotionOperationId' !~ '^[0-9a-f-]{36}$' + OR signer->>'generationOperationId' IS NULL + OR signer->>'generationOperationId' !~ '^[0-9a-f-]{36}$' + OR signer->>'targetKid' IS DISTINCT FROM NEW.signer_kid + OR signer->>'targetGeneration' IS DISTINCT FROM NEW.signer_generation + OR signer->>'correspondenceSha256' IS NULL + OR signer->>'correspondenceSha256' !~ '^[0-9a-f]{64}$' + OR envelope->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR envelope->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR envelope->>'tokenHash' IS DISTINCT FROM NEW.token_hash + OR envelope->>'kid' IS DISTINCT FROM NEW.signer_kid + OR envelope->>'signerGeneration' IS DISTINCT FROM NEW.signer_generation THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof does not match its immutable intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + IF (registry->>'absoluteExpiryMillis')::BIGINT < NEW.expires_at_epoch_second * 1000 + OR (registry->>'absoluteExpiryMillis')::BIGINT > NEW.expires_at_epoch_second * 1000 + 300000 THEN + RAISE EXCEPTION 'Account gameplay delegation Redis receipt expiry is outside the immutable token bound' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + SELECT request_id, account_uuid, bundle_schema, bundle_version, source_version, + issuance_fence, linearization, canonical_sha256, canonical_bundle_bytes + INTO bundle_row + FROM account_gameplay_delegation_auth_evidence_bundles + WHERE operation_id = NEW.operation_id; + IF bundle_row.request_id IS NULL + OR bundle_row.request_id <> NEW.request_id + OR bundle_row.account_uuid <> NEW.account_uuid + OR bundle_row.bundle_schema <> 'account-auth-evidence-bundle/v1' + OR bundle_row.bundle_version <> bundle->>'bundleVersion' + OR bundle_row.source_version <> bundle->>'sourceVersion' + OR bundle_row.linearization <> bundle->>'linearization' + OR bundle_row.canonical_sha256 <> bundle->>'canonicalSha256' + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'authorityTuple' IS DISTINCT FROM + convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'membershipVersion' IS DISTINCT FROM + convert_from(NEW.membership_version_canonical_bytes, 'UTF8')::jsonb + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'authoritySourceVersions' IS DISTINCT FROM + convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8')::jsonb THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has no exact owner evidence bundle' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, + authority_evidence_bundle_sha256, issuance_fence, response_recovery_expiry_epoch_ms, + envelope_sha256, octet_length(envelope_bytes) AS envelope_bytes_length + INTO envelope_row + FROM account_gameplay_delegation_response_envelopes + WHERE operation_id = NEW.operation_id; + IF envelope_row.operation_id IS NULL + OR envelope_row.request_id <> NEW.request_id + OR envelope_row.token_hash <> NEW.token_hash + OR envelope_row.signer_kid <> NEW.signer_kid + OR envelope_row.signer_generation <> NEW.signer_generation + OR envelope_row.authority_evidence_bundle_sha256 <> bundle_row.canonical_sha256 + OR envelope_row.issuance_fence <> NEW.issuance_fence + OR envelope_row.response_recovery_expiry_epoch_ms / 1000 <> NEW.expires_at_epoch_second + OR envelope->>'authorityEvidenceBundleSha256' IS DISTINCT FROM envelope_row.authority_evidence_bundle_sha256 + OR envelope->>'issuanceFence' IS DISTINCT FROM envelope_row.issuance_fence::TEXT + OR envelope->>'responseRecoveryExpiryEpochMillis' IS DISTINCT FROM envelope_row.response_recovery_expiry_epoch_ms::TEXT + OR envelope->>'envelopeSha256' IS DISTINCT FROM envelope_row.envelope_sha256 + OR envelope->>'envelopeBytesLength' IS DISTINCT FROM envelope_row.envelope_bytes_length::TEXT THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has no exact sealed owner envelope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + RETURN NEW; +END; +$$; + +DROP TRIGGER account_gameplay_delegation_operation_guard + ON account_gameplay_delegation_issuance_operations; +CREATE TRIGGER account_gameplay_delegation_operation_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_operation_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V151__account_gameplay_token_identity_fences.sql b/services/account-service/src/main/resources/db/migration/V151__account_gameplay_token_identity_fences.sql new file mode 100644 index 0000000000..00b9ddbbdb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V151__account_gameplay_token_identity_fences.sql @@ -0,0 +1,85 @@ +-- Only the real COMMITTED issuance transaction establishes initial fences; no registry adoption. +-- Historical COMMITTED rows with no fence fail closed and require fresh LOGIN. +CREATE TABLE account_gameplay_token_identity_fences ( + operation_id UUID PRIMARY KEY REFERENCES account_gameplay_delegation_issuance_operations (operation_id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid) ON DELETE RESTRICT, + issuance_request_id UUID NOT NULL UNIQUE, + token_hash VARCHAR(64) NOT NULL UNIQUE, + token_jti UUID NOT NULL UNIQUE, + not_before_epoch_second BIGINT NOT NULL, + token_generation BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + token_identity_fence BIGINT NOT NULL DEFAULT 1, + state VARCHAR(16) NOT NULL DEFAULT 'ACTIVE', + revocation_request_id UUID UNIQUE, + revocation_digest VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_token_identity_shape CHECK ( + token_hash ~ '^[0-9a-f]{64}$' AND not_before_epoch_second > 0 + AND token_generation = 1 AND issuance_fence > 0 + AND account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND issuance_request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND token_jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_gameplay_token_revocation_shape CHECK ( + (state = 'ACTIVE' AND token_identity_fence = 1 + AND revocation_request_id IS NULL AND revocation_digest IS NULL) + OR (state IN ('PENDING', 'COMMITTED') + AND token_identity_fence = CASE WHEN state = 'PENDING' THEN 2 ELSE 3 END + AND revocation_request_id IS NOT NULL AND revocation_digest IS NOT NULL + AND revocation_request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND revocation_digest ~ '^[0-9a-f]{64}$')) +); + +-- Retain immutable identity and forbid reset/recreation. Triggers reinforce the repository's +-- account-row-first lock order; callers must acquire that Account lock before row mutations. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_token_identity_fence_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account token fence retention cannot be bypassed by deletion' USING ERRCODE = '23514'; + END IF; + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account token fence Account source absent' USING ERRCODE = '23514'; + END IF; + PERFORM operation_id FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id AND account_uuid = NEW.account_uuid + AND request_id = NEW.issuance_request_id AND token_hash = NEW.token_hash + AND token_jti = NEW.token_jti AND not_before_epoch_second = NEW.not_before_epoch_second + AND token_generation = NEW.token_generation AND issuance_fence = NEW.issuance_fence + AND status = 'COMMITTED' FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account token fence requires exact COMMITTED issuance' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'ACTIVE' OR NEW.token_identity_fence <> 1 + OR NEW.revocation_request_id IS NOT NULL OR NEW.revocation_digest IS NOT NULL THEN + RAISE EXCEPTION 'Account token fence must begin ACTIVE' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.operation_id, NEW.account_uuid, NEW.issuance_request_id, NEW.token_hash, + NEW.token_jti, NEW.not_before_epoch_second, NEW.token_generation, NEW.issuance_fence, NEW.created_at) + IS DISTINCT FROM ROW(OLD.operation_id, OLD.account_uuid, OLD.issuance_request_id, OLD.token_hash, + OLD.token_jti, OLD.not_before_epoch_second, OLD.token_generation, OLD.issuance_fence, OLD.created_at) THEN + RAISE EXCEPTION 'Account token fence identity is immutable' USING ERRCODE = '23514'; + END IF; + IF NEW IS NOT DISTINCT FROM OLD THEN RETURN NEW; END IF; + IF OLD.state = 'ACTIVE' AND NEW.state = 'PENDING' AND NEW.token_identity_fence = 2 THEN + RETURN NEW; + END IF; + -- Storage only: there is no completion API until the real Gateway deny/clear owner exists. + IF OLD.state = 'PENDING' AND NEW.state = 'COMMITTED' AND NEW.token_identity_fence = 3 + AND NEW.revocation_request_id = OLD.revocation_request_id + AND NEW.revocation_digest = OLD.revocation_digest THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Account token fence transition or revocation identity conflicts' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_gameplay_token_identity_fence_guard +BEFORE INSERT OR UPDATE OR DELETE ON account_gameplay_token_identity_fences +FOR EACH ROW EXECUTE FUNCTION account_gameplay_token_identity_fence_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V152__account_gameplay_login_credential_request_binding.sql b/services/account-service/src/main/resources/db/migration/V152__account_gameplay_login_credential_request_binding.sql new file mode 100644 index 0000000000..17f416099c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V152__account_gameplay_login_credential_request_binding.sql @@ -0,0 +1,87 @@ +-- Bind each newly prepared gameplay LOGIN operation to the exact transient credential +-- presentation using an Account-owned HMAC key. The key ID identifies real retained key +-- material; it is distinct from this digest schema version. Existing v1 rows remain unchanged +-- and non-authorizing because they have no credential binding. +ALTER TABLE account_gameplay_delegation_issuance_operations + DROP CONSTRAINT account_gameplay_delegation_digest_check; + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD CONSTRAINT account_gameplay_delegation_digest_check + CHECK (request_digest_version IN (1, 2) AND request_digest ~ '^[0-9a-f]{64}$'); + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD COLUMN credential_request_digest_version SMALLINT; + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD COLUMN credential_digest_key_id VARCHAR(32); + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD COLUMN credential_request_digest VARCHAR(64); + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD CONSTRAINT account_gameplay_delegation_credential_request_binding_check + CHECK ((credential_request_digest_version IS NULL + AND credential_digest_key_id IS NULL + AND credential_request_digest IS NULL) + OR (credential_request_digest_version = 1 + AND credential_digest_key_id IS NOT NULL + AND credential_digest_key_id ~ '^[A-Za-z0-9_-]{1,32}$' + AND credential_request_digest IS NOT NULL + AND credential_request_digest ~ '^[0-9a-f]{64}$')); + +-- New operations must be keyed from inception. Historical unbound operations are retained, but +-- cannot bind a token candidate or advance to COMMITTED after this migration. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_delegation_credential_request_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.credential_request_digest_version IS DISTINCT FROM 1 + OR NEW.credential_digest_key_id IS NULL + OR NEW.credential_request_digest IS NULL THEN + RAISE EXCEPTION 'Gameplay LOGIN requires an immutable keyed credential request binding' + USING ERRCODE = '23514', + CONSTRAINT = 'account_gameplay_delegation_credential_request_binding_required'; + END IF; + RETURN NEW; + END IF; + + IF NEW.credential_request_digest_version IS DISTINCT FROM OLD.credential_request_digest_version + OR NEW.credential_digest_key_id IS DISTINCT FROM OLD.credential_digest_key_id + OR NEW.credential_request_digest IS DISTINCT FROM OLD.credential_request_digest THEN + RAISE EXCEPTION 'Gameplay LOGIN credential request binding is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_gameplay_delegation_credential_request_binding_immutable'; + END IF; + + IF OLD.credential_request_digest_version IS NULL + AND (NEW.status IS DISTINCT FROM OLD.status + OR NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.signer_kid IS DISTINCT FROM OLD.signer_kid + OR NEW.signer_generation IS DISTINCT FROM OLD.signer_generation + OR NEW.pending_registry_candidate_bytes IS DISTINCT FROM OLD.pending_registry_candidate_bytes) THEN + RAISE EXCEPTION 'Historical unbound gameplay LOGIN evidence cannot advance' + USING ERRCODE = '23514', + CONSTRAINT = 'account_gameplay_delegation_unbound_request_cannot_advance'; + END IF; + + IF NEW.status = 'COMMITTED' + AND (NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.credential_request_digest_version IS DISTINCT FROM 1 + OR NEW.credential_digest_key_id IS NULL + OR NEW.credential_request_digest IS NULL) THEN + RAISE EXCEPTION 'Unbound gameplay LOGIN evidence cannot commit' + USING ERRCODE = '23514', + CONSTRAINT = 'account_gameplay_delegation_unbound_request_cannot_advance'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_credential_request_binding_guard + BEFORE INSERT OR UPDATE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_credential_request_binding_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql b/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql new file mode 100644 index 0000000000..6f9ff7f36f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V153__account_gameplay_delegation_decimal_source_versions.sql @@ -0,0 +1,143 @@ +-- V44 compared the emitted authority tuple and authoritySourceVersions against the exact current +-- owner snapshot. Both generations and source versions are protocol decimal strings, not JSON numbers. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_delegation_authority_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + source_issuer_generation BIGINT; + source_issuer_source_version BIGINT; + current_issuer_sequence BIGINT; + current_issuer_stream VARCHAR(2048); + current_account_generation BIGINT; + current_account_source_version BIGINT; + source_account_generation BIGINT; + source_account_source_version BIGINT; + current_account_sequence BIGINT; + current_account_stream VARCHAR(2048); + current_account_cutoff_generation BIGINT; + current_account_cutoff_stream VARCHAR(2048); + current_account_cutoff_sequence BIGINT; + source_account_issuance_fence BIGINT; + source_account_fence_source_version BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + expected_authority_tuple TEXT; +BEGIN + -- Keep the owner lock order: Account row, issuer/account generations and fence, then the + -- source rows whose exact optional cutoff is carried by the immutable pending intent. + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account gameplay delegation Account source is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence + INTO current_issuer_stream, source_issuer_generation, source_issuer_source_version, + current_issuer_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:issuer/firemud-account-service' + FOR UPDATE; + SELECT source_record.outbox_stream_key, source_record.current_generation, + source_record.current_source_version, source_record.last_outbox_sequence, + source_record.current_issuance_fence, + source_record.current_issuance_fence_source_version, + source_record.cutoff_generation, source_record.cutoff_stream_key, + source_record.cutoff_sequence + INTO current_account_stream, source_account_generation, source_account_source_version, + current_account_sequence, source_account_issuance_fence, + source_account_fence_source_version, current_account_cutoff_generation, + current_account_cutoff_stream, current_account_cutoff_sequence + FROM account_authority_source_records AS source_record + WHERE source_record.scope_kind = 'ACCOUNT' + AND source_record.account_uuid = NEW.account_uuid + AND source_record.issuer_id IS NULL + AND source_record.outbox_stream_key = + 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + FOR UPDATE; + + IF current_account_sequence = 0 + AND current_account_cutoff_generation IS NULL + AND current_account_cutoff_stream IS NULL + AND current_account_cutoff_sequence IS NULL THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":"' || source_account_generation::TEXT + || '","issuerAuthGeneration":"' || source_issuer_generation::TEXT || '"' + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + ELSIF current_account_sequence > 0 + AND current_account_cutoff_generation = source_account_generation + AND current_account_cutoff_stream = current_account_stream + AND current_account_cutoff_sequence = current_account_sequence THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":"' || source_account_generation::TEXT || '"' + || ',"accountSecurityCutoff":{"accountAuthorityGeneration":"' + || current_account_cutoff_generation::TEXT || '","outboxSequence":"' + || current_account_cutoff_sequence::TEXT || '","outboxStreamKey":"' + || current_account_cutoff_stream || '"},"issuerAuthGeneration":"' + || source_issuer_generation::TEXT || '"' + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + END IF; + + IF current_issuer_generation IS NULL OR current_account_generation IS NULL + OR current_issuance_fence IS NULL OR current_issuer_stream IS NULL + OR current_account_stream IS NULL OR current_issuer_sequence IS NULL + OR current_account_sequence IS NULL OR source_issuer_generation IS NULL + OR source_issuer_source_version IS NULL OR source_account_generation IS NULL + OR source_account_source_version IS NULL OR current_fence_source_version IS NULL + OR source_account_issuance_fence IS NULL OR source_account_fence_source_version IS NULL + OR expected_authority_tuple IS NULL + OR current_issuer_stream <> 'account:auth-authority:v1:issuer/firemud-account-service' + OR current_account_stream <> 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + OR source_issuer_generation <> current_issuer_generation + OR source_issuer_source_version <> current_issuer_source_version + OR source_account_generation <> current_account_generation + OR source_account_source_version <> current_account_source_version + OR source_issuer_generation <> source_issuer_source_version + OR source_issuer_generation <> current_issuer_sequence + 1 + OR source_account_generation <> source_account_source_version + OR source_account_generation <> current_account_sequence + 1 + OR current_issuance_fence <> source_account_issuance_fence + OR current_fence_source_version <> source_account_fence_source_version + OR NEW.authority_issuer_generation <> current_issuer_generation + OR NEW.authority_issuer_source_version <> current_issuer_source_version + OR NEW.authority_account_generation <> current_account_generation + OR NEW.authority_account_source_version <> current_account_source_version + OR NEW.issuance_fence <> current_issuance_fence + OR NEW.issuance_fence_source_version <> current_fence_source_version + OR convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8') <> + expected_authority_tuple + OR convert_from(NEW.membership_version_canonical_bytes, 'UTF8') <> '{}' + OR convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8') <> + '{"accountSourceVersion":"' || current_account_source_version::text + || '","issuanceFenceSourceVersion":"' || current_fence_source_version::text + || '","issuerSourceVersion":"' || current_issuer_source_version::text || '"}' THEN + RAISE EXCEPTION 'Account gameplay delegation authority snapshot is stale or missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V154__account_auth_evidence_checkpoint_key_count.sql b/services/account-service/src/main/resources/db/migration/V154__account_auth_evidence_checkpoint_key_count.sql new file mode 100644 index 0000000000..81b0ca2af6 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V154__account_auth_evidence_checkpoint_key_count.sql @@ -0,0 +1,230 @@ +-- Repair the existing exact checkpoint shape checks with PostgreSQL-supported JSONB key counts. +-- Retain the V46 migration checksum, populated owner rows, immutable bundles, and all guard predicates. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_auth_evidence_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; + account_row RECORD; + bundle JSONB; + checkpoint JSONB; + expected_account_stream TEXT; + expected_issuer_stream TEXT := 'account:auth-authority:v1:issuer/firemud-account-service'; + capture_transaction_id TEXT; + allocated_source_fence BIGINT; + allocated_operation_id UUID; + allocated_transaction_id TEXT; + checkpoint_count INTEGER; + matched_account_checkpoint BOOLEAN := FALSE; + matched_issuer_checkpoint BOOLEAN := FALSE; + checkpoint_sequence BIGINT; + stream_sequence BIGINT; + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + current_account_generation BIGINT; + current_account_source_version BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + event_row RECORD; +BEGIN + bundle := convert_from(NEW.canonical_bundle_bytes, 'UTF8')::jsonb; + capture_transaction_id := pg_current_xact_id()::text; + + SELECT last_source_fence, last_operation_id, last_transaction_id + INTO allocated_source_fence, allocated_operation_id, allocated_transaction_id + FROM account_gameplay_auth_evidence_source_fence + WHERE allocator_id = TRUE + FOR UPDATE; + IF allocated_source_fence IS NULL + OR allocated_source_fence <= 0 + OR NEW.source_fence IS DISTINCT FROM allocated_source_fence::text + OR allocated_operation_id IS DISTINCT FROM NEW.operation_id + OR allocated_transaction_id IS DISTINCT FROM capture_transaction_id + OR NEW.source_version IS DISTINCT FROM capture_transaction_id + OR NEW.linearization IS DISTINCT FROM capture_transaction_id THEN + RAISE EXCEPTION 'Account auth-evidence bundle reference is not the exact persisted capture allocation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_capture_reference'; + END IF; + + -- Match the Account owner lock order used by source snapshots and issuance: Account row, + -- issuer/account generations, issuance fence, then the operation row. The Account identity is + -- read-only here, so FOR SHARE also avoids upgrading the source reader's existing lock. + SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + INTO account_row + FROM accounts + WHERE account_uuid = NEW.account_uuid + FOR SHARE; + IF account_row.id IS NULL + OR account_row.id <> account_row.account_uuid_source_numeric_id + OR account_row.account_uuid_provenance NOT IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') + OR bundle#>>'{accountIdentitySource,sourceRowId}' IS DISTINCT FROM account_row.id::text + OR bundle#>>'{accountIdentitySource,sourceNumericId}' IS DISTINCT FROM account_row.account_uuid_source_numeric_id::text + OR bundle#>>'{accountIdentitySource,provenance}' IS DISTINCT FROM account_row.account_uuid_provenance THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the Account identity row' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_identity_match'; + END IF; + + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + + SELECT * INTO operation_row + FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF operation_row.operation_id IS NULL + OR operation_row.request_id <> NEW.request_id + OR operation_row.account_uuid <> NEW.account_uuid + OR operation_row.status <> 'PENDING' + OR bundle->>'schema' IS DISTINCT FROM NEW.bundle_schema + OR bundle->>'profile' IS DISTINCT FROM 'game-session-account-delegation' + OR bundle->>'issuer' IS DISTINCT FROM 'firemud-account-service' + OR bundle->>'audience' IS DISTINCT FROM 'account-service' + OR bundle#>>'{bundleRef,bundleVersion}' IS DISTINCT FROM NEW.bundle_version + OR bundle#>>'{bundleRef,sourceVersion}' IS DISTINCT FROM NEW.source_version + OR bundle#>>'{bundleRef,sourceFence}' IS DISTINCT FROM NEW.source_fence + OR bundle#>>'{bundleRef,linearization}' IS DISTINCT FROM NEW.linearization + OR bundle#>>'{scope,kind}' IS DISTINCT FROM 'account' + OR bundle#>>'{scope,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR jsonb_typeof(bundle#>'{scope,tenantIds}') IS DISTINCT FROM 'array' + OR COALESCE(jsonb_array_length(bundle#>'{scope,tenantIds}'), -1) <> 0 + OR bundle#>>'{operation,operationId}' IS DISTINCT FROM NEW.operation_id::text + OR bundle#>>'{operation,requestId}' IS DISTINCT FROM NEW.request_id::text + OR bundle#>>'{operation,requestDigest}' IS DISTINCT FROM operation_row.request_digest + OR bundle#>>'{operation,callerWorkload}' IS DISTINCT FROM operation_row.caller_workload + OR bundle#>>'{operation,callerContextId}' IS DISTINCT FROM operation_row.caller_context_id::text + OR bundle#>>'{operation,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR bundle#>>'{tokenIdentity,jti}' IS DISTINCT FROM operation_row.token_jti::text + OR bundle#>>'{tokenIdentity,tokenGeneration}' IS DISTINCT FROM operation_row.token_generation::text + OR bundle#>>'{tokenIdentity,iat}' IS DISTINCT FROM operation_row.issued_at_epoch_second::text + OR bundle#>>'{tokenIdentity,nbf}' IS DISTINCT FROM operation_row.not_before_epoch_second::text + OR bundle#>>'{tokenIdentity,exp}' IS DISTINCT FROM operation_row.expires_at_epoch_second::text + OR bundle->'authorityTuple' IS DISTINCT FROM + convert_from(operation_row.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR bundle->'membershipVersion' IS DISTINCT FROM + convert_from(operation_row.membership_version_canonical_bytes, 'UTF8')::jsonb + OR bundle->>'issuanceFence' IS DISTINCT FROM operation_row.issuance_fence::text + OR bundle->'authoritySourceVersions' IS DISTINCT FROM + jsonb_build_object( + 'issuerSourceVersion', operation_row.authority_issuer_source_version::text, + 'accountSourceVersion', operation_row.authority_account_source_version::text, + 'issuanceFenceSourceVersion', operation_row.issuance_fence_source_version::text) + OR NEW.issuance_fence <> operation_row.issuance_fence::text THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the exact pending operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_operation_match'; + END IF; + + IF current_issuer_generation IS NULL + OR current_account_generation IS NULL + OR current_issuance_fence IS NULL + OR operation_row.authority_issuer_generation <> current_issuer_generation + OR operation_row.authority_issuer_source_version <> current_issuer_source_version + OR operation_row.authority_account_generation <> current_account_generation + OR operation_row.authority_account_source_version <> current_account_source_version + OR operation_row.issuance_fence <> current_issuance_fence + OR operation_row.issuance_fence_source_version <> current_fence_source_version THEN + RAISE EXCEPTION 'Account auth-evidence bundle is stale against current authority' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_current_authority'; + END IF; + + expected_account_stream := 'account:auth-authority:v1:account/' || NEW.account_uuid::text; + IF jsonb_typeof(bundle->'outboxCheckpoints') <> 'array' + OR jsonb_array_length(bundle->'outboxCheckpoints') <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle requires exact issuer and Account checkpoints' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT count(*) INTO checkpoint_count FROM jsonb_array_elements(bundle->'outboxCheckpoints'); + IF checkpoint_count <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are ambiguous' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + FOR checkpoint IN SELECT value FROM jsonb_array_elements(bundle->'outboxCheckpoints') LOOP + IF checkpoint->>'outboxStreamKey' = expected_account_stream THEN + matched_account_checkpoint := TRUE; + ELSIF checkpoint->>'outboxStreamKey' = expected_issuer_stream THEN + matched_issuer_checkpoint := TRUE; + ELSE + RAISE EXCEPTION 'Account auth-evidence bundle has an out-of-scope checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF COALESCE(checkpoint->>'outboxSequence', '') !~ '^(0|[1-9][0-9]{0,18})$' THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint sequence is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + checkpoint_sequence := (checkpoint->>'outboxSequence')::BIGINT; + SELECT last_sequence INTO stream_sequence + FROM account_authority_outbox_streams + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + FOR SHARE; + IF checkpoint_sequence = 0 THEN + IF (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 2 + OR checkpoint ? 'sourceEventId' + OR checkpoint ? 'sourceEventDigest' + OR stream_sequence IS DISTINCT FROM 0 + OR EXISTS ( + SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey') THEN + RAISE EXCEPTION 'Account zero checkpoint is not an exact initialized empty stream' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + ELSE + IF (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 4 + OR checkpoint->>'sourceEventId' IS NULL + OR checkpoint->>'sourceEventDigest' IS NULL THEN + RAISE EXCEPTION 'Account positive checkpoint is missing exact event identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT event_id, event_digest INTO event_row + FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + AND outbox_sequence = checkpoint_sequence; + IF stream_sequence IS DISTINCT FROM checkpoint_sequence + OR event_row.event_id IS NULL + OR checkpoint->>'sourceEventId' <> event_row.event_id + OR checkpoint->>'sourceEventDigest' <> event_row.event_digest THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not match a current stored event' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + END IF; + END LOOP; + IF NOT matched_account_checkpoint OR NOT matched_issuer_checkpoint THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF bundle#>'{authorityTuple,accountSecurityCutoff}' IS NOT NULL THEN + IF bundle#>>'{authorityTuple,accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM expected_account_stream + OR bundle#>>'{authorityTuple,accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM + operation_row.authority_account_generation::text + OR COALESCE(bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}', '') !~ '^[1-9][0-9]{0,18}$' THEN + RAISE EXCEPTION 'Account auth-evidence security cutoff is malformed or out of scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + IF (bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}')::BIGINT > ( + SELECT (item->>'outboxSequence')::BIGINT + FROM jsonb_array_elements(bundle->'outboxCheckpoints') AS item + WHERE item->>'outboxStreamKey' = expected_account_stream) THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not cover its cutoff' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V155__account_auth_evidence_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V155__account_auth_evidence_shared_issuer_guard.sql new file mode 100644 index 0000000000..bec4ba5947 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V155__account_auth_evidence_shared_issuer_guard.sql @@ -0,0 +1,232 @@ +-- Preserve shared issuer locking during exact auth-evidence bundle capture. +-- Retain prior migration checksums, populated owner rows, immutable bundles, and all guard predicates. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_auth_evidence_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; + account_row RECORD; + bundle JSONB; + checkpoint JSONB; + expected_account_stream TEXT; + expected_issuer_stream TEXT := 'account:auth-authority:v1:issuer/firemud-account-service'; + capture_transaction_id TEXT; + allocated_source_fence BIGINT; + allocated_operation_id UUID; + allocated_transaction_id TEXT; + checkpoint_count INTEGER; + matched_account_checkpoint BOOLEAN := FALSE; + matched_issuer_checkpoint BOOLEAN := FALSE; + checkpoint_sequence BIGINT; + stream_sequence BIGINT; + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + current_account_generation BIGINT; + current_account_source_version BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + event_row RECORD; +BEGIN + bundle := convert_from(NEW.canonical_bundle_bytes, 'UTF8')::jsonb; + capture_transaction_id := pg_current_xact_id()::text; + + SELECT last_source_fence, last_operation_id, last_transaction_id + INTO allocated_source_fence, allocated_operation_id, allocated_transaction_id + FROM account_gameplay_auth_evidence_source_fence + WHERE allocator_id = TRUE + FOR UPDATE; + IF allocated_source_fence IS NULL + OR allocated_source_fence <= 0 + OR NEW.source_fence IS DISTINCT FROM allocated_source_fence::text + OR allocated_operation_id IS DISTINCT FROM NEW.operation_id + OR allocated_transaction_id IS DISTINCT FROM capture_transaction_id + OR NEW.source_version IS DISTINCT FROM capture_transaction_id + OR NEW.linearization IS DISTINCT FROM capture_transaction_id THEN + RAISE EXCEPTION 'Account auth-evidence bundle reference is not the exact persisted capture allocation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_capture_reference'; + END IF; + + -- Match the Account owner lock order used by source snapshots and issuance: Account row, + -- issuer/account generations, issuance fence, then the operation row. The Account identity is + -- read-only here, so FOR SHARE also avoids upgrading the source reader's existing lock. + SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + INTO account_row + FROM accounts + WHERE account_uuid = NEW.account_uuid + FOR SHARE; + IF account_row.id IS NULL + OR account_row.id <> account_row.account_uuid_source_numeric_id + OR account_row.account_uuid_provenance NOT IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') + OR bundle#>>'{accountIdentitySource,sourceRowId}' IS DISTINCT FROM account_row.id::text + OR bundle#>>'{accountIdentitySource,sourceNumericId}' IS DISTINCT FROM account_row.account_uuid_source_numeric_id::text + OR bundle#>>'{accountIdentitySource,provenance}' IS DISTINCT FROM account_row.account_uuid_provenance THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the Account identity row' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_identity_match'; + END IF; + + -- This guard only reads issuer authority. Keep the source reader's shared lock so concurrent + -- captures cannot deadlock while one waits for the account generation and another inserts. + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR SHARE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + + SELECT * INTO operation_row + FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF operation_row.operation_id IS NULL + OR operation_row.request_id <> NEW.request_id + OR operation_row.account_uuid <> NEW.account_uuid + OR operation_row.status <> 'PENDING' + OR bundle->>'schema' IS DISTINCT FROM NEW.bundle_schema + OR bundle->>'profile' IS DISTINCT FROM 'game-session-account-delegation' + OR bundle->>'issuer' IS DISTINCT FROM 'firemud-account-service' + OR bundle->>'audience' IS DISTINCT FROM 'account-service' + OR bundle#>>'{bundleRef,bundleVersion}' IS DISTINCT FROM NEW.bundle_version + OR bundle#>>'{bundleRef,sourceVersion}' IS DISTINCT FROM NEW.source_version + OR bundle#>>'{bundleRef,sourceFence}' IS DISTINCT FROM NEW.source_fence + OR bundle#>>'{bundleRef,linearization}' IS DISTINCT FROM NEW.linearization + OR bundle#>>'{scope,kind}' IS DISTINCT FROM 'account' + OR bundle#>>'{scope,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR jsonb_typeof(bundle#>'{scope,tenantIds}') IS DISTINCT FROM 'array' + OR COALESCE(jsonb_array_length(bundle#>'{scope,tenantIds}'), -1) <> 0 + OR bundle#>>'{operation,operationId}' IS DISTINCT FROM NEW.operation_id::text + OR bundle#>>'{operation,requestId}' IS DISTINCT FROM NEW.request_id::text + OR bundle#>>'{operation,requestDigest}' IS DISTINCT FROM operation_row.request_digest + OR bundle#>>'{operation,callerWorkload}' IS DISTINCT FROM operation_row.caller_workload + OR bundle#>>'{operation,callerContextId}' IS DISTINCT FROM operation_row.caller_context_id::text + OR bundle#>>'{operation,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR bundle#>>'{tokenIdentity,jti}' IS DISTINCT FROM operation_row.token_jti::text + OR bundle#>>'{tokenIdentity,tokenGeneration}' IS DISTINCT FROM operation_row.token_generation::text + OR bundle#>>'{tokenIdentity,iat}' IS DISTINCT FROM operation_row.issued_at_epoch_second::text + OR bundle#>>'{tokenIdentity,nbf}' IS DISTINCT FROM operation_row.not_before_epoch_second::text + OR bundle#>>'{tokenIdentity,exp}' IS DISTINCT FROM operation_row.expires_at_epoch_second::text + OR bundle->'authorityTuple' IS DISTINCT FROM + convert_from(operation_row.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR bundle->'membershipVersion' IS DISTINCT FROM + convert_from(operation_row.membership_version_canonical_bytes, 'UTF8')::jsonb + OR bundle->>'issuanceFence' IS DISTINCT FROM operation_row.issuance_fence::text + OR bundle->'authoritySourceVersions' IS DISTINCT FROM + jsonb_build_object( + 'issuerSourceVersion', operation_row.authority_issuer_source_version::text, + 'accountSourceVersion', operation_row.authority_account_source_version::text, + 'issuanceFenceSourceVersion', operation_row.issuance_fence_source_version::text) + OR NEW.issuance_fence <> operation_row.issuance_fence::text THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the exact pending operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_operation_match'; + END IF; + + IF current_issuer_generation IS NULL + OR current_account_generation IS NULL + OR current_issuance_fence IS NULL + OR operation_row.authority_issuer_generation <> current_issuer_generation + OR operation_row.authority_issuer_source_version <> current_issuer_source_version + OR operation_row.authority_account_generation <> current_account_generation + OR operation_row.authority_account_source_version <> current_account_source_version + OR operation_row.issuance_fence <> current_issuance_fence + OR operation_row.issuance_fence_source_version <> current_fence_source_version THEN + RAISE EXCEPTION 'Account auth-evidence bundle is stale against current authority' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_current_authority'; + END IF; + + expected_account_stream := 'account:auth-authority:v1:account/' || NEW.account_uuid::text; + IF jsonb_typeof(bundle->'outboxCheckpoints') <> 'array' + OR jsonb_array_length(bundle->'outboxCheckpoints') <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle requires exact issuer and Account checkpoints' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT count(*) INTO checkpoint_count FROM jsonb_array_elements(bundle->'outboxCheckpoints'); + IF checkpoint_count <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are ambiguous' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + FOR checkpoint IN SELECT value FROM jsonb_array_elements(bundle->'outboxCheckpoints') LOOP + IF checkpoint->>'outboxStreamKey' = expected_account_stream THEN + matched_account_checkpoint := TRUE; + ELSIF checkpoint->>'outboxStreamKey' = expected_issuer_stream THEN + matched_issuer_checkpoint := TRUE; + ELSE + RAISE EXCEPTION 'Account auth-evidence bundle has an out-of-scope checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF COALESCE(checkpoint->>'outboxSequence', '') !~ '^(0|[1-9][0-9]{0,18})$' THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint sequence is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + checkpoint_sequence := (checkpoint->>'outboxSequence')::BIGINT; + SELECT last_sequence INTO stream_sequence + FROM account_authority_outbox_streams + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + FOR SHARE; + IF checkpoint_sequence = 0 THEN + IF (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 2 + OR checkpoint ? 'sourceEventId' + OR checkpoint ? 'sourceEventDigest' + OR stream_sequence IS DISTINCT FROM 0 + OR EXISTS ( + SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey') THEN + RAISE EXCEPTION 'Account zero checkpoint is not an exact initialized empty stream' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + ELSE + IF (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 4 + OR checkpoint->>'sourceEventId' IS NULL + OR checkpoint->>'sourceEventDigest' IS NULL THEN + RAISE EXCEPTION 'Account positive checkpoint is missing exact event identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT event_id, event_digest INTO event_row + FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + AND outbox_sequence = checkpoint_sequence; + IF stream_sequence IS DISTINCT FROM checkpoint_sequence + OR event_row.event_id IS NULL + OR checkpoint->>'sourceEventId' <> event_row.event_id + OR checkpoint->>'sourceEventDigest' <> event_row.event_digest THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not match a current stored event' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + END IF; + END LOOP; + IF NOT matched_account_checkpoint OR NOT matched_issuer_checkpoint THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF bundle#>'{authorityTuple,accountSecurityCutoff}' IS NOT NULL THEN + IF bundle#>>'{authorityTuple,accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM expected_account_stream + OR bundle#>>'{authorityTuple,accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM + operation_row.authority_account_generation::text + OR COALESCE(bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}', '') !~ '^[1-9][0-9]{0,18}$' THEN + RAISE EXCEPTION 'Account auth-evidence security cutoff is malformed or out of scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + IF (bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}')::BIGINT > ( + SELECT (item->>'outboxSequence')::BIGINT + FROM jsonb_array_elements(bundle->'outboxCheckpoints') AS item + WHERE item->>'outboxStreamKey' = expected_account_stream) THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not cover its cutoff' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V156__account_gameplay_commit_bundle_source_fence.sql b/services/account-service/src/main/resources/db/migration/V156__account_gameplay_commit_bundle_source_fence.sql new file mode 100644 index 0000000000..5763382e78 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V156__account_gameplay_commit_bundle_source_fence.sql @@ -0,0 +1,309 @@ +-- Align the commit-proof bundle reference with the immutable V46/V84.2 source-fence contract. +-- Preserve the original transition and evidence predicates; accept only the exact stored fence. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_delegation_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + proof JSONB; + bundle_row RECORD; + envelope_row RECORD; + identity_proof JSONB; + registry JSONB; + bundle JSONB; + authority JSONB; + signer JSONB; + envelope JSONB; + proof_key_count INTEGER; + identity_key_count INTEGER; + registry_key_count INTEGER; + bundle_key_count INTEGER; + authority_key_count INTEGER; + signer_key_count INTEGER; + envelope_key_count INTEGER; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.token_hash IS NOT NULL + OR NEW.signer_kid IS NOT NULL + OR NEW.signer_generation IS NOT NULL + OR NEW.pending_registry_candidate_bytes IS NOT NULL + OR NEW.commit_proof_version IS NOT NULL + OR NEW.commit_proof_sha256 IS NOT NULL + OR NEW.commit_proof_canonical_bytes IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account gameplay delegation issuance must begin as unbound PENDING intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_initial_pending_only'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account gameplay delegation issuance evidence cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.caller_context_id IS DISTINCT FROM OLD.caller_context_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_jti IS DISTINCT FROM OLD.token_jti + OR NEW.token_generation IS DISTINCT FROM OLD.token_generation + OR NEW.issued_at_epoch_second IS DISTINCT FROM OLD.issued_at_epoch_second + OR NEW.not_before_epoch_second IS DISTINCT FROM OLD.not_before_epoch_second + OR NEW.expires_at_epoch_second IS DISTINCT FROM OLD.expires_at_epoch_second + OR NEW.authority_issuer_generation IS DISTINCT FROM OLD.authority_issuer_generation + OR NEW.authority_issuer_source_version IS DISTINCT FROM OLD.authority_issuer_source_version + OR NEW.authority_account_generation IS DISTINCT FROM OLD.authority_account_generation + OR NEW.authority_account_source_version IS DISTINCT FROM OLD.authority_account_source_version + OR NEW.issuance_fence IS DISTINCT FROM OLD.issuance_fence + OR NEW.issuance_fence_source_version IS DISTINCT FROM OLD.issuance_fence_source_version + OR NEW.authority_tuple_canonical_bytes IS DISTINCT FROM OLD.authority_tuple_canonical_bytes + OR NEW.membership_version_canonical_bytes IS DISTINCT FROM OLD.membership_version_canonical_bytes + OR NEW.authority_source_versions_canonical_bytes IS DISTINCT FROM OLD.authority_source_versions_canonical_bytes + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Account gameplay delegation intent is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + + IF OLD.status = 'COMMITTED' + OR OLD.commit_proof_version IS NOT NULL + OR OLD.commit_proof_sha256 IS NOT NULL + OR OLD.commit_proof_canonical_bytes IS NOT NULL + OR OLD.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account gameplay delegation commit evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_immutable'; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.commit_proof_version IS NOT NULL + OR NEW.commit_proof_sha256 IS NOT NULL + OR NEW.commit_proof_canonical_bytes IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Pending issuance cannot carry commit proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + IF OLD.token_hash IS NOT NULL OR OLD.signer_kid IS NOT NULL + OR OLD.signer_generation IS NOT NULL OR OLD.pending_registry_candidate_bytes IS NOT NULL + OR NEW.token_hash IS NULL OR NEW.signer_kid IS NULL + OR NEW.signer_generation IS NULL OR NEW.pending_registry_candidate_bytes IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation token identity may be bound exactly once' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_candidate_one_way'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status IS DISTINCT FROM 'COMMITTED' OR OLD.status IS DISTINCT FROM 'PENDING' + OR OLD.token_hash IS NULL OR OLD.signer_kid IS NULL + OR OLD.signer_generation IS NULL OR OLD.pending_registry_candidate_bytes IS NULL + OR NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.signer_kid IS DISTINCT FROM OLD.signer_kid + OR NEW.signer_generation IS DISTINCT FROM OLD.signer_generation + OR NEW.pending_registry_candidate_bytes IS DISTINCT FROM OLD.pending_registry_candidate_bytes + OR NEW.commit_proof_version IS DISTINCT FROM 1 + OR NEW.commit_proof_sha256 IS NULL + OR NEW.commit_proof_sha256 !~ '^[0-9a-f]{64}$' + OR NEW.commit_proof_canonical_bytes IS NULL + OR NEW.committed_at IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation COMMITTED transition is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + + proof := convert_from(NEW.commit_proof_canonical_bytes, 'UTF8')::jsonb; + IF jsonb_typeof(proof) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof is not a canonical object' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + SELECT count(*) INTO proof_key_count FROM jsonb_object_keys(proof); + IF proof_key_count <> 9 THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has unknown or missing fields' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + + identity_proof := proof->'identity'; + registry := proof->'registry'; + bundle := proof->'bundle'; + authority := proof->'authority'; + signer := proof->'signer'; + envelope := proof->'envelope'; + + IF jsonb_typeof(identity_proof) IS DISTINCT FROM 'object' + OR jsonb_typeof(registry) IS DISTINCT FROM 'object' + OR jsonb_typeof(bundle) IS DISTINCT FROM 'object' + OR jsonb_typeof(authority) IS DISTINCT FROM 'object' + OR jsonb_typeof(signer) IS DISTINCT FROM 'object' + OR jsonb_typeof(envelope) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof fields must be objects' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + SELECT count(*) INTO identity_key_count FROM jsonb_object_keys(identity_proof); + SELECT count(*) INTO registry_key_count FROM jsonb_object_keys(registry); + SELECT count(*) INTO bundle_key_count FROM jsonb_object_keys(bundle); + SELECT count(*) INTO authority_key_count FROM jsonb_object_keys(authority); + SELECT count(*) INTO signer_key_count FROM jsonb_object_keys(signer); + SELECT count(*) INTO envelope_key_count FROM jsonb_object_keys(envelope); + + IF identity_key_count <> 12 + OR NOT (identity_proof ?& ARRAY[ + 'operationId', 'requestId', 'accountId', 'requestDigest', 'callerWorkload', + 'callerContextId', 'tokenJti', 'tokenGeneration', 'issuedAtEpochSecond', + 'notBeforeEpochSecond', 'expiresAtEpochSecond', 'tokenSha256']) + OR registry_key_count <> 16 + OR NOT (registry ?& ARRAY[ + 'state', 'registryVersion', 'tokenKey', 'tokenHash', 'kid', 'signerGeneration', + 'operationId', 'requestId', 'requestDigest', 'absoluteExpiryMillis', + 'localAofCount', 'replicaAofCount', 'outcome', 'canonicalRecordSha256', + 'evidenceBundleSha256', 'aclIdentity']) + OR bundle_key_count <> 5 + OR NOT (bundle ?& ARRAY[ + 'bundleVersion', 'sourceVersion', 'sourceFence', 'linearization', 'canonicalSha256']) + OR jsonb_typeof(bundle->'sourceFence') IS DISTINCT FROM 'string' + OR bundle->>'sourceFence' IS NULL + OR bundle->>'sourceFence' !~ '^[1-9][0-9]{0,18}$' + OR authority_key_count <> 12 + OR NOT (authority ?& ARRAY[ + 'issuerGeneration', 'issuerSourceVersion', 'accountGeneration', + 'accountSourceVersion', 'issuanceFence', 'issuanceFenceSourceVersion', + 'authorityTuple', 'authoritySourceVersions', 'issuerProjectionGeneration', + 'accountProjectionGeneration', 'issuerProjectionSha256', 'accountProjectionSha256']) + OR signer_key_count <> 7 + OR NOT (signer ?& ARRAY[ + 'promotionStatus', 'promotionOperationId', 'generationOperationId', + 'targetKid', 'targetGeneration', 'correspondenceSha256', 'correspondence']) + OR envelope_key_count <> 10 + OR NOT (envelope ?& ARRAY[ + 'operationId', 'requestId', 'tokenHash', 'kid', 'signerGeneration', + 'authorityEvidenceBundleSha256', 'issuanceFence', + 'responseRecoveryExpiryEpochMillis', 'envelopeSha256', 'envelopeBytesLength']) + OR proof->>'tokenSha256' IS DISTINCT FROM NEW.token_hash + OR proof->>'registryRecordSha256' IS DISTINCT FROM registry->>'canonicalRecordSha256' + OR identity_proof->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR identity_proof->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR identity_proof->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR identity_proof->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR identity_proof->>'callerWorkload' IS DISTINCT FROM NEW.caller_workload + OR identity_proof->>'callerContextId' IS DISTINCT FROM NEW.caller_context_id::TEXT + OR identity_proof->>'tokenJti' IS DISTINCT FROM NEW.token_jti::TEXT + OR identity_proof->>'tokenGeneration' IS DISTINCT FROM NEW.token_generation::TEXT + OR identity_proof->>'issuedAtEpochSecond' IS DISTINCT FROM NEW.issued_at_epoch_second::TEXT + OR identity_proof->>'notBeforeEpochSecond' IS DISTINCT FROM NEW.not_before_epoch_second::TEXT + OR identity_proof->>'expiresAtEpochSecond' IS DISTINCT FROM NEW.expires_at_epoch_second::TEXT + OR identity_proof->>'tokenSha256' IS DISTINCT FROM NEW.token_hash + OR registry->>'state' IS DISTINCT FROM 'pending' + OR registry->>'registryVersion' IS DISTINCT FROM '1' + OR registry->>'tokenKey' IS DISTINCT FROM ('session:auth:token:' || NEW.token_hash) + OR registry->>'tokenHash' IS DISTINCT FROM NEW.token_hash + OR registry->>'kid' IS DISTINCT FROM NEW.signer_kid + OR registry->>'signerGeneration' IS DISTINCT FROM NEW.signer_generation + OR registry->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR registry->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR registry->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR registry->>'aclIdentity' IS DISTINCT FROM 'account_coord_app' + OR registry->>'absoluteExpiryMillis' IS NULL + OR registry->>'absoluteExpiryMillis' !~ '^[1-9][0-9]{0,18}$' + OR registry->>'localAofCount' IS NULL + OR registry->>'localAofCount' !~ '^[1-9][0-9]{0,3}$' + OR registry->>'replicaAofCount' IS NULL + OR registry->>'replicaAofCount' !~ '^[1-9][0-9]{0,3}$' + OR registry->>'outcome' IS NULL + OR registry->>'outcome' NOT IN ('CREATED', 'EXACT_RETRY') + OR registry->>'canonicalRecordSha256' IS NULL + OR registry->>'canonicalRecordSha256' !~ '^[0-9a-f]{64}$' + OR registry->>'evidenceBundleSha256' IS DISTINCT FROM bundle->>'canonicalSha256' + OR bundle->>'canonicalSha256' IS NULL + OR bundle->>'canonicalSha256' !~ '^[0-9a-f]{64}$' + OR authority->>'issuerGeneration' IS DISTINCT FROM NEW.authority_issuer_generation::TEXT + OR authority->>'issuerSourceVersion' IS DISTINCT FROM NEW.authority_issuer_source_version::TEXT + OR authority->>'accountGeneration' IS DISTINCT FROM NEW.authority_account_generation::TEXT + OR authority->>'accountSourceVersion' IS DISTINCT FROM NEW.authority_account_source_version::TEXT + OR authority->>'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::TEXT + OR authority->>'issuanceFenceSourceVersion' IS DISTINCT FROM NEW.issuance_fence_source_version::TEXT + OR authority->'authorityTuple' IS DISTINCT FROM + convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR authority->'authoritySourceVersions' IS DISTINCT FROM + convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8')::jsonb + OR authority->>'issuerProjectionGeneration' IS DISTINCT FROM NEW.authority_issuer_generation::TEXT + OR authority->>'accountProjectionGeneration' IS DISTINCT FROM NEW.authority_account_generation::TEXT + OR authority->>'issuerProjectionSha256' IS NULL + OR authority->>'issuerProjectionSha256' !~ '^[0-9a-f]{64}$' + OR authority->>'accountProjectionSha256' IS NULL + OR authority->>'accountProjectionSha256' !~ '^[0-9a-f]{64}$' + OR signer->>'promotionStatus' IS DISTINCT FROM 'COMMITTED' + OR signer->>'promotionOperationId' IS NULL + OR signer->>'promotionOperationId' !~ '^[0-9a-f-]{36}$' + OR signer->>'generationOperationId' IS NULL + OR signer->>'generationOperationId' !~ '^[0-9a-f-]{36}$' + OR signer->>'targetKid' IS DISTINCT FROM NEW.signer_kid + OR signer->>'targetGeneration' IS DISTINCT FROM NEW.signer_generation + OR signer->>'correspondenceSha256' IS NULL + OR signer->>'correspondenceSha256' !~ '^[0-9a-f]{64}$' + OR envelope->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR envelope->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR envelope->>'tokenHash' IS DISTINCT FROM NEW.token_hash + OR envelope->>'kid' IS DISTINCT FROM NEW.signer_kid + OR envelope->>'signerGeneration' IS DISTINCT FROM NEW.signer_generation THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof does not match its immutable intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + IF (registry->>'absoluteExpiryMillis')::BIGINT < NEW.expires_at_epoch_second * 1000 + OR (registry->>'absoluteExpiryMillis')::BIGINT > NEW.expires_at_epoch_second * 1000 + 300000 THEN + RAISE EXCEPTION 'Account gameplay delegation Redis receipt expiry is outside the immutable token bound' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + SELECT request_id, account_uuid, bundle_schema, bundle_version, source_version, + source_fence, issuance_fence, linearization, canonical_sha256, canonical_bundle_bytes + INTO bundle_row + FROM account_gameplay_delegation_auth_evidence_bundles + WHERE operation_id = NEW.operation_id; + IF bundle_row.request_id IS NULL + OR bundle_row.request_id <> NEW.request_id + OR bundle_row.account_uuid <> NEW.account_uuid + OR bundle_row.bundle_schema <> 'account-auth-evidence-bundle/v1' + OR bundle_row.bundle_version <> bundle->>'bundleVersion' + OR bundle_row.source_version <> bundle->>'sourceVersion' + OR bundle_row.source_fence <> bundle->>'sourceFence' + OR bundle_row.linearization <> bundle->>'linearization' + OR bundle_row.canonical_sha256 <> bundle->>'canonicalSha256' + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'authorityTuple' IS DISTINCT FROM + convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'membershipVersion' IS DISTINCT FROM + convert_from(NEW.membership_version_canonical_bytes, 'UTF8')::jsonb + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'authoritySourceVersions' IS DISTINCT FROM + convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8')::jsonb THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has no exact owner evidence bundle' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, + authority_evidence_bundle_sha256, issuance_fence, response_recovery_expiry_epoch_ms, + envelope_sha256, octet_length(envelope_bytes) AS envelope_bytes_length + INTO envelope_row + FROM account_gameplay_delegation_response_envelopes + WHERE operation_id = NEW.operation_id; + IF envelope_row.operation_id IS NULL + OR envelope_row.request_id <> NEW.request_id + OR envelope_row.token_hash <> NEW.token_hash + OR envelope_row.signer_kid <> NEW.signer_kid + OR envelope_row.signer_generation <> NEW.signer_generation + OR envelope_row.authority_evidence_bundle_sha256 <> bundle_row.canonical_sha256 + OR envelope_row.issuance_fence <> NEW.issuance_fence + OR envelope_row.response_recovery_expiry_epoch_ms / 1000 <> NEW.expires_at_epoch_second + OR envelope->>'authorityEvidenceBundleSha256' IS DISTINCT FROM envelope_row.authority_evidence_bundle_sha256 + OR envelope->>'issuanceFence' IS DISTINCT FROM envelope_row.issuance_fence::TEXT + OR envelope->>'responseRecoveryExpiryEpochMillis' IS DISTINCT FROM envelope_row.response_recovery_expiry_epoch_ms::TEXT + OR envelope->>'envelopeSha256' IS DISTINCT FROM envelope_row.envelope_sha256 + OR envelope->>'envelopeBytesLength' IS DISTINCT FROM envelope_row.envelope_bytes_length::TEXT THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has no exact sealed owner envelope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql b/services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql new file mode 100644 index 0000000000..02aa6c1254 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql @@ -0,0 +1,19 @@ +-- Retain the published V151 bytes and add the missing statement-level retention guard. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_token_identity_fence_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_gameplay_token_identity_fences) THEN + RAISE EXCEPTION 'Account token fence retention cannot be bypassed by truncation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_token_identity_fence_retention'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_gameplay_token_identity_fence_no_truncate + BEFORE TRUNCATE ON account_gameplay_token_identity_fences + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_token_identity_fence_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql new file mode 100644 index 0000000000..b2e2c3a5c1 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V157__account_gameplay_authority_shared_issuer_guard.sql @@ -0,0 +1,145 @@ +-- Keep the global issuer rows read-shared during issuance authority checks so distinct Account +-- snapshots and pending issuance transactions do not serialize on issuer state. Account-scoped +-- generations, fences, and source rows remain exclusively locked at their mutation boundary. +-- Preserve all V84 predicates and the immutable V1-V84.3 migration history. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_delegation_authority_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + source_issuer_generation BIGINT; + source_issuer_source_version BIGINT; + current_issuer_sequence BIGINT; + current_issuer_stream VARCHAR(2048); + current_account_generation BIGINT; + current_account_source_version BIGINT; + source_account_generation BIGINT; + source_account_source_version BIGINT; + current_account_sequence BIGINT; + current_account_stream VARCHAR(2048); + current_account_cutoff_generation BIGINT; + current_account_cutoff_stream VARCHAR(2048); + current_account_cutoff_sequence BIGINT; + source_account_issuance_fence BIGINT; + source_account_fence_source_version BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + expected_authority_tuple TEXT; +BEGIN + -- Keep the owner lock order: Account row, issuer/account generations and fence, then the + -- source rows whose exact optional cutoff is carried by the immutable pending intent. + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account gameplay delegation Account source is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR SHARE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence + INTO current_issuer_stream, source_issuer_generation, source_issuer_source_version, + current_issuer_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:issuer/firemud-account-service' + FOR SHARE; + SELECT source_record.outbox_stream_key, source_record.current_generation, + source_record.current_source_version, source_record.last_outbox_sequence, + source_record.current_issuance_fence, + source_record.current_issuance_fence_source_version, + source_record.cutoff_generation, source_record.cutoff_stream_key, + source_record.cutoff_sequence + INTO current_account_stream, source_account_generation, source_account_source_version, + current_account_sequence, source_account_issuance_fence, + source_account_fence_source_version, current_account_cutoff_generation, + current_account_cutoff_stream, current_account_cutoff_sequence + FROM account_authority_source_records AS source_record + WHERE source_record.scope_kind = 'ACCOUNT' + AND source_record.account_uuid = NEW.account_uuid + AND source_record.issuer_id IS NULL + AND source_record.outbox_stream_key = + 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + FOR UPDATE; + + IF current_account_sequence = 0 + AND current_account_cutoff_generation IS NULL + AND current_account_cutoff_stream IS NULL + AND current_account_cutoff_sequence IS NULL THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":"' || source_account_generation::TEXT + || '","issuerAuthGeneration":"' || source_issuer_generation::TEXT || '"' + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + ELSIF current_account_sequence > 0 + AND current_account_cutoff_generation = source_account_generation + AND current_account_cutoff_stream = current_account_stream + AND current_account_cutoff_sequence = current_account_sequence THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":"' || source_account_generation::TEXT || '"' + || ',"accountSecurityCutoff":{"accountAuthorityGeneration":"' + || current_account_cutoff_generation::TEXT || '","outboxSequence":"' + || current_account_cutoff_sequence::TEXT || '","outboxStreamKey":"' + || current_account_cutoff_stream || '"},"issuerAuthGeneration":"' + || source_issuer_generation::TEXT || '"' + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + END IF; + + IF current_issuer_generation IS NULL OR current_account_generation IS NULL + OR current_issuance_fence IS NULL OR current_issuer_stream IS NULL + OR current_account_stream IS NULL OR current_issuer_sequence IS NULL + OR current_account_sequence IS NULL OR source_issuer_generation IS NULL + OR source_issuer_source_version IS NULL OR source_account_generation IS NULL + OR source_account_source_version IS NULL OR current_fence_source_version IS NULL + OR source_account_issuance_fence IS NULL OR source_account_fence_source_version IS NULL + OR expected_authority_tuple IS NULL + OR current_issuer_stream <> 'account:auth-authority:v1:issuer/firemud-account-service' + OR current_account_stream <> 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + OR source_issuer_generation <> current_issuer_generation + OR source_issuer_source_version <> current_issuer_source_version + OR source_account_generation <> current_account_generation + OR source_account_source_version <> current_account_source_version + OR source_issuer_generation <> source_issuer_source_version + OR source_issuer_generation <> current_issuer_sequence + 1 + OR source_account_generation <> source_account_source_version + OR source_account_generation <> current_account_sequence + 1 + OR current_issuance_fence <> source_account_issuance_fence + OR current_fence_source_version <> source_account_fence_source_version + OR NEW.authority_issuer_generation <> current_issuer_generation + OR NEW.authority_issuer_source_version <> current_issuer_source_version + OR NEW.authority_account_generation <> current_account_generation + OR NEW.authority_account_source_version <> current_account_source_version + OR NEW.issuance_fence <> current_issuance_fence + OR NEW.issuance_fence_source_version <> current_fence_source_version + OR convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8') <> + expected_authority_tuple + OR convert_from(NEW.membership_version_canonical_bytes, 'UTF8') <> '{}' + OR convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8') <> + '{"accountSourceVersion":"' || current_account_source_version::text + || '","issuanceFenceSourceVersion":"' || current_fence_source_version::text + || '","issuerSourceVersion":"' || current_issuer_source_version::text || '"}' THEN + RAISE EXCEPTION 'Account gameplay delegation authority snapshot is stale or missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua b/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua new file mode 100644 index 0000000000..a89652374a --- /dev/null +++ b/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua @@ -0,0 +1,54 @@ +if #KEYS ~= 1 or #ARGV ~= 3 then + return -2 +end + +local mode = ARGV[1] +local expectedBytes = ARGV[2] +local candidateBytes = ARGV[3] + +if mode ~= 'ABSENT' and mode ~= 'PRESENT' and mode ~= 'VERIFY' then + return -2 +end + +if mode == 'VERIFY' then + if expectedBytes == '' or candidateBytes ~= '' then + return -2 + end +elseif mode == 'ABSENT' then + if expectedBytes ~= '' or candidateBytes == '' then + return -2 + end +elseif expectedBytes == '' or candidateBytes == '' then + return -2 +end + +local currentBytes = redis.call('GET', KEYS[1]) +if currentBytes ~= false and redis.call('PTTL', KEYS[1]) ~= -1 then + return -3 +end + +if mode == 'VERIFY' then + if currentBytes == expectedBytes then + return 0 + end + return -1 +end + +if currentBytes == candidateBytes then + return 0 +end + +if mode == 'ABSENT' then + if currentBytes ~= false then + return -1 + end + redis.call('SET', KEYS[1], candidateBytes) + return 1 +end + +if currentBytes ~= expectedBytes then + return -1 +end + +redis.call('SET', KEYS[1], candidateBytes) +return 1 diff --git a/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-activate-committed.lua b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-activate-committed.lua new file mode 100644 index 0000000000..0e73dd5957 --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-activate-committed.lua @@ -0,0 +1,62 @@ +if #KEYS ~= 1 or #ARGV ~= 3 then + return -4 +end + +local key = KEYS[1] +if not string.match(key, '^session:auth:token:[0-9a-f]+$') + or string.len(key) ~= string.len('session:auth:token:') + 64 then + return -4 +end + +local pending = ARGV[1] +local active = ARGV[2] +if not pending or string.len(pending) == 0 or string.len(pending) > 16384 + or not active or string.len(active) == 0 or string.len(active) > 16384 then + return -4 +end + +-- The two canonical values may differ in exactly the lifecycle pair. String operations preserve +-- every potentially large integer byte-for-byte and avoid cjson's lossy numeric conversion. +local versioned, versionCount = string.gsub(pending, '"registryVersion":1', '"registryVersion":2') +local expectedActive, stateCount = string.gsub(versioned, '"state":"pending"', '"state":"active"') +if versionCount ~= 1 or stateCount ~= 1 or expectedActive ~= active then + return -4 +end + +local deadline = ARGV[3] +if not deadline or not string.match(deadline, '^[1-9][0-9]*$') or string.len(deadline) > 16 then + return -4 +end +local targetExpiry = tonumber(deadline) +if not targetExpiry or targetExpiry <= 0 or targetExpiry > 9007199254740991 + or targetExpiry ~= math.floor(targetExpiry) then + return -4 +end + +local current = redis.call('GET', key) +if not current then + return -3 +end +local currentExpiry = redis.call('PEXPIRETIME', key) +if currentExpiry ~= targetExpiry then + return -2 +end + +if current == pending then + local stored = redis.call('SET', key, active, 'PXAT', deadline, 'XX') + if type(stored) ~= 'table' or stored.ok ~= 'OK' then + return -5 + end + return 1 +end + +if current == active then + -- Exact lost-ack retry: reassert only the original absolute deadline, never a relative TTL. + local stored = redis.call('SET', key, active, 'PXAT', deadline, 'XX') + if type(stored) ~= 'table' or stored.ok ~= 'OK' then + return -5 + end + return 0 +end + +return -1 diff --git a/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project.lua b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project.lua new file mode 100644 index 0000000000..7e3d12faa4 --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project.lua @@ -0,0 +1,127 @@ +local MAX_RECORD_BYTES = 8192 +-- Issuer only. Account source projections use account.account-generation-projection.v1. + +local function exact_fields(value, required, optional) + if type(value) ~= 'table' then return false end + local allowed = {} + for _, field in ipairs(required) do allowed[field] = true end + for _, field in ipairs(optional or {}) do allowed[field] = true end + for field, _ in pairs(value) do + if type(field) ~= 'string' or not allowed[field] then return false end + end + for _, field in ipairs(required) do + if value[field] == nil then return false end + end + return true +end + +local function positive_decimal(value) + if type(value) ~= 'string' + or string.match(value, '^[1-9][0-9]*$') == nil then + return false + end + return true +end + +local function nonnegative_decimal(value) + return type(value) == 'string' + and (value == '0' or string.match(value, '^[1-9][0-9]*$') ~= nil) +end + +local function decrement_decimal(value) + local digits = {} + for index = 1, string.len(value) do + digits[index] = tonumber(string.sub(value, index, index)) + end + local index = #digits + while index > 0 and digits[index] == 0 do + digits[index] = 9 + index = index - 1 + end + if index == 0 then return nil end + digits[index] = digits[index] - 1 + local result = '' + local first = 1 + while first < #digits and digits[first] == 0 do first = first + 1 end + for position = first, #digits do result = result .. tostring(digits[position]) end + return result +end + +local function generation_greater(left, right) + if string.len(left) ~= string.len(right) then + return string.len(left) > string.len(right) + end + return left > right +end + +local function validate_record(record, key) + if type(record) ~= 'string' or string.len(record) == 0 or string.len(record) > MAX_RECORD_BYTES then + return nil + end + local ok, value = pcall(cjson.decode, record) + if not ok or type(value) ~= 'table' then return nil end + + local scope = nil + local scope_id = nil + local expected_stream = nil + local issuer_prefix = 'session:auth:generation:issuer:' + if string.sub(key, 1, string.len(issuer_prefix)) == issuer_prefix then + scope = 'issuer' + scope_id = string.sub(key, string.len(issuer_prefix) + 1) + if scope_id ~= 'firemud-account-service' then return nil end + expected_stream = 'account:auth-authority:v1:issuer/' .. scope_id + else + return nil + end + + local required = { + 'schemaVersion', 'issuerId', 'issuerAuthGeneration', 'sourceVersion', + 'outboxStreamKey', 'lastAppliedSourceOutboxSequence' + } + local optional = {'lastAppliedSourceEventId', 'lastAppliedSourceEventDigest', 'sourceEvent'} + if not exact_fields(value, required, optional) + or value.schemaVersion ~= 'account-auth-issuer-generation-projection/v1' + or value.issuerId ~= scope_id + or not positive_decimal(value.issuerAuthGeneration) + or not positive_decimal(value.sourceVersion) + or value.outboxStreamKey ~= expected_stream + or not nonnegative_decimal(value.lastAppliedSourceOutboxSequence) then return nil end + if value.lastAppliedSourceOutboxSequence == '0' then + if value.issuerAuthGeneration ~= '1' or value.sourceVersion ~= '1' + or value.lastAppliedSourceEventId ~= nil or value.lastAppliedSourceEventDigest ~= nil + or value.sourceEvent ~= nil then return nil end + else + if value.issuerAuthGeneration == '1' or value.sourceVersion == '1' + or type(value.lastAppliedSourceEventId) ~= 'string' + or string.len(value.lastAppliedSourceEventId) == 0 + or type(value.lastAppliedSourceEventDigest) ~= 'string' + or string.match(value.lastAppliedSourceEventDigest, '^sha256:[0-9a-f]+$') == nil + or string.len(value.lastAppliedSourceEventDigest) ~= 71 + or type(value.sourceEvent) ~= 'string' or string.len(value.sourceEvent) == 0 then return nil end + end + + return value +end + +if #KEYS ~= 1 or #ARGV ~= 1 then return -4 end +local key = KEYS[1] +local generation_prefix = 'session:auth:generation:' +if string.len(key) > 256 + or string.sub(key, 1, string.len(generation_prefix)) ~= generation_prefix then return -4 end +local incoming = validate_record(ARGV[1], key) +if not incoming then return -4 end + +local current = redis.call('GET', key) +if current then + local existing = validate_record(current, key) + if not existing or redis.call('PTTL', key) ~= -1 then return -5 end + if generation_greater(existing.issuerAuthGeneration, incoming.issuerAuthGeneration) then return -1 end + if existing.issuerAuthGeneration == incoming.issuerAuthGeneration then + if current == ARGV[1] then return 0 end + return -2 + end +end + +local stored = redis.call('SET', key, ARGV[1]) +if type(stored) ~= 'table' or stored.ok ~= 'OK' then return -3 end +return 1 diff --git a/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-pending-register.lua b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-pending-register.lua new file mode 100644 index 0000000000..475700c06f --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-pending-register.lua @@ -0,0 +1,39 @@ +if #KEYS ~= 1 or #ARGV ~= 2 then + return -4 +end + +local key = KEYS[1] +if not string.match(key, '^session:auth:token:[0-9a-f]+$') + or string.len(key) ~= string.len('session:auth:token:') + 64 then + return -4 +end + +local record = ARGV[1] +if not record or string.len(record) == 0 or string.len(record) > 16384 then + return -4 +end + +local targetExpiry = tonumber(ARGV[2]) +if not targetExpiry or targetExpiry <= 0 or targetExpiry > 9007199254740991 + or targetExpiry ~= math.floor(targetExpiry) then + return -4 +end + +local current = redis.call('GET', key) +if current then + if current ~= record then + return -1 + end + local currentExpiry = redis.call('PEXPIRETIME', key) + if currentExpiry ~= targetExpiry then + return -2 + end + redis.call('SET', key, record, 'PXAT', ARGV[2]) + return 0 +end + +local stored = redis.call('SET', key, record, 'PXAT', ARGV[2], 'NX') +if type(stored) ~= 'table' or stored.ok ~= 'OK' then + return -3 +end +return 1 diff --git a/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json new file mode 100644 index 0000000000..55813ccfad --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json @@ -0,0 +1,36 @@ +{ + "scriptId": "account.game-session-delegation-activate-committed.v1", + "resourcePath": "redis/lua/account-game-session-delegation-activate-committed.lua", + "sha256": "3f60abccf2920b300940f757e9e746012232beeda1d20446020d62072312cd7a", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "tokenRecord", + "ownedPrefix": "session:auth:token:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + {"name": "exactCanonicalPendingRecordUtf8"}, + {"name": "exactCanonicalActiveRecordUtf8"}, + {"name": "originalAbsoluteExpiryEpochMillis"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "COMMITTED_PENDING_ACTIVATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "EXACT_ACTIVE_RETRY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "CONFLICTING_REGISTRY_RECORD", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "ABSOLUTE_EXPIRY_MISMATCH", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "PENDING_RECORD_MISSING", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_NONCANONICAL_TRANSITION", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "CONDITIONAL_ACTIVE_STORE_FAILED", "category": "CONTENTION", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "A missing, stale, or unacknowledged Account registry transition denies token use; only exact durable Account issuance owner evidence can support a retry.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "v1"}], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json new file mode 100644 index 0000000000..7c9a0214c8 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json @@ -0,0 +1,32 @@ +{ + "scriptId": "account.game-session-delegation-authority-project-issuer.v1", + "resourcePath": "redis/lua/account-game-session-delegation-authority-project.lua", + "sha256": "eaa061052d7b3a37ef2ee46f81cf3b3b66da804ac697f913dbd1ada3ed03850b", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "authorityProjection", + "ownedPrefix": "session:auth:generation:issuer:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [{"name": "canonicalProjectionUtf8"}], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "PROJECTION_ADVANCED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "EXACT_PROJECTION_RETRY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "STALE_GENERATION", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "EQUAL_GENERATION_CONFLICT", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "CONDITIONAL_STORE_FAILED", "category": "CONTENTION", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "STORED_PROJECTION_MALFORMED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "Missing or stale source projection denies delegation use until Account reprojects exact owner evidence.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "v1"}], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json new file mode 100644 index 0000000000..bf6fa19ea1 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json @@ -0,0 +1,34 @@ +{ + "scriptId": "account.game-session-delegation-pending-register.v1", + "resourcePath": "redis/lua/account-game-session-delegation-pending-register.lua", + "sha256": "1b8cb8c50e7a83674f436b06dfeb394e4a1f3502d268e72c2c768fcfaf675ac4", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "tokenRecord", + "ownedPrefix": "session:auth:token:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + {"name": "canonicalPendingRecordUtf8"}, + {"name": "absoluteExpiryEpochMillis"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "PENDING_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "EXACT_PENDING_RETRY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "CONFLICTING_RECORD", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "EXPIRY_MISMATCH", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "CONDITIONAL_STORE_FAILED", "category": "CONTENTION", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "A missing token registry projection denies token use; Account recovery requires exact durable issuance evidence.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "v1"}], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json b/services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json new file mode 100644 index 0000000000..6834920b7f --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json @@ -0,0 +1,34 @@ +{ + "scriptId": "account.account-generation-projection.v1", + "resourcePath": "redis/account_generation_projection_cas.lua", + "sha256": "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "accountGenerationProjection", + "ownedPrefix": "session:auth:generation:account:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + {"name": "expectedMode"}, + {"name": "expectedBytes"}, + {"name": "candidateBytes"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "APPLIED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "STALE", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "TTL_PRESENT", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "On loss, fail closed and rebuild only from Account's exact current durable source snapshot.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "v1"}], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json b/services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json new file mode 100644 index 0000000000..443692a76d --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json @@ -0,0 +1,34 @@ +{ + "scriptId": "account.selected-membership-generation-projection.v1", + "resourcePath": "redis/account_generation_projection_cas.lua", + "sha256": "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "membershipGenerationProjection", + "ownedPrefix": "session:auth:generation:membership:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + {"name": "expectedMode"}, + {"name": "expectedBytes"}, + {"name": "candidateBytes"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "APPLIED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "STALE", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "TTL_PRESENT", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "On loss deny selected gameplay use; reapply exact Account membership events without sequence gaps.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "v1"}], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json b/services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json new file mode 100644 index 0000000000..503886fd6c --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json @@ -0,0 +1,34 @@ +{ + "scriptId": "account.selected-tenant-generation-projection.v1", + "resourcePath": "redis/account_generation_projection_cas.lua", + "sha256": "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "tenantGenerationProjection", + "ownedPrefix": "session:auth:generation:tenant:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + {"name": "expectedMode"}, + {"name": "expectedBytes"}, + {"name": "candidateBytes"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "APPLIED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "STALE", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "TTL_PRESENT", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "On loss deny selected gameplay use; reapply exact Account source events without sequence gaps.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "v1"}], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java new file mode 100644 index 0000000000..dbe7ed701c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java @@ -0,0 +1,549 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +import java.sql.SQLException; +import java.util.ArrayList; +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.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class AccountAuthEvidenceBundlePersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_auth_bundle"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final long CONCURRENT_PROOF_TIMEOUT_SECONDS = 180L; + private static final long CONCURRENT_WORKER_SHUTDOWN_TIMEOUT_SECONDS = 100L; + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void configureDatabase() { + postgres.start(); + } + + @AfterAll + static void stopOwnedContainer() { + postgres.stop(); + } + + @Test + void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() { + TestContext context = newTestContext(MigrationVersion.fromVersion("153")); + DSLContext dsl = context.dsl(); + Account account = createAccount(context); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + PendingIntent zero = preparePending(context, sources, account.getAccountUuid()); + Map>> before = retainedOwnerRows(dsl); + + // Stock V84 cannot produce a historical bundle: its insert guard calls a nonexistent + // PostgreSQL function. The genuine capture attempt must roll back its allocator and row writes. + assertThatThrownBy( + () -> inTransaction(context, () -> bundles.captureAndPersist(zero.requestId()))) + .isInstanceOf(DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .extracting("SQLState") + .isEqualTo("42883"); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); + assertThat(dsl.fetch("SELECT * FROM account_gameplay_delegation_auth_evidence_bundles")) + .isEmpty(); + + assertThat(migrateCheckpointRepair(context)).isEqualTo(1); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); + AccountAuthEvidenceBundle zeroBundle = + inTransaction(context, () -> bundles.captureAndPersist(zero.requestId())); + assertThat(zeroBundle.fields().get("outboxCheckpoints")) + .asList() + .allSatisfy( + checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "0") + .hasSize(2)); + + AccountGameplayDelegationIssuancePersistenceIntegrationTest.advanceEmailVerifiedThroughOwner( + dsl, context.transaction(), sources, account.getAccountUuid()); + PendingIntent positive = preparePending(context, sources, account.getAccountUuid()); + AccountAuthEvidenceBundle positiveBundle = + inTransaction(context, () -> bundles.captureAndPersist(positive.requestId())); + assertThat(positiveBundle.fields().get("outboxCheckpoints")) + .asList() + .anySatisfy( + checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "1") + .containsKeys("sourceEventId", "sourceEventDigest") + .hasSize(4)); + var retainedBundles = + dsl.fetch( + "SELECT * FROM account_gameplay_delegation_auth_evidence_bundles ORDER BY operation_id") + .intoMaps(); + assertThat(retainedBundles).hasSize(2); + var retainedOwners = retainedOwnerRows(dsl); + assertThat(migrateCheckpointRepair(context)).isZero(); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(retainedOwners); + assertThat( + dsl.fetch( + "SELECT * FROM account_gameplay_delegation_auth_evidence_bundles ORDER BY operation_id") + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(retainedBundles); + assertThat( + inTransaction(context, () -> bundles.readStoredNonAuthorizingValue(zero.operationId())) + .canonicalBytes()) + .isEqualTo(zeroBundle.canonicalBytes()); + assertThat( + inTransaction( + context, () -> bundles.readStoredNonAuthorizingValue(positive.operationId())) + .canonicalBytes()) + .isEqualTo(positiveBundle.canonicalBytes()); + } + + @Test + void repairedGuardRejectsExtraAndMissingKeysInBothRealCheckpointBranches() throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + Account account = createAccount(context); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuancePersistenceIntegrationTest.advanceEmailVerifiedThroughOwner( + dsl, context.transaction(), sources, account.getAccountUuid()); + for (boolean positive : List.of(false, true)) { + for (boolean extraKey : List.of(false, true)) { + PendingIntent pending = preparePending(context, sources, account.getAccountUuid()); + var before = retainedOwnerRows(dsl); + DSLContext corruptingInsert = spy(dsl); + // Fault injection changes only a real owner-produced bundle at its SQL insert boundary; + // no owner authority, operation, checkpoint, or committed row is fabricated. + doAnswer( + invocation -> { + Object[] bindings = ((Object[]) invocation.getRawArguments()[1]).clone(); + bindings[10] = corruptCheckpointKeys((byte[]) bindings[10], positive, extraKey); + return dsl.execute((String) invocation.getRawArguments()[0], bindings); + }) + .when(corruptingInsert) + .execute( + startsWith("INSERT INTO account_gameplay_delegation_auth_evidence_bundles"), + any(Object[].class)); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(corruptingInsert, authorities, outbox); + assertThatThrownBy( + () -> inTransaction(context, () -> bundles.captureAndPersist(pending.requestId()))) + .isInstanceOf(DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .extracting("SQLState") + .isEqualTo("23514"); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); + assertThat(dsl.fetch("SELECT * FROM account_gameplay_delegation_auth_evidence_bundles")) + .isEmpty(); + } + } + } + + private static byte[] corruptCheckpointKeys(byte[] original, boolean positive, boolean extraKey) + throws Exception { + JsonMapper json = JsonMapper.builder().build(); + Map fields = + json.readValue(original, new TypeReference>() {}); + List checkpoints = new ArrayList<>((List) fields.get("outboxCheckpoints")); + boolean corrupted = false; + for (int i = 0; i < checkpoints.size(); i++) { + Map checkpoint = (Map) checkpoints.get(i); + if (positive == !"0".equals(checkpoint.get("outboxSequence"))) { + Map changed = new LinkedHashMap<>(checkpoint); + if (extraKey) changed.put("unexpected", true); + else changed.remove(positive ? "sourceEventDigest" : "outboxStreamKey"); + checkpoints.set(i, changed); + corrupted = true; + break; + } + } + assertThat(corrupted).isTrue(); + fields.put("outboxCheckpoints", checkpoints); + return Rfc8785CanonicalJson.canonicalizeUtf8(json.writeValueAsString(fields)); + } + + private static PendingIntent preparePending( + TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) { + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + PendingIntent pending = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot(currentSnapshot(context, sources, accountId)), + AccountGameplayCredentialRequestBindingFixture.binding()); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources); + inTransaction(context, () -> issuance.beginPending(pending)); + return pending; + } + + private static Map>> retainedOwnerRows(DSLContext dsl) { + Map>> rows = new LinkedHashMap<>(); + for (String table : + List.of( + "accounts", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_source_records", + "account_authority_outbox_streams", + "account_authority_outbox_events", + "account_gameplay_delegation_issuance_operations", + "account_gameplay_auth_evidence_source_fence")) { + rows.put(table, dsl.fetch("SELECT * FROM " + table + " ORDER BY 1").intoMaps()); + } + return rows; + } + + @Test + void freshOwnerBaselinesProduceExactZeroCheckpointBundlesAndConcurrentRetryReadback() + throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + Account account = createAccount(context); + UUID accountId = account.getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sourceEvidence, accountId); + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + PendingIntent pending = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot(snapshot), + AccountGameplayCredentialRequestBindingFixture.binding()); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence); + inTransaction(context, () -> issuance.beginPending(pending)); + + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + CountDownLatch captureStart = new CountDownLatch(1); + ExecutorService concurrentCaptures = Executors.newFixedThreadPool(2); + var firstCapture = + concurrentCaptures.submit( + () -> { + captureStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); + var secondCapture = + concurrentCaptures.submit( + () -> { + captureStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); + AccountAuthEvidenceBundle first; + AccountAuthEvidenceBundle concurrentRetry; + try { + captureStart.countDown(); + first = awaitConcurrentProof(firstCapture); + concurrentRetry = awaitConcurrentProof(secondCapture); + } finally { + stopConcurrentProofWorkers(concurrentCaptures); + } + assertThat(concurrentRetry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + var exactRetry = inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + assertThat(exactRetry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(first.fields()).containsEntry("schema", "account-auth-evidence-bundle/v1"); + assertThat(first.fields().get("bundleRef")) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("bundleVersion", "1") + .containsEntry("sourceFence", "1"); + Map firstReference = (Map) first.fields().get("bundleRef"); + assertThat(firstReference.get("sourceVersion")).isInstanceOf(String.class); + assertThat((String) firstReference.get("sourceVersion")).matches("[1-9][0-9]{0,19}"); + assertThat(firstReference.get("linearization")).isEqualTo(firstReference.get("sourceVersion")); + assertThat(first.fields().get("authoritySourceVersions")) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("accountSourceVersion", "1"); + assertThat(((Map) first.fields().get("tokenIdentity")).get("tokenGeneration")) + .isEqualTo("1"); + Map firstAuthorityTuple = (Map) first.fields().get("authorityTuple"); + assertThat(firstAuthorityTuple.get("issuerAuthGeneration")).isEqualTo("1"); + assertThat(firstAuthorityTuple.get("accountAuthorityGeneration")).isEqualTo("1"); + Object accountAuthoritySourceVersion = + ((Map) first.fields().get("authoritySourceVersions")).get("accountSourceVersion"); + assertThat(firstReference.get("sourceVersion")).isNotEqualTo(accountAuthoritySourceVersion); + + PendingIntent nextPending = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot(snapshot), + AccountGameplayCredentialRequestBindingFixture.binding()); + inTransaction(context, () -> issuance.beginPending(nextPending)); + AccountAuthEvidenceBundle nextBundle = + inTransaction(context, () -> bundles.captureAndPersist(nextPending.requestId())); + Map nextReference = (Map) nextBundle.fields().get("bundleRef"); + assertThat(nextReference.get("sourceFence")).isEqualTo("2"); + assertThat(new java.math.BigInteger((String) nextReference.get("sourceFence"))) + .isGreaterThan(new java.math.BigInteger((String) firstReference.get("sourceFence"))); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_auth_evidence_bundles " + + "SET source_fence = '99' WHERE operation_id = ?", + pending.operationId()))) + .isInstanceOf(RuntimeException.class); + assertThat(first.fields().get("outboxCheckpoints")) + .asList() + .allSatisfy( + checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "0") + .doesNotContainKeys("sourceEventId", "sourceEventDigest")); + Long bundleCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS bundle_count " + + "FROM account_gameplay_delegation_auth_evidence_bundles"), + "bundle count query must return a row") + .get("bundle_count", Long.class); + assertThat(bundleCount).isEqualTo(2L); + + Account updated = + inTransaction( + context, + () -> { + AccountRepository accounts = + new AccountRepository( + dsl, + new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl))); + Account row = accounts.findByAccountUuid(accountId).orElseThrow(); + row.setRole("moderator"); + return accounts.save(row); + }); + assertThat(updated.getRole()).isEqualTo("moderator"); + assertThatThrownBy( + () -> inTransaction(context, () -> bundles.captureAndPersist(pending.requestId()))) + .isInstanceOf(AccountAuthEvidenceBundleRepository.OwnerEvidenceUnavailableException.class); + String storedCanonicalDigest = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT canonical_sha256 FROM " + + "account_gameplay_delegation_auth_evidence_bundles WHERE operation_id = ?", + pending.operationId()), + "stored bundle digest query must return a row") + .get("canonical_sha256", String.class); + assertThat(storedCanonicalDigest).isEqualTo(first.canonicalSha256()); + } + + private static Account createAccount(TestContext context) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + account.setUsername("auth-bundle-" + suffix); + account.setEmail("auth-bundle-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + // The fresh Account birth path creates the exact empty global-role source only for null role. + DSLContext dsl = context.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + return inTransaction( + context, + () -> { + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(dsl, sourceEvidence).save(account); + }); + } + + private static IssuerAccountSourceSnapshot currentSnapshot( + TestContext context, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + UUID accountId) { + return inTransaction( + context, () -> sourceEvidence.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot snapshot) { + var cutoff = + snapshot + .account() + .accountSecurityCutoff() + .map( + value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + return new AccountAuthoritySnapshot( + snapshot.account().scope().accountId(), + snapshot.issuer().generation(), + snapshot.issuer().sourceVersion(), + snapshot.account().generation(), + snapshot.account().sourceVersion(), + snapshot.issuanceFence().value(), + snapshot.issuanceFence().sourceVersion(), + cutoff); + } + + private TestContext newTestContext() { + return newTestContext(null); + } + + private TestContext newTestContext(MigrationVersion target) { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) configuration.target(target); + configuration.load().migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), + dsl, + dataSource, + schema); + } + + private static int migrateCheckpointRepair(TestContext context) { + return Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("154")) + .load() + .migrate() + .migrationsExecuted; + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static T awaitConcurrentProof(Future future) + throws InterruptedException, TimeoutException { + try { + return future.get(CONCURRENT_PROOF_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (ExecutionException workerFailure) { + throw new AssertionError( + "Concurrent bundle persistence proof worker failed;sqlstate=" + + safeWorkerSqlState(workerFailure)); + } + } + + private static String safeWorkerSqlState(Throwable failure) { + Throwable current = failure; + for (int depth = 0; current != null && depth < 8; depth++) { + if (current instanceof SQLException sqlFailure) { + String sqlState = sqlFailure.getSQLState(); + if (sqlState != null && sqlState.matches("[0-9A-Z]{5}")) return sqlState; + } + current = current.getCause(); + } + return "UNKNOWN"; + } + + private static void stopConcurrentProofWorkers(ExecutorService executor) { + executor.shutdownNow(); + try { + if (!executor.awaitTermination( + CONCURRENT_WORKER_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new AssertionError("Concurrent bundle persistence proof workers did not terminate"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("Concurrent bundle persistence proof cleanup was interrupted"); + } + } + + private record TestContext( + TransactionTemplate transaction, + DSLContext dsl, + DriverManagerDataSource dataSource, + String schema) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java new file mode 100644 index 0000000000..62a0f9d7e0 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -0,0 +1,2535 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import de.mkammerer.argon2.Argon2; +import de.mkammerer.argon2.Argon2Factory; +import io.grpc.Context; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.BoundTokenCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.StaleAuthorityException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigester; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommitSignerFixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.postgresql.util.PSQLException; +import org.postgresql.util.ServerErrorMessage; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationIssuancePersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_gameplay_issuance"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + + @TempDir Path temporaryDirectory; + private final AtomicReference capturedCommitProof = new AtomicReference<>(); + + @BeforeAll + static void configureDatabase() { + postgres.start(); + } + + @AfterAll + static void stopOwnedContainer() { + postgres.stop(); + } + + @Test + void safeCommitFailureDiagnosticAllowsOnlyKnownConstraintsAndSqlState() { + PSQLException allowedConstraint = + new PSQLException( + new ServerErrorMessage( + "SERROR\u0000VERROR\u0000C23514\u0000" + + "naccount_gameplay_delegation_commit_shape\u0000\u0000"), + false); + assertThat( + AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic( + new SQLException("private wrapper details", "99999", allowedConstraint))) + .isEqualTo("sqlstate=23514;constraint=account_gameplay_delegation_commit_shape"); + + PSQLException unlistedConstraint = + new PSQLException( + new ServerErrorMessage( + "SERROR\u0000VERROR\u0000C23514\u0000" + "nprivate_token_payload\u0000\u0000"), + false); + String suppressed = + AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic( + new SQLException("private wrapper details", "99999", unlistedConstraint)); + assertThat(suppressed) + .isEqualTo("sqlstate=23514;constraint=UNKNOWN") + .doesNotContain("private", "token", "payload"); + + String unknown = + AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic( + new IllegalStateException("private exception details")); + assertThat(unknown).isEqualTo("sqlstate=UNKNOWN;constraint=UNKNOWN").doesNotContain("private"); + } + + @Test + void commitProofRequiresCanonicalExactStoredBundleSourceFence() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.CAPTURE_COMMIT_PROOF, false, false); + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class); + + byte[] validProof = Objects.requireNonNull(capturedCommitProof.get()); + Record evidenceBefore = readCommitBundleEvidence(harness); + String sourceFence = evidenceBefore.get("source_fence", String.class); + String validProofJson = new String(validProof, StandardCharsets.UTF_8); + assertThat(validProofJson).contains("\"sourceFence\":\"" + sourceFence + "\""); + + byte[] missingSourceFence = removeCommitProofSourceFence(validProof, sourceFence); + assertCommitProofRejected( + harness, missingSourceFence, "account_gameplay_delegation_commit_evidence_match"); + + byte[] changedSourceFence = + replaceCommitProofSourceFence( + validProof, sourceFence, Long.toString(Long.parseLong(sourceFence) + 1L)); + assertCommitProofRejected( + harness, changedSourceFence, "account_gameplay_delegation_commit_evidence_match"); + + byte[] noncanonicalSourceFence = replaceCommitProofSourceFence(validProof, sourceFence, "01"); + assertCommitProofRejected( + harness, noncanonicalSourceFence, "account_gameplay_delegation_commit_evidence_match"); + + assertPendingWithoutCommitProof(harness); + assertThat(tokenFenceCount(harness)).isZero(); + assertCommitBundleEvidenceUnchanged(harness, evidenceBefore); + verify(harness.issuance(), times(1)) + .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); + PendingRegistryCandidate pendingBeforeRetry = + inTransaction( + harness.context(), + () -> harness.issuance().readPendingRegistryCandidate(harness.pending().requestId())); + Record envelopeBeforeRetry = readResponseEnvelope(harness); + + // The exact original proof succeeds after the invalid variants leave all owner evidence intact. + reset(harness.issuance()); + assertThat(harness.service().commitPendingCandidate(harness.pending().requestId()).outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + assertThat(tokenFenceCount(harness)).isEqualTo(1L); + assertCommitBundleEvidenceUnchanged(harness, evidenceBefore); + verify(harness.issuance(), never()) + .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); + Record committedCandidate = readCandidateRow(harness); + assertThat(committedCandidate.get("token_hash", String.class)) + .isEqualTo(pendingBeforeRetry.tokenHash()); + assertThat(committedCandidate.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(pendingBeforeRetry.canonicalRecordBytes()); + Record envelopeAfterRetry = readResponseEnvelope(harness); + assertThat(envelopeAfterRetry.get("envelope_sha256", String.class)) + .isEqualTo(envelopeBeforeRetry.get("envelope_sha256", String.class)); + assertThat(envelopeAfterRetry.get("envelope_bytes", byte[].class)) + .containsExactly(envelopeBeforeRetry.get("envelope_bytes", byte[].class)); + } + + @Test + void createsRequestIdentityFromCurrentAccountAuthorityAndReplaysItExactly() { + TestContext context = newTestContext(); + UUID accountId = createAccount(context).getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + + var created = + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + CALLER_WORKLOAD, + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding())); + var replay = + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + CALLER_WORKLOAD, + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding())); + + assertThat(created.created()).isTrue(); + assertThat(created.identity().accountId()).isEqualTo(accountId); + assertThat(created.identity().requestId()).isEqualTo(requestId); + assertThat(created.identity().callerWorkload()).isEqualTo(CALLER_WORKLOAD); + assertThat(created.identity().callerContextId()).isEqualTo(callerContextId); + assertThat(created.identity().operationId()).isEqualTo(created.operation().operationId()); + assertThat(created.identity().tokenJti()).isEqualTo(created.operation().tokenJti()); + assertThat(created.identity().expiresAtEpochSecond() - created.identity().issuedAtEpochSecond()) + .isEqualTo(GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); + assertThat(replay.created()).isFalse(); + assertThat(replay.identity()).isEqualTo(created.identity()); + assertThat(replay.operation()).isEqualTo(created.operation()); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + "spiffe://firemud/ns/other/sa/game-session-service", + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + CALLER_WORKLOAD, + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + UUID otherAccountId = createAccount(context).getAccountUuid(); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + otherAccountId, + CALLER_WORKLOAD, + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + + Record operationCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + requestId), + "Operation count query must return a row"); + assertThat(operationCount.get(0, Long.class)).isEqualTo(1L); + } + + @Test + void credentialBindingMigrationRetainsLegacyEvidenceAndRequiresImmutableBoundRows() + throws Exception { + // V151 is the receiving pre-binding schema immediately before V152. + TestContext context = newTestContextAtVersion("151"); + Account account = createAccount(context); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + PendingIntent retainedIntent = + intent( + currentSnapshot(context, sources, account.getAccountUuid()), account.getAccountUuid()); + insertRetainedUnboundPendingOperation(context.dsl(), retainedIntent); + Record beforeMigration = + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + retainedIntent.requestId()); + assertThat(beforeMigration).isNotNull(); + + migrateTestSchemaToLatest(context); + + Record retained = + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + retainedIntent.requestId()); + assertThat(retained).isNotNull(); + assertThat(retained.intoMap()).containsAllEntriesOf(beforeMigration.intoMap()); + assertThat(retained.get("operation_id", UUID.class)) + .isEqualTo(beforeMigration.get("operation_id", UUID.class)); + assertThat(retained.get("request_digest_version", Short.class)).isEqualTo((short) 1); + assertThat(retained.get("request_digest", String.class)) + .isEqualTo(beforeMigration.get("request_digest", String.class)); + assertThat(retained.get("status", String.class)).isEqualTo("PENDING"); + assertThat(retained.get("token_hash", String.class)).isNull(); + assertThat(retained.get("signer_kid", String.class)).isNull(); + assertThat(retained.get("signer_generation", String.class)).isNull(); + assertThat(retained.get("pending_registry_candidate_bytes", byte[].class)).isNull(); + assertThat(retained.get("credential_request_digest_version", Short.class)).isNull(); + assertThat(retained.get("credential_digest_key_id", String.class)).isNull(); + assertThat(retained.get("credential_request_digest", String.class)).isNull(); + + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> repository.readCurrentGameplayLoginReplay(retainedIntent.requestId()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.StorageUnavailableException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET token_hash = ?, signer_kid = ?, signer_generation = ?, " + + "pending_registry_candidate_bytes = ? WHERE request_id = ?", + "cd".repeat(32), + "integration-key", + "1", + new byte[] {1, 2, 3}, + retainedIntent.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED' WHERE request_id = ?", + retainedIntent.requestId()))) + .isInstanceOf(DataAccessException.class); + Record retainedAfterDeniedAdvances = + context + .dsl() + .fetchOne( + "SELECT status, token_hash, pending_registry_candidate_bytes, " + + "credential_request_digest_version, credential_digest_key_id, " + + "credential_request_digest " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + retainedIntent.requestId()); + assertThat(retainedAfterDeniedAdvances.get("status", String.class)).isEqualTo("PENDING"); + assertThat(retainedAfterDeniedAdvances.get("token_hash", String.class)).isNull(); + assertThat(retainedAfterDeniedAdvances.get("pending_registry_candidate_bytes", byte[].class)) + .isNull(); + assertThat(retainedAfterDeniedAdvances.get("credential_request_digest_version", Short.class)) + .isNull(); + assertThat(retainedAfterDeniedAdvances.get("credential_digest_key_id", String.class)).isNull(); + assertThat(retainedAfterDeniedAdvances.get("credential_request_digest", String.class)).isNull(); + + var binding = AccountGameplayCredentialRequestBindingFixture.binding(); + UUID newRequestId = UUID.randomUUID(); + inTransaction( + context, + () -> + repository.beginPendingForAccount( + newRequestId, + account.getAccountUuid(), + CALLER_WORKLOAD, + UUID.randomUUID(), + binding)); + Record bound = + context + .dsl() + .fetchOne( + "SELECT request_digest_version, credential_request_digest_version, " + + "credential_digest_key_id, credential_request_digest " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + newRequestId); + assertThat(bound.get("request_digest_version", Short.class)).isEqualTo((short) 2); + assertThat(bound.get("credential_request_digest_version", Short.class)) + .isEqualTo((short) binding.digestSchemaVersion()); + assertThat(bound.get("credential_digest_key_id", String.class)) + .isEqualTo(binding.digestKeyId()); + assertThat(bound.get("credential_request_digest", String.class)) + .isEqualTo(binding.credentialRequestDigest()); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET credential_request_digest = ? WHERE request_id = ?", + "cd".repeat(32), + newRequestId))) + .isInstanceOf(DataAccessException.class); + Record boundAfterDeniedMutation = + context + .dsl() + .fetchOne( + "SELECT credential_request_digest_version, credential_digest_key_id, " + + "credential_request_digest " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + newRequestId); + assertThat(boundAfterDeniedMutation.get("credential_request_digest_version", Short.class)) + .isEqualTo((short) binding.digestSchemaVersion()); + assertThat(boundAfterDeniedMutation.get("credential_digest_key_id", String.class)) + .isEqualTo(binding.digestKeyId()); + assertThat(boundAfterDeniedMutation.get("credential_request_digest", String.class)) + .isEqualTo(binding.credentialRequestDigest()); + } + + @Test + void deterministicOtpFixtureAndCanonicalLoginCommitBeforeReturningCredential() throws Exception { + TestContext context = newTestContext(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + Account account = createEmailOtpAccount(context, sources); + AccountEmailLoginChallengeRepository challenges = + new AccountEmailLoginChallengeRepository(context.dsl()); + AccountEmailLoginChallenge challenge = + persistEmailLoginChallenge(context, challenges, account.getId(), "123456"); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl())); + AccountGameplayDelegationIssuanceRepository issuances = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources, bundles); + CommitHarness harness = + buildCommitHarness( + context, account.getAccountUuid(), sources, bundles, issuances, null, null); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + CanonicalGameplayLoginRequest request = + canonicalLoginRequest(account.getEmail(), "123456", requestId, callerContextId); + + var result = + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + request, + CALLER_WORKLOAD, + deterministicOtpCredentialVerifier(challenges, "123456"))); + + assertThat(result.accountId()).isEqualTo(account.getAccountUuid()); + assertThat(result.tokenJti()).isNotNull(); + assertThat(result.compactJwtBytes()).isNotEmpty(); + assertThat(result.expiresAtEpochSecond()).isPositive(); + assertThat(result.toString()).doesNotContain("123456"); + assertThat(challenges.findByAccountId(account.getId())).isEmpty(); + Record stored = + context + .dsl() + .fetchOne( + "SELECT status, account_uuid, token_jti, caller_context_id " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + requestId); + assertThat(stored).isNotNull(); + assertThat(stored.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(stored.get("account_uuid", UUID.class)).isEqualTo(account.getAccountUuid()); + assertThat(stored.get("token_jti", UUID.class)).isEqualTo(result.tokenJti()); + assertThat(stored.get("caller_context_id", UUID.class)).isEqualTo(callerContextId); + assertThat(harness.redis().registeredRecord()).isNotEmpty(); + assertThat(challenge.getId()).isNotNull(); + } + + @Test + void failureAfterOtpDeleteRollsBackCanonicalLoginAndOtpConsumption() throws Exception { + TestContext context = newTestContext(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + Account account = createEmailOtpAccount(context, sources); + AccountEmailLoginChallengeRepository actualChallenges = + new AccountEmailLoginChallengeRepository(context.dsl()); + AccountEmailLoginChallenge challenge = + persistEmailLoginChallenge(context, actualChallenges, account.getId(), "654321"); + AccountEmailLoginChallengeRepository challenges = spy(actualChallenges); + doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException("simulated failure after OTP deletion"); + }) + .when(challenges) + .delete(any(AccountEmailLoginChallenge.class)); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl())); + AccountGameplayDelegationIssuanceRepository issuances = + new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources, bundles); + CommitHarness harness = + buildCommitHarness( + context, account.getAccountUuid(), sources, bundles, issuances, null, null); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + CanonicalGameplayLoginRequest request = + canonicalLoginRequest(account.getEmail(), "654321", requestId, callerContextId); + + assertThatThrownBy( + () -> + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + request, + CALLER_WORKLOAD, + deterministicOtpCredentialVerifier(challenges, "654321")))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulated failure"); + + AccountEmailLoginChallenge restored = + actualChallenges.findByAccountId(account.getId()).orElseThrow(); + assertThat(restored.getId()).isEqualTo(challenge.getId()); + assertThat(restored.getCodeHash()).isEqualTo(challenge.getCodeHash()); + Record operationCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + requestId), + "Operation count query must return a row"); + assertThat(operationCount.get(0, Long.class)).isEqualTo(0L); + assertThat(harness.redis().registeredRecord()).isNull(); + } + + @Test + void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + UUID accountId = createAccount(context).getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(dsl, authorities); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + IssuerAccountSourceSnapshot firstSnapshot = currentSnapshot(context, sources, accountId); + PendingIntent firstIntent = intent(firstSnapshot, accountId); + + var first = inTransaction(context, () -> repository.beginPending(firstIntent)); + var exactRetry = inTransaction(context, () -> repository.beginPending(firstIntent)); + assertThat(exactRetry).isEqualTo(first); + assertThat(first.candidateBound()).isFalse(); + assertThat(readCandidate(dsl, firstIntent.requestId()).authorityTupleBytes()) + .isEqualTo(canonicalBytes(GameSessionAccountDelegationProfile.authorityTuple(1L, 1L))); + + PendingIntent changedContext = + new PendingIntent( + firstIntent.operationId(), + firstIntent.requestId(), + firstIntent.callerWorkload(), + UUID.randomUUID(), + firstIntent.tokenJti(), + firstIntent.issuedAtEpochSecond(), + firstIntent.notBeforeEpochSecond(), + firstIntent.expiresAtEpochSecond(), + firstIntent.authoritySnapshot(), + firstIntent.credentialRequestBinding()); + assertThatThrownBy(() -> inTransaction(context, () -> repository.beginPending(changedContext))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + + String mismatchedTimeCandidate = + compactCandidate(firstIntent, firstIntent.expiresAtEpochSecond() + 1L); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.bindSignedCandidate( + firstIntent.requestId(), mismatchedTimeCandidate, "1"))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + assertThat(readCandidate(dsl, firstIntent.requestId()).tokenHash()).isNull(); + + String compactJwt = compactCandidate(firstIntent); + AccountResponseEnvelopeCryptography responseCryptography = + mock(AccountResponseEnvelopeCryptography.class); + byte[] ciphertext = new byte[] {3, 1, 4, 1, 5}; + when(responseCryptography.encrypt( + any(Binding.class), any(byte[].class), any(java.time.Instant.class))) + .thenReturn(new EncryptedResponseEnvelope(ciphertext)); + AccountGameplayDelegationResponseEnvelopeRepository responses = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, responseCryptography); + CallerIdentity caller = + new CallerIdentity(firstIntent.callerWorkload(), firstIntent.callerContextId()); + BindReadSeal boundReadSeal = + inTransaction( + context, + () -> { + BoundTokenCandidate boundCandidate = + repository.bindSignedCandidate(firstIntent.requestId(), compactJwt, "1"); + PendingRegistryCandidate persistedCandidate = + repository.readPendingRegistryCandidate(firstIntent.requestId()); + SealedCandidateObservation sealed = + responses.sealPendingCandidate(firstIntent.requestId(), caller, compactJwt); + return new BindReadSeal(boundCandidate, persistedCandidate, sealed); + }); + BoundTokenCandidate bound = boundReadSeal.bound(); + assertThat(boundReadSeal.persisted().tokenHash()).isEqualTo(bound.tokenHash()); + assertThat(boundReadSeal.persisted().canonicalRecordBytes()).isNotEmpty(); + assertThat(boundReadSeal.sealed().operationId()).isEqualTo(firstIntent.operationId()); + assertThat(boundReadSeal.sealed().requestId()).isEqualTo(firstIntent.requestId()); + assertThat(boundReadSeal.sealed().envelopeBytesLength()).isPositive(); + var boundRetry = + inTransaction( + context, + () -> repository.bindSignedCandidate(firstIntent.requestId(), compactJwt, "1")); + assertThat(boundRetry).isEqualTo(bound); + assertThat(bound.tokenHash()).hasSize(64).matches("[0-9a-f]{64}"); + + RecordData persisted = readCandidate(dsl, firstIntent.requestId()); + assertThat(new String(persisted.candidateBytes(), StandardCharsets.UTF_8)) + .doesNotContain(compactJwt); + assertThat(persisted.status()).isEqualTo("PENDING"); + assertThat(persisted.tokenHash()).isEqualTo(bound.tokenHash()); + assertThat(persisted.authorityTupleBytes()) + .isEqualTo(canonicalBytes(GameSessionAccountDelegationProfile.authorityTuple(1L, 1L))); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET token_hash = ? WHERE request_id = ?", + "f".repeat(64), + firstIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("token identity may be bound exactly once"); + + advanceEmailVerifiedThroughOwner(dsl, context.transaction(), sources, accountId); + assertThatThrownBy(() -> inTransaction(context, () -> repository.beginPending(firstIntent))) + .isInstanceOf(StaleAuthorityException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> repository.bindSignedCandidate(firstIntent.requestId(), compactJwt, "1"))) + .isInstanceOf(StaleAuthorityException.class); + RecordData accountAdvancePersisted = readCandidate(dsl, firstIntent.requestId()); + assertThat(accountAdvancePersisted.status()).isEqualTo(persisted.status()); + assertThat(accountAdvancePersisted.tokenHash()).isEqualTo(persisted.tokenHash()); + assertThat(accountAdvancePersisted.candidateBytes()) + .containsExactly(persisted.candidateBytes()); + assertThat(accountAdvancePersisted.authorityTupleBytes()) + .containsExactly(persisted.authorityTupleBytes()); + + IssuerAccountSourceSnapshot afterAccountAdvance = currentSnapshot(context, sources, accountId); + PendingIntent secondIntent = intent(afterAccountAdvance, accountId); + inTransaction(context, () -> repository.beginPending(secondIntent)); + assertThat(secondIntent.authoritySnapshot().accountSecurityCutoff()).isPresent(); + byte[] advancedAuthorityTuple = + canonicalBytes( + GameSessionAccountDelegationProfile.authorityTuple( + secondIntent.authoritySnapshot().issuerGeneration(), + secondIntent.authoritySnapshot().accountGeneration(), + secondIntent.authoritySnapshot().accountSecurityCutoff())); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET authority_tuple_canonical_bytes = ? WHERE request_id = ?", + canonicalBytes( + authorityTupleWithoutCutoff( + secondIntent.authoritySnapshot().issuerGeneration(), + secondIntent.authoritySnapshot().accountGeneration())), + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authority snapshot is stale or missing"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET issuance_fence = issuance_fence + 1 WHERE request_id = ?", + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authority snapshot is stale or missing"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET issuance_fence_source_version = issuance_fence_source_version + 1 " + + "WHERE request_id = ?", + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authority snapshot is stale or missing"); + assertThat(readCandidate(dsl, secondIntent.requestId()).authorityTupleBytes()) + .containsExactly(advancedAuthorityTuple); + String advancedJwt = compactCandidate(secondIntent); + var advancedBound = + inTransaction( + context, + () -> repository.bindSignedCandidate(secondIntent.requestId(), advancedJwt, "1")); + var advancedBoundRetry = + inTransaction( + context, + () -> repository.bindSignedCandidate(secondIntent.requestId(), advancedJwt, "1")); + assertThat(advancedBoundRetry).isEqualTo(advancedBound); + RecordData advancedPersisted = readCandidate(dsl, secondIntent.requestId()); + + byte[] otherwiseShapedCommitProof = + canonicalBytes( + Map.ofEntries( + Map.entry("schema", "account-game-session-delegation-commit-proof/v1"), + Map.entry("identity", Map.of()), + Map.entry("tokenSha256", advancedBound.tokenHash()), + Map.entry("registryRecordSha256", "a".repeat(64)), + Map.entry("registry", Map.of()), + Map.entry("bundle", Map.of()), + Map.entry("authority", Map.of()), + Map.entry("signer", Map.of()), + Map.entry("envelope", Map.of()))); + String otherwiseShapedProofSha256 = sha256Hex(otherwiseShapedCommitProof); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_gameplay_delegation_issuance_operations (" + + "operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "credential_request_digest_version, credential_digest_key_id, credential_request_digest, " + + "request_digest_version, request_digest, token_jti, token_generation, " + + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " + + "authority_issuer_generation, authority_issuer_source_version, " + + "authority_account_generation, authority_account_source_version, issuance_fence, " + + "issuance_fence_source_version, authority_tuple_canonical_bytes, " + + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes, " + + "status, token_hash, signer_kid, signer_generation, " + + "pending_registry_candidate_bytes, commit_proof_version, commit_proof_sha256, " + + "commit_proof_canonical_bytes, committed_at) " + + "SELECT operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "credential_request_digest_version, credential_digest_key_id, credential_request_digest, " + + "request_digest_version, request_digest, token_jti, token_generation, " + + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " + + "authority_issuer_generation, authority_issuer_source_version, " + + "authority_account_generation, authority_account_source_version, issuance_fence, " + + "issuance_fence_source_version, authority_tuple_canonical_bytes, " + + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes, " + + "'COMMITTED', token_hash, signer_kid, signer_generation, " + + "pending_registry_candidate_bytes, 1, ?, ?, CURRENT_TIMESTAMP " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + otherwiseShapedProofSha256, + otherwiseShapedCommitProof, + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("must begin as unbound PENDING intent"); + RecordData afterCommittedInsert = readCandidate(dsl, secondIntent.requestId()); + assertThat(afterCommittedInsert.status()).isEqualTo("PENDING"); + assertThat(afterCommittedInsert.tokenHash()).isEqualTo(advancedBound.tokenHash()); + assertThat(afterCommittedInsert.candidateBytes()) + .containsExactly(advancedPersisted.candidateBytes()); + + byte[] forgedCommitProof = "{}".getBytes(StandardCharsets.US_ASCII); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED', commit_proof_version = 1, " + + "commit_proof_sha256 = ?, commit_proof_canonical_bytes = ?, " + + "committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", + "a".repeat(64), + forgedCommitProof, + secondIntent.requestId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("unknown or missing fields"); + RecordData afterForgedCommit = readCandidate(dsl, secondIntent.requestId()); + assertThat(afterForgedCommit.status()).isEqualTo("PENDING"); + assertThat(afterForgedCommit.tokenHash()).isEqualTo(advancedBound.tokenHash()); + assertThat(afterForgedCommit.candidateBytes()) + .containsExactly(advancedPersisted.candidateBytes()); + var commitColumns = + dsl.resultQuery( + "SELECT commit_proof_version, commit_proof_sha256, " + + "commit_proof_canonical_bytes, committed_at " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + secondIntent.requestId()) + .fetchOne(); + assertThat(commitColumns.get("commit_proof_version")).isNull(); + assertThat(commitColumns.get("commit_proof_sha256")).isNull(); + assertThat(commitColumns.get("commit_proof_canonical_bytes")).isNull(); + assertThat(commitColumns.get("committed_at")).isNull(); + + var advancedReadback = + inTransaction( + context, () -> repository.readPendingRegistryCandidate(secondIntent.requestId())); + assertThat(advancedReadback.authoritySnapshot().accountSecurityCutoff()) + .isEqualTo(secondIntent.authoritySnapshot().accountSecurityCutoff()); + assertThat(advancedPersisted.authorityTupleBytes()).containsExactly(advancedAuthorityTuple); + assertThat(new String(advancedPersisted.candidateBytes(), StandardCharsets.UTF_8)) + .contains("\"accountSecurityCutoff\"") + .doesNotContain(advancedJwt); + inTransaction( + context, + () -> + sources.appendIssuerAuthorityChange( + ACCOUNT_ISSUER, "SIGNER_COMPROMISE", UUID.randomUUID().toString())); + assertThatThrownBy(() -> inTransaction(context, () -> repository.beginPending(secondIntent))) + .isInstanceOf(StaleAuthorityException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> repository.readPendingRegistryCandidate(secondIntent.requestId()))) + .isInstanceOf(StaleAuthorityException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.bindSignedCandidate(secondIntent.requestId(), advancedJwt, "1"))) + .isInstanceOf(StaleAuthorityException.class); + RecordData afterIssuerAdvance = readCandidate(dsl, secondIntent.requestId()); + assertThat(afterIssuerAdvance.status()).isEqualTo(advancedPersisted.status()); + assertThat(afterIssuerAdvance.tokenHash()).isEqualTo(advancedPersisted.tokenHash()); + assertThat(afterIssuerAdvance.candidateBytes()) + .containsExactly(advancedPersisted.candidateBytes()); + assertThat(afterIssuerAdvance.authorityTupleBytes()) + .containsExactly(advancedPersisted.authorityTupleBytes()); + } + + @Test + void realCommittedIssuanceEstablishesExactSqlFenceAndIndependentRetryReadback() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false); + assertThat( + Objects.requireNonNull( + harness + .dsl() + .fetchOne("SELECT count(*) FROM account_gameplay_token_identity_fences"), + "token identity fence count query must return a row") + .get(0, Long.class)) + .isZero(); + harness.service().commitPendingCandidate(harness.pending().requestId()); + TokenIdentity identity = tokenFenceIdentity(harness); + AccountGameplayTokenIdentityFenceRepository fences = + new AccountGameplayTokenIdentityFenceRepository(harness.dsl()); + var active = inTransaction(harness.context(), () -> fences.requireActiveForUpdate(identity)); + assertThat(active.state()).isEqualTo(State.ACTIVE); + assertThat(active.tokenIdentityFence()).isEqualTo(1L); + assertThat(active.identity()).isEqualTo(identity); + assertThatThrownBy( + () -> + inTransaction( + harness.context(), + () -> harness.dsl().execute("TRUNCATE account_gameplay_token_identity_fences"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Account token fence retention cannot be bypassed by truncation"); + assertThat(inTransaction(harness.context(), () -> fences.requireActiveForUpdate(identity))) + .isEqualTo(active); + assertThat(harness.issuance().readCommittedProof(identity.issuanceRequestId())).isPresent(); + assertThat(harness.service().commitPendingCandidate(identity.issuanceRequestId()).outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.EXACT_RETRY); + assertThat( + Objects.requireNonNull( + harness + .dsl() + .fetchOne("SELECT count(*) FROM account_gameplay_token_identity_fences"), + "token identity fence count query must return a row") + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void concurrentDifferentAccountIssuerSnapshotsAndPendingIssuanceShareGlobalRows() + throws Exception { + TestContext context = newTestContext(); + Account firstAccount = createAccount(context); + Account secondAccount = createAccount(context); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository( + context.dsl(), + sources, + new AccountAuthEvidenceBundleRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl()))); + PendingIntent firstIntent = + intent( + currentSnapshot(context, sources, firstAccount.getAccountUuid()), + firstAccount.getAccountUuid()); + PendingIntent secondIntent = + intent( + currentSnapshot(context, sources, secondAccount.getAccountUuid()), + secondAccount.getAccountUuid()); + CountDownLatch sharedIssuerSnapshotsHeld = new CountDownLatch(2); + CountDownLatch releaseIssuance = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + inTransaction( + context, + () -> { + sources.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, firstAccount.getAccountUuid()); + sharedIssuerSnapshotsHeld.countDown(); + awaitLatch(releaseIssuance, "release concurrent first Account issuance"); + return issuance.beginPending(firstIntent); + })); + var second = + executor.submit( + () -> + inTransaction( + context, + () -> { + sources.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, secondAccount.getAccountUuid()); + sharedIssuerSnapshotsHeld.countDown(); + awaitLatch(releaseIssuance, "release concurrent second Account issuance"); + return issuance.beginPending(secondIntent); + })); + + assertThat(sharedIssuerSnapshotsHeld.await(10, TimeUnit.SECONDS)).isTrue(); + releaseIssuance.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS).requestId()).isEqualTo(firstIntent.requestId()); + assertThat(second.get(10, TimeUnit.SECONDS).requestId()).isEqualTo(secondIntent.requestId()); + } finally { + releaseIssuance.countDown(); + executor.shutdownNow(); + } + } + + private static TokenIdentity tokenFenceIdentity(CommitHarness harness) { + Record row = + Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT token_hash FROM account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + harness.pending().requestId()), + "committed token candidate query must return a row"); + return new TokenIdentity( + harness.accountId(), + harness.pending().operationId(), + harness.pending().requestId(), + row.get("token_hash", String.class), + harness.pending().tokenJti(), + harness.pending().notBeforeEpochSecond(), + 1L, + harness.pending().authoritySnapshot().issuanceFence()); + } + + @Test + void signerProducedRsaProofCommitsWithExactOwnerEvidenceAndExactRetryDoesNotRepeatNetworkWork() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false, true); + + var committed = harness.service().commitPendingCandidate(harness.pending().requestId()); + + assertThat(committed.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + assertThat(committed.operationId()).isEqualTo(harness.pending().operationId()); + assertThat(committed.requestId()).isEqualTo(harness.pending().requestId()); + assertThat(committed.accountId()).isEqualTo(harness.accountId()); + assertThat(committed.proofSha256()).matches("[0-9a-f]{64}"); + var row = + harness + .dsl() + .resultQuery( + "SELECT status, token_hash, pending_registry_candidate_bytes, " + + "commit_proof_sha256, commit_proof_canonical_bytes, committed_at " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(); + assertThat(row.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(row.get("token_hash", String.class)).matches("[0-9a-f]{64}"); + assertThat(row.get("pending_registry_candidate_bytes", byte[].class)).isNotEmpty(); + byte[] persistedProof = row.get("commit_proof_canonical_bytes", byte[].class); + assertThat(row.get("commit_proof_sha256", String.class)).isEqualTo(committed.proofSha256()); + assertThat(row.get("committed_at")).isNotNull(); + Record bundleEvidence = + Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT source_fence FROM account_gameplay_delegation_auth_evidence_bundles " + + "WHERE operation_id = ?", + harness.pending().operationId()), + "committed issuance evidence bundle must exist"); + String storedSourceFence = bundleEvidence.get("source_fence", String.class); + assertThat(new String(persistedProof, StandardCharsets.UTF_8)) + .contains("account-game-session-delegation-commit-proof/v1") + .contains("\"sourceFence\":\"" + storedSourceFence + "\"") + .doesNotContain("eyJ"); + // This fixture does not advance Account security state through an owner event, so no + // security-cutoff checkpoint is present in its exact authority snapshot. + assertThat(harness.pending().authoritySnapshot().accountSecurityCutoff()).isEmpty(); + assertThat(harness.redis().registeredRecord()).isNotEmpty(); + assertThat(new String(harness.redis().registeredRecord(), StandardCharsets.UTF_8)) + .doesNotContain("eyJ"); + + CanonicalGameplayLoginRequest exactLoginRetry = harness.loginRequest(); + AtomicInteger credentialVerifierCalls = new AtomicInteger(); + var firstLoginReplay = + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls))); + var exactLoginRetryResult = + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls))); + assertThat(firstLoginReplay.accountId()).isEqualTo(harness.accountId()); + assertThat(firstLoginReplay.tokenJti()).isEqualTo(harness.pending().tokenJti()); + assertThat(firstLoginReplay.tokenSha256()).isEqualTo(row.get("token_hash", String.class)); + assertThat(firstLoginReplay.compactJwtBytes()) + .containsExactly(exactLoginRetryResult.compactJwtBytes()); + assertThat(firstLoginReplay.toString()) + .doesNotContain("already-consumed-credential", "eyJ", committed.proofSha256()); + assertThat(credentialVerifierCalls).hasValue(0); + assertThat( + Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT status FROM account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + harness.pending().requestId()), + "issuance status query must return a row") + .get("status", String.class)) + .isEqualTo("COMMITTED"); + + GameplayCredentialSourceContext sourceContext = exactLoginRetry.sourceContext(); + CanonicalGameplayLoginRequest changedCallerContext = + new CanonicalGameplayLoginRequest( + exactLoginRetry.requestId(), + exactLoginRetry.email(), + exactLoginRetry.credential(), + new GameplayCredentialSourceContext( + UUID.randomUUID(), + sourceContext.canonicalClientAddress(), + sourceContext.transportClass())); + assertThatThrownBy( + () -> + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + changedCallerContext, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls)))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + assertThat(credentialVerifierCalls).hasValue(0); + + AccountGameplayDelegationIssuanceRepository expiredReader = + new AccountGameplayDelegationIssuanceRepository( + harness.dsl(), + harness.sources(), + Clock.fixed( + Instant.ofEpochSecond(harness.pending().expiresAtEpochSecond()), ZoneOffset.UTC)); + assertThatThrownBy( + () -> + inTransaction( + harness.context(), + () -> + expiredReader.readCurrentGameplayLoginReplay( + harness.pending().requestId()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.PendingCandidateUnavailableException.class); + + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + harness.issuance(), + harness.signer(), + new AccountGameplayDelegationTokenRegistry( + harness.issuance(), + harness.context().manager(), + harness.redis().client(), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + 30_000L), + harness.context().manager(), + Clock.systemUTC()); + var currentObservation = + committedOwner.inspectCurrentCommittedIssuance(harness.pending().requestId()); + assertThat(currentObservation.operationId()).isEqualTo(harness.pending().operationId()); + assertThat(currentObservation.requestId()).isEqualTo(harness.pending().requestId()); + assertThat(currentObservation.accountId()).isEqualTo(harness.accountId()); + assertThat(currentObservation.tokenSha256()).isEqualTo(row.get("token_hash", String.class)); + assertThat(currentObservation.commitProofSha256()).isEqualTo(committed.proofSha256()); + assertThat(currentObservation.authoritySnapshot()) + .isEqualTo(harness.pending().authoritySnapshot()); + assertThat(currentObservation.evidenceBundleReference().canonicalSha256()) + .matches("[0-9a-f]{64}"); + assertThat(currentObservation.envelopeSha256()).matches("[0-9a-f]{64}"); + assertThat(currentObservation.toString()) + .doesNotContain( + "eyJ", + currentObservation.tokenSha256(), + currentObservation.envelopeSha256(), + currentObservation.commitProofSha256()); + + byte[] originalProof = persistedProof.clone(); + inTransaction( + harness.context(), + () -> { + AccountRepository accounts = new AccountRepository(harness.dsl(), harness.sources()); + Account changed = accounts.findByAccountUuid(harness.accountId()).orElseThrow(); + changed.setEmailVerified(true); + accounts.save(changed); + return null; + }); + assertThatThrownBy( + () -> committedOwner.inspectCurrentCommittedIssuance(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException.class) + .hasNoCause(); + var unchangedAfterAuthorityChange = + harness + .dsl() + .resultQuery( + "SELECT status, commit_proof_sha256, commit_proof_canonical_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(); + assertThat(unchangedAfterAuthorityChange.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(unchangedAfterAuthorityChange.get("commit_proof_sha256", String.class)) + .isEqualTo(committed.proofSha256()); + assertThat(unchangedAfterAuthorityChange.get("commit_proof_canonical_bytes", byte[].class)) + .containsExactly(originalProof); + + assertThatThrownBy( + () -> + withAuthenticatedGameSession( + () -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls)))) + // This generic Account mutation has no closed source-event receipt. Reject its unsupported + // authority before comparing a current snapshot with the retained issuance snapshot. + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account authority source evidence is unavailable or inconsistent"); + assertThat(credentialVerifierCalls).hasValue(0); + + int closesBeforeRetry = harness.redis().connectionCloseCount(); + int loadsBeforeRetry = harness.redis().scriptLoadCount(); + var exactRetry = harness.service().commitPendingCandidate(harness.pending().requestId()); + assertThat(exactRetry.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.EXACT_RETRY); + assertThat(exactRetry.operationId()).isEqualTo(committed.operationId()); + assertThat(exactRetry.requestId()).isEqualTo(committed.requestId()); + assertThat(exactRetry.accountId()).isEqualTo(committed.accountId()); + assertThat(exactRetry.proofSha256()).isEqualTo(committed.proofSha256()); + assertThat(harness.redis().connectionCloseCount()).isEqualTo(closesBeforeRetry); + assertThat(harness.redis().scriptLoadCount()).isEqualTo(loadsBeforeRetry); + assertThat( + Objects.requireNonNull( + harness + .dsl() + .resultQuery( + "SELECT commit_proof_canonical_bytes FROM " + + "account_gameplay_delegation_issuance_operations " + + "WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(), + "committed proof query must return a row") + .get("commit_proof_canonical_bytes", byte[].class)) + .containsExactly(persistedProof); + } + + @Test + void signerTrustWithdrawalAfterExternalProofLeavesOnlyQuarantinedPendingCandidate() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.WITHDRAW_SIGNER_TRUST, false); + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + assertPendingWithoutCommitProof(harness); + assertThat(harness.redis().registeredRecord()).isNotEmpty(); + } + + @Test + void advancedAccountSourceChangeAfterProjectionDeniesCommitWithoutRewritingCandidate() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.ADVANCE_ACCOUNT_AFTER_PROJECTION, false); + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + assertPendingWithoutCommitProof(harness); + assertThat( + currentSnapshot(harness.context(), harness.sources(), harness.accountId()) + .account() + .generation()) + .isGreaterThan(harness.pending().authoritySnapshot().accountGeneration()); + } + + @Test + void realIssuerWriterInvalidatesAlreadySignedPendingCommit() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false); + harness.signerFixture().preparePendingCandidate(harness.pending().requestId()); + PendingRegistryCandidate pendingBeforeIssuerMutation = + inTransaction( + harness.context(), + () -> harness.issuance().readPendingRegistryCandidate(harness.pending().requestId())); + Record envelopeBeforeIssuerMutation = readResponseEnvelope(harness); + CountDownLatch issuerSnapshotHeld = new CountDownLatch(1); + CountDownLatch releaseIssuerSnapshot = new CountDownLatch(1); + CountDownLatch issuerWriterEntered = new CountDownLatch(1); + CountDownLatch issuerWriterCompleted = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var ownerRead = + executor.submit( + () -> + inTransaction( + harness.context(), + () -> { + harness + .sources() + .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, harness.accountId()); + issuerSnapshotHeld.countDown(); + awaitLatch(releaseIssuerSnapshot, "release held issuer snapshot"); + return null; + })); + assertThat(issuerSnapshotHeld.await(10, TimeUnit.SECONDS)).isTrue(); + + var issuerWriter = + executor.submit( + () -> { + inTransaction( + harness.context(), + () -> { + issuerWriterEntered.countDown(); + harness + .sources() + .appendIssuerAuthorityChange( + ACCOUNT_ISSUER, "SIGNER_COMPROMISE", UUID.randomUUID().toString()); + return null; + }); + issuerWriterCompleted.countDown(); + }); + assertThat(issuerWriterEntered.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(issuerWriterCompleted.await(250, TimeUnit.MILLISECONDS)).isFalse(); + + releaseIssuerSnapshot.countDown(); + ownerRead.get(10, TimeUnit.SECONDS); + issuerWriter.get(10, TimeUnit.SECONDS); + assertThat(issuerWriterCompleted.getCount()).isZero(); + } finally { + releaseIssuerSnapshot.countDown(); + executor.shutdownNow(); + } + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + assertPendingWithoutCommitProof(harness); + Record candidateAfterIssuerMutation = readCandidateRow(harness); + assertThat(candidateAfterIssuerMutation.get("token_hash", String.class)) + .isEqualTo(pendingBeforeIssuerMutation.tokenHash()); + assertThat(candidateAfterIssuerMutation.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(pendingBeforeIssuerMutation.canonicalRecordBytes()); + Record envelopeAfterIssuerMutation = readResponseEnvelope(harness); + assertThat(envelopeAfterIssuerMutation.get("envelope_sha256", String.class)) + .isEqualTo(envelopeBeforeIssuerMutation.get("envelope_sha256", String.class)); + assertThat(envelopeAfterIssuerMutation.get("envelope_bytes", byte[].class)) + .containsExactly(envelopeBeforeIssuerMutation.get("envelope_bytes", byte[].class)); + } + + @Test + void changedPendingRedisReadbackNeverCommitsTheCandidate() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.TRANSIENT_REDIS_READBACK, true); + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + assertPendingWithoutCommitProof(harness); + assertThat(harness.redis().connectionCloseCount()).isEqualTo(1); + verify(harness.issuance(), times(1)) + .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); + PendingRegistryCandidate pendingBeforeRetry = + inTransaction( + harness.context(), + () -> harness.issuance().readPendingRegistryCandidate(harness.pending().requestId())); + Record envelopeBeforeRetry = readResponseEnvelope(harness); + + harness.redis().restorePendingReadback(); + reset(harness.issuance()); + assertThat(harness.service().commitPendingCandidate(harness.pending().requestId()).outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + verify(harness.issuance(), never()) + .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); + Record committedCandidate = readCandidateRow(harness); + assertThat(committedCandidate.get("token_hash", String.class)) + .isEqualTo(pendingBeforeRetry.tokenHash()); + assertThat(committedCandidate.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(pendingBeforeRetry.canonicalRecordBytes()); + Record envelopeAfterRetry = readResponseEnvelope(harness); + assertThat(envelopeAfterRetry.get("envelope_sha256", String.class)) + .isEqualTo(envelopeBeforeRetry.get("envelope_sha256", String.class)); + assertThat(envelopeAfterRetry.get("envelope_bytes", byte[].class)) + .containsExactly(envelopeBeforeRetry.get("envelope_bytes", byte[].class)); + } + + @Test + void ambiguousCommittedSqlReadbackDoesNotReturnSuccessThoughExactOwnerRowIsCommitted() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.AMBIGUOUS_COMMITTED_READBACK, false); + + assertThatThrownBy( + () -> harness.service().commitPendingCandidate(harness.pending().requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + var row = + harness + .dsl() + .resultQuery( + "SELECT status, commit_proof_sha256, commit_proof_canonical_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(); + assertThat(row.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(row.get("commit_proof_sha256", String.class)).matches("[0-9a-f]{64}"); + assertThat(row.get("commit_proof_canonical_bytes", byte[].class)).isNotEmpty(); + } + + private CommitHarness newCommitHarness(CommitHook hook, boolean mismatchRedisReadback) + throws Exception { + return newCommitHarness(hook, mismatchRedisReadback, false); + } + + private CommitHarness newCommitHarness( + CommitHook hook, boolean mismatchRedisReadback, boolean bindCanonicalLoginRequest) + throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + Account account = createAccount(context); + UUID accountId = account.getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sources, accountId); + CanonicalGameplayLoginRequest loginRequest = null; + PendingIntent pending; + if (bindCanonicalLoginRequest) { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + loginRequest = + canonicalLoginRequest( + account.getEmail(), "already-consumed-credential", requestId, callerContextId); + AccountGameplayCredentialRequestBinding binding = + AccountGameplayCredentialRequestDigester.bind( + integrationDigestKeySource().currentKey(), + loginRequest, + account.getEmail(), + CALLER_WORKLOAD, + accountId); + pending = intent(snapshot, accountId, requestId, callerContextId, binding); + } else { + pending = intent(snapshot, accountId); + } + AccountGameplayDelegationIssuanceRepository storedIssuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + inTransaction(context, () -> storedIssuance.beginPending(pending)); + + AccountGameplayDelegationIssuanceRepository issuance = storedIssuance; + if (hook == CommitHook.AMBIGUOUS_COMMITTED_READBACK) { + issuance = spy(storedIssuance); + AtomicInteger committedReads = new AtomicInteger(); + AccountGameplayDelegationIssuanceRepository readbackSpy = issuance; + doAnswer( + invocation -> + committedReads.incrementAndGet() == 1 + ? invocation.callRealMethod() + : Optional.empty()) + .when(readbackSpy) + .readCommittedProof(pending.requestId()); + } else if (hook == CommitHook.TRANSIENT_REDIS_READBACK) { + issuance = spy(storedIssuance); + } else if (hook == CommitHook.CAPTURE_COMMIT_PROOF) { + issuance = spy(storedIssuance); + AccountGameplayDelegationIssuanceRepository proofSpy = issuance; + doAnswer( + invocation -> { + AccountGameplayDelegationIssuanceCommitService.CommitProof commitProof = + invocation.getArgument(4); + capturedCommitProof.set(commitProof.canonicalBytes()); + throw new IllegalStateException(); + }) + .when(proofSpy) + .commitPendingCandidate(any(), any(), any(), any(), any()); + } + + return buildCommitHarness( + context, + accountId, + sources, + bundles, + issuance, + pending, + loginRequest, + hook, + mismatchRedisReadback); + } + + private CommitHarness buildCommitHarness( + TestContext context, + UUID accountId, + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthEvidenceBundleRepository bundles, + AccountGameplayDelegationIssuanceRepository issuance, + PendingIntent pending, + CanonicalGameplayLoginRequest loginRequest, + CommitHook hook, + boolean mismatchRedisReadback) + throws Exception { + DSLContext dsl = context.dsl(); + IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sources, accountId); + Path responseKeyring = temporaryDirectory.resolve("response-keyring-" + UUID.randomUUID()); + writeTestKeyring(responseKeyring); + AccountResponseEnvelopeCryptography responseCryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(responseKeyring.toString())); + AccountGameplayDelegationResponseEnvelopeRepository responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, responseCryptography); + AccountGameplayDelegationResponseEnvelopeService responseService = + new AccountGameplayDelegationResponseEnvelopeService(responseRepository); + + // Only the commit service uses this manager: its transaction is the final commit boundary. + TransactionHookManager transactionManager = new TransactionHookManager(context.manager()); + AccountGameplayDelegationCommitSignerFixture signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, issuance, responseService, context.manager(), Clock.systemUTC()); + signerFixture.observeDatabaseFailures(dsl); + transactionManager.setBeforeTargetTransaction( + switch (hook) { + case NONE, AMBIGUOUS_COMMITTED_READBACK, CAPTURE_COMMIT_PROOF, TRANSIENT_REDIS_READBACK -> + () -> {}; + case WITHDRAW_SIGNER_TRUST -> signerFixture::withdrawTrust; + case ADVANCE_ACCOUNT_AFTER_PROJECTION -> + () -> + advanceEmailVerifiedThroughOwner(dsl, context.transaction(), sources, accountId); + }); + + RedisHarness redis = + new RedisHarness(accountId, snapshot, mismatchRedisReadback, getClass().getClassLoader()); + AccountGameplayDelegationTokenRegistry tokenRegistry = + new AccountGameplayDelegationTokenRegistry( + issuance, + context.manager(), + redis.client(), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + 30_000L); + AccountGameplayDelegationAuthorityProjection authorityProjection = + new AccountGameplayDelegationAuthorityProjection( + sources, context.manager(), redis.client()); + AccountGameplayDelegationIssuanceCommitService service = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + tokenRegistry, + authorityProjection, + issuance, + transactionManager, + Clock.systemUTC()); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, signerFixture.signer(), tokenRegistry, context.manager(), Clock.systemUTC()); + AccountGameplayDelegationResponseRecoveryOwner responseOwner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseRepository, committedOwner, context.manager()); + AccountGameplayCanonicalLoginOwner loginOwner = + new AccountGameplayCanonicalLoginOwner( + new AccountRepository(dsl, sources), + issuance, + integrationDigestKeySource(), + service, + responseOwner, + context.manager(), + Clock.systemUTC()); + return new CommitHarness( + context, + dsl, + accountId, + sources, + pending, + redis, + service, + issuance, + signerFixture, + signerFixture.signer(), + loginOwner, + loginRequest); + } + + private CommitHarness buildCommitHarness( + TestContext context, + UUID accountId, + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthEvidenceBundleRepository bundles, + AccountGameplayDelegationIssuanceRepository issuance, + PendingIntent pending, + CanonicalGameplayLoginRequest loginRequest) + throws Exception { + return buildCommitHarness( + context, + accountId, + sources, + bundles, + issuance, + pending, + loginRequest, + CommitHook.NONE, + false); + } + + private static void assertPendingWithoutCommitProof(CommitHarness harness) { + var row = + harness + .dsl() + .resultQuery( + "SELECT status, token_hash, pending_registry_candidate_bytes, " + + "commit_proof_version, commit_proof_sha256, " + + "commit_proof_canonical_bytes, committed_at " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()) + .fetchOne(); + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("token_hash", String.class)).matches("[0-9a-f]{64}"); + byte[] storedCandidate = row.get("pending_registry_candidate_bytes", byte[].class); + assertThat(storedCandidate).isNotEmpty(); + if (harness.redis().registeredRecord() != null) { + assertThat(storedCandidate).containsExactly(harness.redis().registeredRecord()); + } + assertThat(row.get("commit_proof_version")).isNull(); + assertThat(row.get("commit_proof_sha256")).isNull(); + assertThat(row.get("commit_proof_canonical_bytes")).isNull(); + assertThat(row.get("committed_at")).isNull(); + } + + private static Record readCommitBundleEvidence(CommitHarness harness) { + return Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT bundle_version, source_version, source_fence, linearization, " + + "canonical_sha256, canonical_bundle_bytes " + + "FROM account_gameplay_delegation_auth_evidence_bundles " + + "WHERE operation_id = ?", + harness.pending().operationId()), + "commit proof evidence bundle must exist"); + } + + private static Record readCandidateRow(CommitHarness harness) { + return Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT token_hash, pending_registry_candidate_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + harness.pending().requestId()), + "issuance candidate row must exist"); + } + + private static Record readResponseEnvelope(CommitHarness harness) { + return Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT envelope_sha256, envelope_bytes " + + "FROM account_gameplay_delegation_response_envelopes WHERE operation_id = ?", + harness.pending().operationId()), + "sealed PENDING response envelope must exist"); + } + + private static void assertCommitBundleEvidenceUnchanged(CommitHarness harness, Record before) { + Record after = readCommitBundleEvidence(harness); + for (String column : + List.of( + "bundle_version", + "source_version", + "source_fence", + "linearization", + "canonical_sha256")) { + assertThat(after.get(column)).isEqualTo(before.get(column)); + } + assertThat(after.get("canonical_bundle_bytes", byte[].class)) + .containsExactly(before.get("canonical_bundle_bytes", byte[].class)); + } + + private static void assertCommitProofRejected( + CommitHarness harness, byte[] proofBytes, String safeConstraint) throws Exception { + assertThatThrownBy( + () -> + harness + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED', commit_proof_version = 1, " + + "commit_proof_sha256 = ?, commit_proof_canonical_bytes = ?, " + + "committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", + sha256Hex(proofBytes), + proofBytes, + harness.pending().requestId())) + .isInstanceOf(DataAccessException.class) + .satisfies( + failure -> + assertThat( + AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic(failure)) + .isEqualTo("sqlstate=23514;constraint=" + safeConstraint)); + assertPendingWithoutCommitProof(harness); + assertThat(tokenFenceCount(harness)).isZero(); + } + + private static long tokenFenceCount(CommitHarness harness) { + return Objects.requireNonNull( + harness.dsl().fetchOne("SELECT count(*) FROM account_gameplay_token_identity_fences"), + "token identity fence count query must return a row") + .get(0, Long.class); + } + + private static byte[] removeCommitProofSourceFence(byte[] proofBytes, String sourceFence) { + String json = new String(proofBytes, StandardCharsets.UTF_8); + String field = "\"sourceFence\":\"" + sourceFence + "\","; + assertThat(json).contains(field); + return json.replace(field, "").getBytes(StandardCharsets.UTF_8); + } + + private static byte[] replaceCommitProofSourceFence( + byte[] proofBytes, String sourceFence, String replacement) { + String json = new String(proofBytes, StandardCharsets.UTF_8); + String field = "\"sourceFence\":\"" + sourceFence + "\""; + assertThat(json).contains(field); + return json.replace(field, "\"sourceFence\":\"" + replacement + "\"") + .getBytes(StandardCharsets.UTF_8); + } + + private static Account createAccount(TestContext context) { + return createAccount(context, "PASSWORD"); + } + + private static Account createAccount(TestContext context, String loginAuthModes) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + account.setUsername("delegation-" + suffix); + account.setEmail("delegation-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + // The fresh Account birth path creates the exact empty global-role source only for null role. + account.setLoginAuthModes(loginAuthModes); + DSLContext dsl = context.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + return inTransaction( + context, + () -> { + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(dsl, sourceEvidence).save(account); + }); + } + + private static Account createEmailOtpAccount( + TestContext context, AccountAuthoritySourceEvidenceRepository sourceEvidence) { + return createAccount(context, "EMAIL_OTP"); + } + + /** Test-only owner transaction using the retained closed operation/source receipt protocol. */ + static void advanceEmailVerifiedThroughOwner( + DSLContext dsl, + TransactionTemplate transaction, + AccountAuthoritySourceEvidenceRepository sources, + UUID accountUuid) { + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountSecurityStateOperationRepository operations = + new AccountSecurityStateOperationRepository(dsl); + DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(dsl); + transaction.execute( + status -> { + Account account = + new AccountRepository(dsl, sources).findByAccountUuid(accountUuid).orElseThrow(); + var source = + sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountUuid).account(); + var roleRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version " + + "FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", + accountUuid)); + long roleVersion = roleRow.get("global_role_source_version", Long.class); + AccountState before = + new AccountState( + account.isEmailVerified(), + AccountLoginAuthModes.read(account.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + java.util.Arrays.stream(roleRow.get("global_roles", String[].class)) + .sorted() + .toList(), + account.getLifecycleState().name()); + AccountState after = + new AccountState( + true, before.loginAuthModes(), before.globalRoles(), before.lifecycleState()); + if (before.emailVerified()) + throw new IllegalStateException("Fixture expected unverified Account"); + UUID requestId = UUID.randomUUID(); + AccountSecurityStateMutationRequest request = + new AccountSecurityStateMutationRequest( + requestId, + accountUuid, + securityStateCorrelation(accountUuid, requestId), + source.generation(), + source.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + long checkpointSequence = source.checkpoint().sequence(); + byte[] checkpointPayload = + checkpointSequence == 0L + ? new byte[0] + : outbox + .findEvent(accountStream(accountUuid), checkpointSequence) + .orElseThrow() + .payload(); + Capture draft = + new Capture( + account.getId(), + account.getAccountUuidProvenance(), + before, + new AccountAuthorityGenerationRepository.ScopeState( + source.scope(), + source.generation(), + source.sourceVersion(), + source.issuanceFence()), + checkpointSequence, + checkpointPayload, + roleVersion, + null); + byte[] captureBytes = + AccountSecurityStateOperationRepository.captureBytes(request, draft); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + accountUuid.toString(), + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + accountStream(accountUuid), + Long.toString(checkpointSequence), + captureBytes); + SourceChange change = + new SourceChange(UUID.randomUUID(), List.of(sourceEvidence), captureBytes); + Capture capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + draft.sourceState(), + checkpointSequence, + checkpointPayload, + roleVersion, + change); + fences.requestSourceChange(change); + if (!fences.sourceMutationPermitted(change)) + throw new IllegalStateException("Fixture owner source is not settled"); + operations.claim(request, capture); + var advanced = sources.prepareClosedAccountAdvance(accountUuid, source); + dsl.execute( + "UPDATE accounts SET email_verified = TRUE WHERE account_uuid = ?", accountUuid); + Event event = + outbox.append( + accountStream(accountUuid), + requestId.toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + requestId, + accountUuid, + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + request.mutationKinds(), + after)); + return new EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fences.markSourceCommitted(change); + operations.complete(request, event, advanced, roleVersion); + return null; + }); + } + + private static byte[] securityStateCorrelation(UUID accountUuid, UUID operationId) { + return ("{\"actorAccountUuid\":\"" + + accountUuid + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + operationId + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private static String accountStream(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static AccountEmailLoginChallenge persistEmailLoginChallenge( + TestContext context, + AccountEmailLoginChallengeRepository challenges, + Long accountId, + String code) { + LocalDateTime now = LocalDateTime.now(); + AccountEmailLoginChallenge challenge = new AccountEmailLoginChallenge(); + challenge.setAccountId(accountId); + challenge.setCodeHash(hashCredential(code)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setInvalidAttemptCount(0); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return inTransaction(context, () -> challenges.save(challenge)); + } + + private static String hashCredential(String credential) { + Argon2 argon2 = Argon2Factory.create(); + char[] chars = credential.toCharArray(); + try { + return argon2.hash(2, 65536, 1, chars); + } finally { + argon2.wipeArray(chars); + } + } + + private static CanonicalGameplayLoginRequest canonicalLoginRequest( + String email, String credential, UUID requestId, UUID callerContextId) { + return new CanonicalGameplayLoginRequest( + requestId, + email, + credential, + new GameplayCredentialSourceContext(callerContextId, "203.0.113.10", "FIRST_PARTY_WEB")); + } + + /** + * Test-only deterministic successful credential verifier. These PostgreSQL proofs exercise the + * canonical owner's transaction boundary and persisted issuance; they do not prove production + * password or OTP verification. + */ + private static AccountGameplayCanonicalLoginOwner.CredentialVerifier + deterministicOtpCredentialVerifier( + AccountEmailLoginChallengeRepository challenges, String expectedCredential) { + return new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public void verifyAbsentAccountCredential(String presentedCredential) { + throw new AssertionError( + "Known-account integration fixture must not verify decoy credentials"); + } + + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String presentedCredential) { + if (!expectedCredential.equals(presentedCredential)) { + throw new AssertionError("Unexpected deterministic integration credential"); + } + AccountEmailLoginChallenge challenge = + challenges + .findByAccountId(account.getId()) + .orElseThrow(() -> new AssertionError("Expected seeded OTP challenge")); + return new AccountGameplayCanonicalLoginOwner.CredentialVerification( + account.getAccountUuid(), challenge.getId()); + } + + @Override + public void consumeOneTimeCredential( + Account account, AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + challenges.lockAccountChallenge(account.getId()); + AccountEmailLoginChallenge challenge = + challenges + .findByAccountId(account.getId()) + .orElseThrow(() -> new AssertionError("Expected locked OTP challenge")); + if (!challenge.getId().equals(verification.oneTimeChallengeId())) { + throw new AssertionError("OTP challenge changed during deterministic proof"); + } + challenges.delete(challenge); + } + }; + } + + private static AccountGameplayCanonicalLoginOwner.CredentialVerifier verifierMustNotRun( + AtomicInteger calls) { + return new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public void verifyAbsentAccountCredential(String presentedCredential) { + throw new AssertionError("Replay integration fixture must not verify decoy credentials"); + } + + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String presentedCredential) { + calls.incrementAndGet(); + throw new AssertionError("A replay must not re-verify or retain credentials"); + } + + @Override + public void consumeOneTimeCredential( + Account account, AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + calls.incrementAndGet(); + throw new AssertionError("A replay must not consume a credential again"); + } + }; + } + + private static AccountGameplayCredentialRequestDigestKeySource integrationDigestKeySource() { + CredentialDigestKey key = + new CredentialDigestKey( + "account-login-integration", + new SecretKeySpec(new byte[32], "HmacSHA256"), + Instant.MAX); + return new AccountGameplayCredentialRequestDigestKeySource() { + @Override + public CredentialDigestKey currentKey() { + return key; + } + + @Override + public CredentialDigestKey requireKey(String keyId) { + return key.keyId().equals(keyId) ? key : null; + } + }; + } + + private static T withAuthenticatedGameSession(java.util.function.Supplier action) { + AtomicReference result = new AtomicReference<>(); + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", "test", "game-session-service"); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> result.set(action.get())); + return result.get(); + } + + private static IssuerAccountSourceSnapshot currentSnapshot( + TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) { + return inTransaction( + context, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + } + + private static PendingIntent intent(IssuerAccountSourceSnapshot snapshot, UUID accountId) { + return intent( + snapshot, + accountId, + UUID.randomUUID(), + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private static PendingIntent intent( + IssuerAccountSourceSnapshot snapshot, + UUID accountId, + UUID requestId, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding) { + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + AccountSecurityCutoff cutoff = + snapshot + .account() + .accountSecurityCutoff() + .map( + value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())) + .orElse(null); + return new PendingIntent( + UUID.randomUUID(), + requestId, + CALLER_WORKLOAD, + callerContextId, + UUID.randomUUID(), + now, + now, + now + 120L, + new AccountAuthoritySnapshot( + accountId, + snapshot.issuer().generation(), + snapshot.issuer().sourceVersion(), + snapshot.account().generation(), + snapshot.account().sourceVersion(), + snapshot.issuanceFence().value(), + snapshot.issuanceFence().sourceVersion(), + Optional.ofNullable(cutoff)), + credentialRequestBinding); + } + + private static String compactCandidate(PendingIntent intent) throws Exception { + return compactCandidate(intent, intent.expiresAtEpochSecond()); + } + + private static String compactCandidate(PendingIntent intent, long expiresAt) throws Exception { + Map header = Map.of("alg", "RS256", "kid", "delegation-kid", "typ", "JWT"); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", intent.authoritySnapshot().accountId().toString()), + Map.entry("accountId", intent.authoritySnapshot().accountId().toString()), + Map.entry("jti", intent.tokenJti().toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", expiresAt), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence()))); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String head = encoder.encodeToString(canonicalBytes(header)); + String payload = encoder.encodeToString(canonicalBytes(claims)); + String signature = encoder.encodeToString(new byte[] {1, 2, 3}); + return head + "." + payload + "." + signature; + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256Hex(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static Map authorityTupleWithoutCutoff( + long issuerGeneration, long accountGeneration) { + Map tuple = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple(issuerGeneration, 1L)); + tuple.put("accountAuthorityGeneration", accountGeneration); + return tuple; + } + + private static RecordData readCandidate(DSLContext dsl, UUID requestId) { + var row = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT status, token_hash, pending_registry_candidate_bytes, " + + "authority_tuple_canonical_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + requestId) + .fetchOne(), + "issuance candidate query must return a row"); + return new RecordData( + row.get("status", String.class), + row.get("token_hash", String.class), + row.get("pending_registry_candidate_bytes", byte[].class), + row.get("authority_tuple_canonical_bytes", byte[].class)); + } + + private static AccountAuthoritySourceEvidenceRepository sourceEvidence( + DSLContext dsl, AccountAuthorityGenerationRepository authorities) { + return new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + } + + private static void insertRetainedUnboundPendingOperation(DSLContext dsl, PendingIntent intent) + throws Exception { + var authority = intent.authoritySnapshot(); + int inserted = + dsl.execute( + "INSERT INTO account_gameplay_delegation_issuance_operations " + + "(operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "request_digest_version, request_digest, token_jti, token_generation, " + + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " + + "authority_issuer_generation, authority_issuer_source_version, " + + "authority_account_generation, authority_account_source_version, issuance_fence, " + + "issuance_fence_source_version, authority_tuple_canonical_bytes, " + + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + intent.operationId(), + intent.requestId(), + authority.accountId(), + intent.callerWorkload(), + intent.callerContextId(), + "00".repeat(32), + intent.tokenJti(), + intent.issuedAtEpochSecond(), + intent.notBeforeEpochSecond(), + intent.expiresAtEpochSecond(), + authority.issuerGeneration(), + authority.issuerSourceVersion(), + authority.accountGeneration(), + authority.accountSourceVersion(), + authority.issuanceFence(), + authority.issuanceFenceSourceVersion(), + canonicalBytes(legacyNumericAuthorityTuple(authority)), + canonicalBytes(Map.of()), + canonicalBytes(legacyNumericSourceVersions(authority))); + assertThat(inserted).isEqualTo(1); + } + + /** + * V78's historical SQL guard expected JSON numeric generations before the V84 string contract. + */ + private static Map legacyNumericAuthorityTuple( + AccountAuthoritySnapshot authority) { + Map tuple = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())); + tuple.put("accountAuthorityGeneration", authority.accountGeneration()); + tuple.put("issuerAuthGeneration", authority.issuerGeneration()); + return tuple; + } + + private static Map legacyNumericSourceVersions( + AccountAuthoritySnapshot authority) { + return Map.of( + "accountSourceVersion", authority.accountSourceVersion(), + "issuanceFenceSourceVersion", authority.issuanceFenceSourceVersion(), + "issuerSourceVersion", authority.issuerSourceVersion()); + } + + private static void writeTestKeyring(Path root) throws Exception { + Files.createDirectories(root); + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) key[index] = (byte) (index + 1); + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", + StandardCharsets.US_ASCII); + } + + private static String sha1Hex(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(value)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private TestContext newTestContext() { + return newTestContext(null); + } + + private TestContext newTestContextAtVersion(String version) { + return newTestContext(MigrationVersion.fromVersion(version)); + } + + private TestContext newTestContext(MigrationVersion target) { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) flywayConfiguration.target(target); + flywayConfiguration.load().migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext( + new TransactionTemplate(transactionManager), transactionManager, dsl, dataSource, schema); + } + + private static void migrateTestSchemaToLatest(TestContext context) { + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .load() + .migrate(); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static void awaitLatch(CountDownLatch latch, String description) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to " + description); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted waiting to " + description, interrupted); + } + } + + private record TestContext( + TransactionTemplate transaction, + PlatformTransactionManager manager, + DSLContext dsl, + DriverManagerDataSource dataSource, + String schema) {} + + private enum CommitHook { + NONE, + WITHDRAW_SIGNER_TRUST, + ADVANCE_ACCOUNT_AFTER_PROJECTION, + AMBIGUOUS_COMMITTED_READBACK, + TRANSIENT_REDIS_READBACK, + CAPTURE_COMMIT_PROOF + } + + private record CommitHarness( + TestContext context, + DSLContext dsl, + UUID accountId, + AccountAuthoritySourceEvidenceRepository sources, + PendingIntent pending, + RedisHarness redis, + AccountGameplayDelegationIssuanceCommitService service, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayDelegationCommitSignerFixture signerFixture, + AccountGameplayDelegationSigner signer, + AccountGameplayCanonicalLoginOwner loginOwner, + CanonicalGameplayLoginRequest loginRequest) {} + + private static final class TransactionHookManager implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private final AtomicReference beforeTargetTransaction = + new AtomicReference<>(() -> {}); + + private TransactionHookManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + private void setBeforeTargetTransaction(Runnable operation) { + beforeTargetTransaction.set(operation); + } + + @Override + public org.springframework.transaction.TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + beforeTargetTransaction.getAndSet(() -> {}).run(); + return delegate.getTransaction(definition); + } + + @Override + public void commit(org.springframework.transaction.TransactionStatus status) { + delegate.commit(status); + } + + @Override + public void rollback(org.springframework.transaction.TransactionStatus status) { + delegate.rollback(status); + } + } + + private static final class RedisHarness { + private final UUID accountId; + private volatile boolean mismatchPendingReadback; + private final byte[][] authorityProjectionBytes; + private final AtomicReference pendingRecord = new AtomicReference<>(); + private final AtomicLong absoluteExpiryMillis = new AtomicLong(); + private final AtomicInteger connectionCloseCount = new AtomicInteger(); + private final AtomicInteger scriptLoadCount = new AtomicInteger(); + private final StatefulRedisConnection connection = + mock(StatefulRedisConnection.class); + private final RedisCommands commands = mock(RedisCommands.class); + private final AccountGameplayDelegationRedisClient client; + + private RedisHarness( + UUID accountId, + IssuerAccountSourceSnapshot source, + boolean mismatchPendingReadback, + ClassLoader resourceClassLoader) + throws Exception { + this.accountId = accountId; + this.mismatchPendingReadback = mismatchPendingReadback; + authorityProjectionBytes = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> { + scriptLoadCount.incrementAndGet(); + return sha1Hex(invocation.getArgument(0)); + }); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] keys = (byte[][]) invocation.getRawArguments()[2]; + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String key = new String(keys[0], StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + if (arguments.length == 2) { + pendingRecord.set(arguments[0].clone()); + } else if (arguments.length == 3) { + // The activation CAS ARGV order is exact PENDING bytes, exact ACTIVE bytes, + // and the original absolute deadline. Readback must see the ACTIVE record. + pendingRecord.set(arguments[1].clone()); + } else { + throw new AssertionError("Unexpected token-registry script arguments"); + } + absoluteExpiryMillis.set( + Long.parseLong( + new String(arguments[arguments.length - 1], StandardCharsets.US_ASCII))); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER)) { + authorityProjectionBytes[0] = arguments[0].clone(); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { + if (arguments.length == 3 && arguments[2].length > 0) { + authorityProjectionBytes[1] = arguments[2].clone(); + } + } + return 1L; + }); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + byte[] value = pendingRecord.get(); + if (value == null) return null; + return this.mismatchPendingReadback + ? ascii("different-pending-record") + : value.clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(key)) { + return authorityProjectionBytes[0].clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .equals(key)) { + return authorityProjectionBytes[1].clone(); + } + return null; + }); + when(commands.pexpiretime(any(byte[].class))) + .thenAnswer(invocation -> absoluteExpiryMillis.get()); + when(commands.pttl( + eq( + (AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .getBytes(StandardCharsets.US_ASCII)))) + .thenReturn(-1L); + when(commands.pttl( + eq( + (AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .getBytes(StandardCharsets.US_ASCII)))) + .thenReturn(-1L); + org.mockito.Mockito.doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + doAnswer( + invocation -> { + connectionCloseCount.incrementAndGet(); + return null; + }) + .when(connection) + .close(); + + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + client = + new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled(resourceClassLoader), + new AcknowledgementRequirements(1, 1, 1_000), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + resourceClassLoader); + } + + private AccountGameplayDelegationRedisClient client() { + return client; + } + + private byte[] registeredRecord() { + byte[] value = pendingRecord.get(); + return value == null ? null : value.clone(); + } + + private void restorePendingReadback() { + mismatchPendingReadback = false; + } + + private int connectionCloseCount() { + return connectionCloseCount.get(); + } + + private int scriptLoadCount() { + return scriptLoadCount.get(); + } + } + + private record BindReadSeal( + BoundTokenCandidate bound, + PendingRegistryCandidate persisted, + SealedCandidateObservation sealed) {} + + private record RecordData( + String status, String tokenHash, byte[] candidateBytes, byte[] authorityTupleBytes) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java new file mode 100644 index 0000000000..ee72ecd6a2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java @@ -0,0 +1,580 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_gameplay_resp"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final long CONCURRENT_PROOF_TIMEOUT_SECONDS = 180L; + private static final long CONCURRENT_WORKER_SHUTDOWN_TIMEOUT_SECONDS = 100L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir Path tempDirectory; + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void configureDatabase() { + postgres.start(); + } + + @AfterAll + static void stopOwnedContainer() { + postgres.stop(); + } + + @Test + void storesExactEncryptedCandidateAndRejectsMismatchRollbackAndExpiredHorizon() throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + UUID accountId = createAccount(context).getAccountUuid(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuancePersistenceIntegrationTest.advanceEmailVerifiedThroughOwner( + dsl, context.transaction(), sourceEvidence, accountId); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence); + IssuerAccountSourceSnapshot authority = currentSnapshot(context, sourceEvidence, accountId); + AccountAuthoritySnapshot authoritySnapshot = authoritySnapshot(authority); + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + PendingIntent pending = intent(authoritySnapshot, accountId, now); + inTransaction(context, () -> issuance.beginPending(pending)); + String compactJwt = compactCandidate(pending); + inTransaction( + context, () -> issuance.bindSignedCandidate(pending.requestId(), compactJwt, "1")); + + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + CallerIdentity caller = new CallerIdentity(pending.callerWorkload(), pending.callerContextId()); + + // The bytes are a deliberately unverified structurally valid candidate. This proves the + // Account source/bundle and encrypted-candidate storage primitive only; it does not prove a + // signer signature, registry write, completed issuance, or caller recovery authority. + writeTestKeyring(tempDirectory.resolve("response-keyring")); + AccountResponseEnvelopeCryptography realCrypto = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring( + tempDirectory.resolve("response-keyring").toString())); + AccountGameplayDelegationResponseEnvelopeRepository realResponses = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sourceEvidence, bundles, realCrypto); + CountDownLatch captureAndSealStart = new CountDownLatch(1); + ExecutorService concurrentCaptureAndSeal = Executors.newFixedThreadPool(2); + AccountAuthEvidenceBundle concurrentBundle; + AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation first; + try { + Future directCapture = + concurrentCaptureAndSeal.submit( + () -> { + captureAndSealStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); + Future seal = + concurrentCaptureAndSeal.submit( + () -> { + captureAndSealStart.await(); + return inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + pending.requestId(), caller, compactJwt)); + }); + captureAndSealStart.countDown(); + concurrentBundle = awaitConcurrentProof(directCapture); + first = awaitConcurrentProof(seal); + } finally { + stopConcurrentProofWorkers(concurrentCaptureAndSeal); + } + var retry = + inTransaction( + context, + () -> realResponses.sealPendingCandidate(pending.requestId(), caller, compactJwt)); + assertThat(retry).isEqualTo(first); + byte[] storedBundleBytes = + inTransaction( + context, + () -> bundles.readStoredNonAuthorizingValue(pending.operationId()).canonicalBytes()); + assertThat(storedBundleBytes).isEqualTo(concurrentBundle.canonicalBytes()); + assertThat(concurrentBundle.fields().get("authorityTuple")) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry( + "accountSecurityCutoff", + authoritySnapshot.accountSecurityCutoff().orElseThrow().toMap()); + assertThat(first.operationId()).isEqualTo(pending.operationId()); + assertThat(first.responseRecoveryExpiryEpochMillis()) + .isEqualTo(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L)); + assertThat(first.toString()).doesNotContain(compactJwt); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS response_count " + + "FROM account_gameplay_delegation_response_envelopes"), + "response count query must return a row") + .get("response_count", Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS bundle_count " + + "FROM account_gameplay_delegation_auth_evidence_bundles"), + "bundle count query must return a row") + .get("bundle_count", Long.class)) + .isEqualTo(1L); + byte[] storedEnvelope = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT envelope_bytes FROM account_gameplay_delegation_response_envelopes " + + "WHERE operation_id = ?", + pending.operationId()), + "stored response envelope query must return a row") + .get("envelope_bytes", byte[].class); + assertThat(new String(storedEnvelope, StandardCharsets.ISO_8859_1)).doesNotContain(compactJwt); + + byte[] boundMetadata = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pending_registry_candidate_bytes FROM " + + "account_gameplay_delegation_issuance_operations WHERE request_id = ?", + pending.requestId()), + "bound candidate query must return a row") + .get("pending_registry_candidate_bytes", byte[].class); + assertThat(new String(boundMetadata, StandardCharsets.ISO_8859_1)).doesNotContain(compactJwt); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + pending.requestId(), caller, compactJwt + "A"))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_response_envelopes " + + "SET envelope_bytes = ? WHERE operation_id = ?", + new byte[] {1, 2, 3}, + pending.operationId())) + .isInstanceOf(DataAccessException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT envelope_sha256 FROM " + + "account_gameplay_delegation_response_envelopes WHERE operation_id = ?", + pending.operationId()), + "response digest query must return a row") + .get("envelope_sha256", String.class)) + .isEqualTo(first.envelopeSha256()); + + PendingIntent secondPending = intent(authoritySnapshot, accountId, now); + inTransaction(context, () -> issuance.beginPending(secondPending)); + String secondJwt = compactCandidate(secondPending); + var secondCandidate = + inTransaction( + context, () -> issuance.bindSignedCandidate(secondPending.requestId(), secondJwt, "1")); + byte[] secondStoredBundleBytes = + inTransaction( + context, + () -> + bundles + .readStoredNonAuthorizingValue(secondPending.operationId()) + .canonicalBytes()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS bundle_count " + + "FROM account_gameplay_delegation_auth_evidence_bundles"), + "bound candidate bundle count query must return a row") + .get("bundle_count", Long.class)) + .isEqualTo(2L); + byte[] fakeCiphertext = new byte[] {1, 2, 3}; + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_gameplay_delegation_response_envelopes " + + "(operation_id, request_id, token_hash, signer_kid, " + + "signer_generation, authority_evidence_bundle_sha256, " + + "issuance_fence, response_recovery_expiry_epoch_ms, " + + "envelope_sha256, envelope_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + secondPending.operationId(), + secondPending.requestId(), + secondCandidate.tokenHash(), + secondCandidate.kid(), + secondCandidate.signerGeneration(), + "a".repeat(64), + authority.issuanceFence().value(), + Math.multiplyExact(secondPending.expiresAtEpochSecond(), 1_000L), + sha256(fakeCiphertext), + fakeCiphertext)) + .isInstanceOf(DataAccessException.class); + + var unavailableCrypto = + new AccountResponseEnvelopeCryptography(new AccountResponseEnvelopeKeyring("")); + var unavailableResponses = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sourceEvidence, bundles, unavailableCrypto); + CallerIdentity secondCaller = + new CallerIdentity(secondPending.callerWorkload(), secondPending.callerContextId()); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + unavailableResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt))) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS bundle_count " + + "FROM account_gameplay_delegation_auth_evidence_bundles"), + "bundle count query must return a row") + .get("bundle_count", Long.class)) + .isEqualTo(2L); + assertThat( + inTransaction( + context, + () -> + bundles.readStoredNonAuthorizingValue(pending.operationId()).canonicalBytes())) + .containsExactly(storedBundleBytes); + assertThat( + inTransaction( + context, + () -> + bundles + .readStoredNonAuthorizingValue(secondPending.operationId()) + .canonicalBytes())) + .containsExactly(secondStoredBundleBytes); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS response_count " + + "FROM account_gameplay_delegation_response_envelopes"), + "failed encryption response count query must return a row") + .get("response_count", Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchOne( + "SELECT operation_id FROM account_gameplay_delegation_response_envelopes " + + "WHERE operation_id = ?", + secondPending.operationId())) + .isNull(); + + CountDownLatch concurrentStart = new CountDownLatch(1); + ExecutorService concurrentRetries = Executors.newFixedThreadPool(2); + try { + Future firstRetry = + concurrentRetries.submit( + () -> { + concurrentStart.await(); + return inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt)); + }); + Future secondRetry = + concurrentRetries.submit( + () -> { + concurrentStart.await(); + return inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt)); + }); + concurrentStart.countDown(); + var firstConcurrentObservation = awaitConcurrentProof(firstRetry); + var secondConcurrentObservation = awaitConcurrentProof(secondRetry); + assertThat(firstConcurrentObservation).isEqualTo(secondConcurrentObservation); + assertThat(firstConcurrentObservation.operationId()).isEqualTo(secondPending.operationId()); + } finally { + stopConcurrentProofWorkers(concurrentRetries); + } + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS response_count " + + "FROM account_gameplay_delegation_response_envelopes"), + "response count query must return a row") + .get("response_count", Long.class)) + .isEqualTo(2L); + + long expiredIssueTime = now - 121L; + PendingIntent expiredPending = intent(authoritySnapshot, accountId, expiredIssueTime); + AccountGameplayDelegationIssuanceRepository expiredIssuance = + new AccountGameplayDelegationIssuanceRepository( + dsl, + sourceEvidence, + Clock.fixed(Instant.ofEpochSecond(expiredIssueTime), ZoneOffset.UTC)); + inTransaction(context, () -> expiredIssuance.beginPending(expiredPending)); + String expiredJwt = compactCandidate(expiredPending); + inTransaction( + context, + () -> expiredIssuance.bindSignedCandidate(expiredPending.requestId(), expiredJwt, "1")); + AccountGameplayDelegationResponseEnvelopeRepository expiredResponses = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sourceEvidence, bundles, realCrypto); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + expiredResponses.sealPendingCandidate( + expiredPending.requestId(), + new CallerIdentity( + expiredPending.callerWorkload(), expiredPending.callerContextId()), + expiredJwt))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException + .class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS response_count " + + "FROM account_gameplay_delegation_response_envelopes"), + "response count query must return a row") + .get("response_count", Long.class)) + .isEqualTo(2L); + } + + private static Account createAccount(TestContext context) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + account.setUsername("response-envelope-" + suffix); + account.setEmail("response-envelope-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + // The fresh Account birth path creates the exact empty global-role source only for null role. + DSLContext dsl = context.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository( + dsl, authorities, new AccountAuthorityOutboxRepository(dsl)); + return inTransaction( + context, + () -> { + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(dsl, sourceEvidence).save(account); + }); + } + + private static void writeTestKeyring(Path root) throws Exception { + Files.createDirectories(root); + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) { + key[index] = (byte) (index + 1); + } + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", + StandardCharsets.US_ASCII); + } + + private static IssuerAccountSourceSnapshot currentSnapshot( + TestContext context, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + UUID accountId) { + return inTransaction( + context, () -> sourceEvidence.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot snapshot) { + var cutoff = + snapshot + .account() + .accountSecurityCutoff() + .map( + value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + return new AccountAuthoritySnapshot( + snapshot.account().scope().accountId(), + snapshot.issuer().generation(), + snapshot.issuer().sourceVersion(), + snapshot.account().generation(), + snapshot.account().sourceVersion(), + snapshot.issuanceFence().value(), + snapshot.issuanceFence().sourceVersion(), + cutoff); + } + + private static PendingIntent intent( + AccountAuthoritySnapshot authoritySnapshot, UUID accountId, long now) { + if (!accountId.equals(authoritySnapshot.accountId())) { + throw new IllegalArgumentException( + "Fixture Account identity does not match its owner snapshot"); + } + return new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot, + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private static String compactCandidate(PendingIntent intent) throws Exception { + Map header = Map.of("alg", "RS256", "kid", "delegation-kid", "typ", "JWT"); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", intent.authoritySnapshot().accountId().toString()), + Map.entry("accountId", intent.authoritySnapshot().accountId().toString()), + Map.entry("jti", intent.tokenJti().toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", intent.expiresAtEpochSecond()), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence()))); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String head = encoder.encodeToString(canonicalJson(header)); + String payload = encoder.encodeToString(canonicalJson(claims)); + return head + "." + payload + "." + encoder.encodeToString(new byte[] {1, 2, 3}); + } + + private static byte[] canonicalJson(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), dsl); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static T awaitConcurrentProof(Future future) + throws InterruptedException, TimeoutException { + try { + return future.get(CONCURRENT_PROOF_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (ExecutionException workerFailure) { + throw new AssertionError( + "Concurrent response-envelope proof worker failed;sqlstate=" + + safeWorkerSqlState(workerFailure)); + } + } + + private static String safeWorkerSqlState(Throwable failure) { + Throwable current = failure; + for (int depth = 0; current != null && depth < 8; depth++) { + if (current instanceof SQLException sqlFailure) { + String sqlState = sqlFailure.getSQLState(); + if (sqlState != null && sqlState.matches("[0-9A-Z]{5}")) return sqlState; + } + current = current.getCause(); + } + return "UNKNOWN"; + } + + private static void stopConcurrentProofWorkers(ExecutorService executor) { + executor.shutdownNow(); + try { + if (!executor.awaitTermination( + CONCURRENT_WORKER_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new AssertionError("Concurrent response-envelope proof workers did not terminate"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("Concurrent response-envelope proof cleanup was interrupted"); + } + } + + private record TestContext(TransactionTemplate transaction, DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java new file mode 100644 index 0000000000..18513eac27 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java @@ -0,0 +1,477 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommitSignerFixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Exercises Account's SQL recovery component with physical PostgreSQL rows and the real Account + * signer, envelope cryptography, committed-issuance, and registry-owner classes. The pinned Redis + * connection is a deterministic Lettuce command fixture, not a live Redis deployment. This test + * does not call Authenticate, bind Game Session socket context, or prove full LOGIN behavior. + */ +class AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_gameplay_recovery"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + private static final SecureRandom RESPONSE_KEY_RANDOM = new SecureRandom(); + + @TempDir Path temporaryDirectory; + + @BeforeAll + static void configureDatabase() { + postgres.start(); + } + + @AfterAll + static void stopOwnedContainer() { + postgres.stop(); + } + + @Test + void repeatedRecoveryReadsOneCommittedOperationAndReturnsTheSameOriginalCredential() + throws Exception { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createAccount(context, sources); + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sources, accountId); + PendingIntent intent = intent(accountId, authoritySnapshot(snapshot)); + inTransaction(context, () -> issuance.beginPending(intent)); + + Path keyringRoot = Files.createDirectory(temporaryDirectory.resolve("response-keyring")); + writeResponseKeyring(keyringRoot.resolve("keyring")); + AccountResponseEnvelopeCryptography cryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(keyringRoot.toString())); + AccountGameplayDelegationResponseEnvelopeRepository responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, issuance, cryptography); + AccountGameplayDelegationResponseEnvelopeService envelopeService = + new AccountGameplayDelegationResponseEnvelopeService(responseRepository); + AccountGameplayDelegationCommitSignerFixture signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, issuance, envelopeService, context.manager(), Clock.systemUTC()); + signerFixture.observeDatabaseFailures(dsl); + RedisHarness redis = new RedisHarness(snapshot, getClass().getClassLoader()); + AccountGameplayDelegationTokenRegistry registry = + new AccountGameplayDelegationTokenRegistry( + issuance, + context.manager(), + redis.client(), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + 30_000L); + AccountGameplayDelegationAuthorityProjection authorityProjection = + new AccountGameplayDelegationAuthorityProjection( + sources, context.manager(), redis.client()); + AccountGameplayDelegationIssuanceCommitService commitService = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + registry, + authorityProjection, + issuance, + context.manager(), + Clock.systemUTC()); + + var committed = commitService.commitPendingCandidate(intent.requestId()); + assertThat(committed.operationId()).isEqualTo(intent.operationId()); + assertThat(committed.proofSha256()).matches("[0-9a-f]{64}"); + byte[] candidateBeforeRecovery = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pending_registry_candidate_bytes FROM " + + "account_gameplay_delegation_issuance_operations WHERE request_id = ?", + intent.requestId()), + "pending candidate query must return a row") + .get("pending_registry_candidate_bytes", byte[].class); + + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, signerFixture.signer(), registry, context.manager(), Clock.systemUTC()); + AccountGameplayDelegationResponseRecoveryOwner recoveryOwner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseRepository, committedOwner, context.manager()); + CallerIdentity caller = new CallerIdentity(intent.callerWorkload(), intent.callerContextId()); + + RecoveredCredential first = + recoveryOwner.recoverInitialLoginResponse(intent.requestId(), accountId, caller); + RecoveredCredential exactRetry = + recoveryOwner.recoverInitialLoginResponse(intent.requestId(), accountId, caller); + + assertThat(first.compactJwtBytes()).isNotEmpty(); + assertThat(new String(first.compactJwtBytes(), StandardCharsets.US_ASCII).split("\\.", -1)) + .hasSize(3) + .allSatisfy(segment -> assertThat(segment).isNotEmpty()); + assertThat(exactRetry.compactJwtBytes()).containsExactly(first.compactJwtBytes()); + assertThat(first.tokenSha256()).isEqualTo(exactRetry.tokenSha256()); + assertThat(first.tokenSha256()).isEqualTo(sha256(first.compactJwtBytes())); + assertThat(first.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(first.accountId()).isEqualTo(accountId); + assertThat(first.tokenJti()).isEqualTo(intent.tokenJti()); + assertThat(first.expiresAtEpochSecond()).isEqualTo(intent.expiresAtEpochSecond()); + assertThat(exactRetry.expiresAtEpochSecond()).isEqualTo(first.expiresAtEpochSecond()); + assertThat(first.toString()) + .doesNotContain(new String(first.compactJwtBytes(), StandardCharsets.US_ASCII)); + + var operationAfterRecovery = + dsl.fetchOne( + "SELECT status, token_hash, signer_generation, commit_proof_sha256, " + + "commit_proof_canonical_bytes, pending_registry_candidate_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + intent.requestId()); + assertThat(operationAfterRecovery.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(operationAfterRecovery.get("token_hash", String.class)) + .isEqualTo(first.tokenSha256()); + assertThat(operationAfterRecovery.get("signer_generation", String.class)).isEqualTo("42"); + assertThat(operationAfterRecovery.get("commit_proof_sha256", String.class)) + .isEqualTo(committed.proofSha256()); + byte[] commitProofCanonicalBytes = + operationAfterRecovery.get("commit_proof_canonical_bytes", byte[].class); + assertThat(containsByteSequence(commitProofCanonicalBytes, first.compactJwtBytes())).isFalse(); + assertThat(operationAfterRecovery.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(candidateBeforeRecovery); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS envelope_count " + + "FROM account_gameplay_delegation_response_envelopes WHERE request_id = ?", + intent.requestId()), + "response envelope count query must return a row") + .get("envelope_count", Long.class)) + .isEqualTo(1L); + byte[] storedEnvelope = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT envelope_bytes FROM account_gameplay_delegation_response_envelopes " + + "WHERE request_id = ?", + intent.requestId()), + "stored response envelope query must return a row") + .get("envelope_bytes", byte[].class); + assertThat(containsByteSequence(storedEnvelope, first.compactJwtBytes())).isFalse(); + assertThat(redis.activeRecord()).contains("\"state\":\"active\""); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext(new TransactionTemplate(transactionManager), transactionManager, dsl); + } + + private static UUID createAccount( + TestContext context, AccountAuthoritySourceEvidenceRepository sources) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + account.setUsername("recovery-" + suffix); + account.setEmail("recovery-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + // The fresh Account birth path creates the exact empty global-role source only for null role. + return inTransaction( + context, + () -> { + sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(context.dsl(), sources).save(account); + }) + .getAccountUuid(); + } + + private static IssuerAccountSourceSnapshot currentSnapshot( + TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) { + return inTransaction( + context, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot source) { + Optional cutoff = + source + .account() + .accountSecurityCutoff() + .map( + value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + return new AccountAuthoritySnapshot( + source.account().scope().accountId(), + source.issuer().generation(), + source.issuer().sourceVersion(), + source.account().generation(), + source.account().sourceVersion(), + source.issuanceFence().value(), + source.issuanceFence().sourceVersion(), + cutoff); + } + + private static PendingIntent intent(UUID accountId, AccountAuthoritySnapshot authority) { + long now = Instant.now().getEpochSecond(); + return new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 180L, + authority, + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private static void writeResponseKeyring(Path path) throws Exception { + byte[] key = new byte[32]; + RESPONSE_KEY_RANDOM.nextBytes(key); + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Arrays.fill(key, (byte) 0); + Files.writeString( + path, + "firemud-account-response-envelope-keyring-v1\nactive response-key-1 " + encoded + "\n", + StandardCharsets.US_ASCII); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static String sha256(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static boolean containsByteSequence(byte[] haystack, byte[] needle) { + if (needle.length == 0) { + return true; + } + for (int start = 0; start <= haystack.length - needle.length; start++) { + int offset = 0; + while (offset < needle.length && haystack[start + offset] == needle[offset]) { + offset++; + } + if (offset == needle.length) { + return true; + } + } + return false; + } + + private static String sha1(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(value)); + } + + private record TestContext( + TransactionTemplate transaction, PlatformTransactionManager manager, DSLContext dsl) {} + + private static final class RedisHarness { + private final AtomicReference tokenRecord = new AtomicReference<>(); + private final AtomicLong absoluteExpiryMillis = new AtomicLong(); + private final byte[][] projections; + private final StatefulRedisConnection connection = + mock(StatefulRedisConnection.class); + private final RedisCommands commands = mock(RedisCommands.class); + private final AccountGameplayDelegationRedisClient client; + + private RedisHarness(IssuerAccountSourceSnapshot snapshot, ClassLoader classLoader) + throws Exception { + projections = AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] keys = invocation.getArgument(2); + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String key = new String(keys[0], StandardCharsets.US_ASCII); + if (!key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + return 0L; + } + if (arguments.length == 2) { + byte[] existing = tokenRecord.get(); + long expiry = Long.parseLong(new String(arguments[1], StandardCharsets.US_ASCII)); + if (existing == null) { + tokenRecord.set(arguments[0].clone()); + absoluteExpiryMillis.set(expiry); + return 1L; + } + return Arrays.equals(existing, arguments[0]) + && absoluteExpiryMillis.get() == expiry + ? 0L + : -1L; + } + if (arguments.length == 3) { + byte[] observed = tokenRecord.get(); + long expiry = Long.parseLong(new String(arguments[2], StandardCharsets.US_ASCII)); + if (Arrays.equals(observed, arguments[0]) + && absoluteExpiryMillis.get() == expiry) { + tokenRecord.set(arguments[1].clone()); + return 1L; + } + return Arrays.equals(observed, arguments[1]) + && absoluteExpiryMillis.get() == expiry + ? 0L + : -1L; + } + return -1L; + }); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + byte[] value = tokenRecord.get(); + return value == null ? null : value.clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(key)) { + return projections[0].clone(); + } + if (key.startsWith( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX)) { + return projections[1].clone(); + } + return null; + }); + when(commands.pexpiretime(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + return key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX) + ? absoluteExpiryMillis.get() + : null; + }); + when(commands.pttl( + eq( + (AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + + snapshot.account().scope().accountId()) + .getBytes(StandardCharsets.US_ASCII)))) + .thenReturn(-1L); + when(commands.pttl( + eq( + (AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .getBytes(StandardCharsets.US_ASCII)))) + .thenReturn(-1L); + Mockito.doReturn(java.util.List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + doAnswer(invocation -> null).when(connection).close(); + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + client = + new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled(classLoader), + new AcknowledgementRequirements(1, 1, 1_000), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + classLoader); + } + + private AccountGameplayDelegationRedisClient client() { + return client; + } + + private String activeRecord() { + byte[] value = tokenRecord.get(); + return value == null ? "" : new String(value, StandardCharsets.UTF_8); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java new file mode 100644 index 0000000000..dcab9b5d8b --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java @@ -0,0 +1,598 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.sql.SQLException; +import java.time.Clock; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.jooq.DSLContext; +import org.jooq.ExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.postgresql.util.PSQLException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Integration-source-set-only signer harness. Cryptographic signing and verification are real; + * protected Kubernetes/API trust and committed materializer evidence are deliberately mocked. + */ +public final class AccountGameplayDelegationCommitSignerFixture { + private static final Logger LOGGER = + LoggerFactory.getLogger(AccountGameplayDelegationCommitSignerFixture.class); + private static final Set SAFE_CONSTRAINTS = + Set.of( + "account_gameplay_delegation_commit_immutable", + "account_gameplay_delegation_commit_shape", + "account_gameplay_delegation_candidate_one_way", + "account_gameplay_delegation_commit_evidence_match", + "account_gameplay_token_identity_shape", + "account_gameplay_token_revocation_shape"); + + private enum ProofStage { + BEFORE_SIGNING, + SIGNING_PENDING_CANDIDATE, + SIGNED_PENDING_CANDIDATE + } + + private final AtomicReference proofStage = + new AtomicReference<>(ProofStage.BEFORE_SIGNING); + private static final String ENVIRONMENT = "staging"; + private static final String CLUSTER = "cluster-a"; + private static final String NAMESPACE = "firemud"; + private static final String MATERIALIZER_REVISION = "materializer-r1"; + private static final String API_REVISION = "api-revision-1"; + private static final String MATERIALIZER_DIGEST = "b".repeat(64); + private static final String API_DIGEST = "c".repeat(64); + private static final String SERVING_CA_DIGEST = "e".repeat(64); + private static final String CLUSTER_UID = "44444444-4444-4444-8444-444444444444"; + private static final String NAMESPACE_UID = "55555555-5555-4555-8555-555555555555"; + private static final String CONFIG_MAP_UID = "66666666-6666-4666-8666-666666666666"; + private static final String API_ORIGIN = "https://kubernetes.example.test:6443"; + private static final UUID GENERATION_OPERATION_ID = + UUID.fromString("7af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final UUID PROMOTION_OPERATION_ID = + UUID.fromString("8af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final UUID ROTATED_GENERATION_OPERATION_ID = + UUID.fromString("9af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final UUID ROTATED_PROMOTION_OPERATION_ID = + UUID.fromString("aaf097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final String GENERATION = "42"; + private static final String KID = "account-key-42"; + private static final String ROTATED_GENERATION = "43"; + private static final String ROTATED_KID = "account-key-43"; + + private final AccountGameplayDelegationSigner signer; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtSignerDesiredStateRepository.Binding signerBinding; + private final TrustFence trustFence; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final SourceIdentity sourceIdentity; + private final Path privateBundlePath; + private final Path publicJwksPath; + private final RSAPublicKey originalPublicKey; + private final AtomicReference currentKeyPair; + private final AtomicReference currentGeneration = new AtomicReference<>(GENERATION); + private final AtomicReference currentKid = new AtomicReference<>(KID); + private final AtomicReference currentOwnerEvidence = + new AtomicReference<>(); + private final AtomicReference trustedJwksJson = new AtomicReference<>(); + + private AccountGameplayDelegationCommitSignerFixture( + Path temporaryDirectory, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayDelegationResponseEnvelopeService envelopeService, + PlatformTransactionManager transactionManager, + Clock clock) + throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + KeyPair pair = generator.generateKeyPair(); + originalPublicKey = (RSAPublicKey) pair.getPublic(); + currentKeyPair = new AtomicReference<>(pair); + String fingerprint = fingerprint(pair); + sourceIdentity = sourceIdentity(); + signerBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + trustFence = + new TrustFence(CLUSTER_UID, NAMESPACE_UID, MATERIALIZER_DIGEST, MATERIALIZER_REVISION); + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + GENERATION_OPERATION_ID.toString(), + GENERATION, + KID, + fingerprint); + + Path privateRoot = + Files.createDirectory(temporaryDirectory.resolve("private-" + UUID.randomUUID())); + Path publicRoot = + Files.createDirectory(temporaryDirectory.resolve("public-" + UUID.randomUUID())); + privateBundlePath = privateRoot.resolve("current.key"); + publicJwksPath = publicRoot.resolve("jwks.json"); + Files.writeString(privateBundlePath, privateBundleJson(expectedIdentity, pair)); + String originalJwks = jwksJson(Map.of(KID, originalPublicKey)); + Files.writeString(publicJwksPath, originalJwks); + trustedJwksJson.set(originalJwks); + + materializerTrust = mock(AccountJwtSignerMaterializerTrustBinding.class); + AccountJwtSignerMaterializerTrustBinding.Binding materializer = + mock(AccountJwtSignerMaterializerTrustBinding.Binding.class); + when(materializer.environmentId()).thenReturn(ENVIRONMENT); + when(materializer.clusterId()).thenReturn(CLUSTER); + when(materializer.namespace()).thenReturn(NAMESPACE); + when(materializer.expectedClusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(materializer.expectedNamespaceUid()).thenReturn(NAMESPACE_UID); + when(materializer.bindingDigest()).thenReturn(MATERIALIZER_DIGEST); + when(materializer.configRevision()).thenReturn(MATERIALIZER_REVISION); + when(materializerTrust.current()).thenReturn(Optional.of(materializer)); + + AccountJwtJwksApiBinding apiBinding = mock(AccountJwtJwksApiBinding.class); + AccountJwtJwksApiBinding.ParsedBinding api = mock(AccountJwtJwksApiBinding.ParsedBinding.class); + when(api.environmentId()).thenReturn(ENVIRONMENT); + when(api.clusterId()).thenReturn(CLUSTER); + when(api.namespace()).thenReturn(NAMESPACE); + when(api.expectedClusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(api.expectedNamespaceUid()).thenReturn(NAMESPACE_UID); + when(api.bindingDigest()).thenReturn(API_DIGEST); + when(api.configRevision()).thenReturn(API_REVISION); + when(api.apiServer()).thenReturn(java.net.URI.create(API_ORIGIN)); + when(api.servingCaSha256()).thenReturn(SERVING_CA_DIGEST); + when(apiBinding.current()).thenReturn(api); + + trustedJwksSource = mock(AccountJwtJwksTrustedSource.class); + when(trustedJwksSource.sourceIdentity()).thenReturn(sourceIdentity); + when(trustedJwksSource.load()) + .thenAnswer( + invocation -> + new PublicJwksSnapshot( + sourceIdentity, trustedJwksJson.get().getBytes(StandardCharsets.UTF_8))); + + AccountJwtSignerDesiredStateRepository desiredState = + mock(AccountJwtSignerDesiredStateRepository.class); + currentOwnerEvidence.set( + ownerEvidence( + signerBinding, + trustFence, + fingerprint, + GENERATION, + KID, + GENERATION_OPERATION_ID, + PROMOTION_OPERATION_ID, + Optional.empty(), + Optional.empty(), + 6L, + "12", + "13", + "20", + "21")); + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenAnswer(invocation -> Optional.of(currentOwnerEvidence.get())); + + signer = + spy( + new AccountGameplayDelegationSigner( + issuance, + desiredState, + materializerTrust, + apiBinding, + trustedJwksSource, + envelopeService, + transactionManager, + clock, + privateBundlePath.getParent(), + privateBundlePath.getFileName(), + publicJwksPath.getParent(), + publicJwksPath.getFileName())); + doAnswer( + invocation -> { + proofStage.set(ProofStage.SIGNING_PENDING_CANDIDATE); + try { + Object result = invocation.callRealMethod(); + proofStage.set(ProofStage.SIGNED_PENDING_CANDIDATE); + return result; + } catch (RuntimeException failure) { + reportSafeFailure(failure); + throw failure; + } + }) + .when(signer) + .signPendingCandidate(any(UUID.class)); + } + + /** Observes failures only; does not retain SQL, exception text, or throwable objects. */ + public void observeDatabaseFailures(DSLContext dsl) { + dsl.configuration() + .setAppending( + new DefaultExecuteListenerProvider( + ExecuteListener.onException(context -> reportSafeFailure(context.sqlException())))); + } + + private void reportSafeFailure(Throwable failure) { + LOGGER.warn( + "Account integration proof failure: stage={};{}", + proofStage.get().name(), + safeFailureDiagnostic(failure)); + } + + /** Returns only SQLSTATE and a constraint identifier from the fixed Account allowlist. */ + public static String safeFailureDiagnostic(Throwable failure) { + String sqlState = "UNKNOWN"; + String constraint = "UNKNOWN"; + Throwable current = failure; + for (int depth = 0; current != null && depth < 8; depth++, current = current.getCause()) { + if (current instanceof PSQLException postgresFailure) { + String candidateSqlState = postgresFailure.getSQLState(); + if (candidateSqlState != null && candidateSqlState.matches("[0-9A-Z]{5}")) { + sqlState = candidateSqlState; + } + var serverError = postgresFailure.getServerErrorMessage(); + String candidateConstraint = serverError == null ? null : serverError.getConstraint(); + if (candidateConstraint != null && SAFE_CONSTRAINTS.contains(candidateConstraint)) { + constraint = candidateConstraint; + } + break; + } + if (current instanceof SQLException sqlFailure) { + String candidate = sqlFailure.getSQLState(); + if (candidate != null && candidate.matches("[0-9A-Z]{5}")) { + sqlState = candidate; + } + } + } + return "sqlstate=" + sqlState + ";constraint=" + constraint; + } + + public static AccountGameplayDelegationCommitSignerFixture create( + Path temporaryDirectory, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayDelegationResponseEnvelopeService envelopeService, + PlatformTransactionManager transactionManager, + Clock clock) + throws Exception { + return new AccountGameplayDelegationCommitSignerFixture( + temporaryDirectory, issuance, envelopeService, transactionManager, clock); + } + + public AccountGameplayDelegationSigner signer() { + return signer; + } + + /** Prepares the real signer-produced pending candidate without exposing its compact JWT. */ + public void preparePendingCandidate(UUID requestId) { + signer.signPendingCandidate(requestId); + } + + /** Advances mocked protected signer evidence while retaining the original public key in JWKS. */ + public void rotateToNextGenerationRetainingOriginalKey() throws Exception { + if (!GENERATION.equals(currentGeneration.get())) { + throw new IllegalStateException("The integration signer fixture has already rotated"); + } + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + KeyPair rotatedPair = generator.generateKeyPair(); + String rotatedFingerprint = fingerprint(rotatedPair); + var expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + ROTATED_GENERATION_OPERATION_ID.toString(), + ROTATED_GENERATION, + ROTATED_KID, + rotatedFingerprint); + LinkedHashMap retainedKeys = new LinkedHashMap<>(); + retainedKeys.put(KID, originalPublicKey); + retainedKeys.put(ROTATED_KID, (RSAPublicKey) rotatedPair.getPublic()); + String retainedJwks = jwksJson(retainedKeys); + + Files.writeString(privateBundlePath, privateBundleJson(expectedIdentity, rotatedPair)); + Files.writeString(publicJwksPath, retainedJwks); + trustedJwksJson.set(retainedJwks); + currentOwnerEvidence.set( + ownerEvidence( + signerBinding, + trustFence, + rotatedFingerprint, + ROTATED_GENERATION, + ROTATED_KID, + ROTATED_GENERATION_OPERATION_ID, + ROTATED_PROMOTION_OPERATION_ID, + Optional.of(new ActiveSigner(GENERATION, KID)), + Optional.of(fingerprint(originalPublicKey)), + 7L, + "13", + "14", + "21", + "22")); + currentKeyPair.set(rotatedPair); + currentKid.set(ROTATED_KID); + currentGeneration.set(ROTATED_GENERATION); + } + + /** + * Removes only the original key from the mocked current JWKS to exercise fail-closed recovery. + */ + public void withdrawOriginalKeyFromCurrentJwks() { + if (!ROTATED_GENERATION.equals(currentGeneration.get())) { + throw new IllegalStateException("Historical-key withdrawal requires the rotated fixture"); + } + trustedJwksJson.set( + jwksJson(Map.of(currentKid.get(), (RSAPublicKey) currentKeyPair.get().getPublic()))); + } + + /** Restores the exact original public key in the mocked current JWKS after a negative case. */ + public void restoreOriginalKeyInCurrentJwks() { + if (!ROTATED_GENERATION.equals(currentGeneration.get())) { + throw new IllegalStateException("Historical-key restoration requires the rotated fixture"); + } + LinkedHashMap retainedKeys = new LinkedHashMap<>(); + retainedKeys.put(KID, originalPublicKey); + retainedKeys.put(currentKid.get(), (RSAPublicKey) currentKeyPair.get().getPublic()); + trustedJwksJson.set(jwksJson(retainedKeys)); + } + + public String currentGeneration() { + return currentGeneration.get(); + } + + public String currentKid() { + return currentKid.get(); + } + + public void withdrawTrust() { + when(materializerTrust.current()).thenReturn(Optional.empty()); + } + + private static CommittedSignerEvidence ownerEvidence( + AccountJwtSignerDesiredStateRepository.Binding binding, + TrustFence trust, + String fingerprint, + String generationValue, + String kid, + UUID generationOperationId, + UUID promotionOperationId, + Optional previousActive, + Optional previousFingerprint, + long prePromotionStateVersion, + String expectedSecretResourceVersion, + String observedSecretResourceVersion, + String expectedPublicResourceVersion, + String observedPublicResourceVersion) { + ActiveSigner active = new ActiveSigner(generationValue, kid); + boolean initialGeneration = GENERATION.equals(generationValue); + String operationDigest = initialGeneration ? "2".repeat(64) : "3".repeat(64); + String generationRequestDigest = initialGeneration ? "3".repeat(64) : "4".repeat(64); + String promotionRequestDigest = initialGeneration ? "5".repeat(64) : "6".repeat(64); + String generationReceiptDigest = initialGeneration ? "4".repeat(64) : "5".repeat(64); + String prepublicationIntentDigest = initialGeneration ? "6".repeat(64) : "7".repeat(64); + String prepublicationReceiptDigest = initialGeneration ? "7".repeat(64) : "8".repeat(64); + String mountedObservationDigest = initialGeneration ? "8".repeat(64) : "9".repeat(64); + String readinessPlanDigest = initialGeneration ? "9".repeat(64) : "a".repeat(64); + String readinessEvidenceDigest = initialGeneration ? "a".repeat(64) : "b".repeat(64); + String privateReceiptDigest = initialGeneration ? "b".repeat(64) : "c".repeat(64); + String publicDataDigest = initialGeneration ? "c".repeat(64) : "d".repeat(64); + String publicReceiptDigest = initialGeneration ? "d".repeat(64) : "e".repeat(64); + DesiredState desired = + new DesiredState( + binding, + Math.addExact(prePromotionStateVersion, 1L), + Optional.of(active), + Optional.of(active), + Optional.of(generationOperationId), + Optional.empty(), + Optional.empty()); + + GenerationResult generation = mock(GenerationResult.class); + when(generation.operationId()).thenReturn(generationOperationId); + when(generation.binding()).thenReturn(binding); + when(generation.trustFence()).thenReturn(trust); + when(generation.operationDigest()).thenReturn(operationDigest); + when(generation.generationRequestDigest()).thenReturn(generationRequestDigest); + when(generation.desiredStateVersion()).thenReturn(prePromotionStateVersion); + when(generation.privateSecretName()) + .thenReturn(AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + when(generation.secretUid()).thenReturn(CONFIG_MAP_UID); + when(generation.expectedPriorResourceVersion()).thenReturn(expectedSecretResourceVersion); + when(generation.observedResourceVersion()).thenReturn(observedSecretResourceVersion); + when(generation.targetGeneration()).thenReturn(generationValue); + when(generation.targetKid()).thenReturn(kid); + when(generation.targetAlgorithm()).thenReturn("RS256"); + when(generation.publicKeyFingerprint()).thenReturn(fingerprint); + when(generation.receiptDigest()).thenReturn(generationReceiptDigest); + + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + when(promotion.operationId()).thenReturn(promotionOperationId); + when(promotion.generationOperationId()).thenReturn(generationOperationId); + when(promotion.binding()).thenReturn(binding); + when(promotion.trustFence()).thenReturn(trust); + when(promotion.targetGeneration()).thenReturn(generationValue); + when(promotion.targetKid()).thenReturn(kid); + when(promotion.targetAlgorithm()).thenReturn("RS256"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(fingerprint); + when(promotion.requestDigest()).thenReturn(promotionRequestDigest); + when(promotion.expectedRecordVersion()).thenReturn(prePromotionStateVersion); + when(promotion.expectedPreviousActive()).thenReturn(previousActive); + when(promotion.expectedPreviousPublicKeyFingerprint()).thenReturn(previousFingerprint); + when(promotion.expectedPublishedActive()).thenReturn(Optional.of(active)); + when(promotion.generationOperationDigest()).thenReturn(operationDigest); + when(promotion.generationReceiptDigest()).thenReturn(generationReceiptDigest); + when(promotion.secretUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPrivateResourceVersion()).thenReturn(expectedSecretResourceVersion); + when(promotion.apiBindingDigest()).thenReturn(API_DIGEST); + when(promotion.apiConfigRevision()).thenReturn(API_REVISION); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicResourceVersion()).thenReturn(expectedPublicResourceVersion); + when(promotion.prepublicationIntentDigest()).thenReturn(prepublicationIntentDigest); + when(promotion.prepublicationReceiptDigest()).thenReturn(prepublicationReceiptDigest); + when(promotion.mountedObservationDigest()).thenReturn(mountedObservationDigest); + when(promotion.readinessPlanDigest()).thenReturn(readinessPlanDigest); + when(promotion.readinessEvidenceDigest()).thenReturn(readinessEvidenceDigest); + when(promotion.status()).thenReturn("COMMITTED"); + when(promotion.privatePromotionDispatched()).thenReturn(true); + when(promotion.privatePromotionObservedResourceVersion()) + .thenReturn(Optional.of(observedSecretResourceVersion)); + when(promotion.privatePromotionReceiptDigest()).thenReturn(Optional.of(privateReceiptDigest)); + when(promotion.activeJwksObservedResourceVersion()) + .thenReturn(Optional.of(observedPublicResourceVersion)); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of(publicDataDigest)); + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.of(publicReceiptDigest)); + + return new CommittedSignerEvidence( + promotion, + generation, + desired, + new PrivatePromotionReceipt( + promotionOperationId, + generationOperationId, + observedSecretResourceVersion, + privateReceiptDigest), + new ActiveJwksPromotionReceipt( + promotionOperationId, + CONFIG_MAP_UID, + expectedPublicResourceVersion, + observedPublicResourceVersion, + publicDataDigest, + publicReceiptDigest)); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + API_REVISION, + API_ORIGIN, + SERVING_CA_DIGEST); + } + + private static String privateBundleJson( + AccountMountedJwtSignerBundle.ExpectedIdentity identity, KeyPair pair) { + return "{" + + "\"version\":1," + + "\"environmentId\":\"" + + identity.environmentId() + + "\"," + + "\"clusterId\":\"" + + identity.clusterId() + + "\"," + + "\"namespace\":\"" + + identity.namespace() + + "\"," + + "\"operationId\":\"" + + identity.operationId() + + "\"," + + "\"generation\":\"" + + identity.generation() + + "\"," + + "\"kid\":\"" + + identity.kid() + + "\"," + + "\"algorithm\":\"RS256\"," + + "\"privateKeyPkcs8\":\"" + + base64Url(((RSAPrivateCrtKey) pair.getPrivate()).getEncoded()) + + "\",\"publicKeyFingerprint\":\"" + + identity.publicKeyFingerprint() + + "\"}"; + } + + private static String jwksJson(Map keys) { + StringBuilder json = new StringBuilder("{\"keys\":["); + boolean first = true; + for (Map.Entry entry : keys.entrySet()) { + if (!first) json.append(','); + first = false; + RSAPublicKey key = entry.getValue(); + json.append("{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\"") + .append(entry.getKey()) + .append("\",\"key_ops\":[\"verify\"],\"n\":\"") + .append(base64Url(unsigned(key.getModulus()))) + .append("\",\"e\":\"") + .append(base64Url(unsigned(key.getPublicExponent()))) + .append("\"}"); + } + return json.append("]}").toString(); + } + + private static String fingerprint(KeyPair pair) { + return fingerprint((RSAPublicKey) pair.getPublic()); + } + + private static String fingerprint(RSAPublicKey key) { + String material = + "{\"e\":\"" + + base64Url(unsigned(key.getPublicExponent())) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsigned(key.getModulus())) + + "\"}"; + try { + return HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(material.getBytes(StandardCharsets.US_ASCII))); + } catch (java.security.GeneralSecurityException failure) { + throw new IllegalStateException("Test signer fingerprint is unavailable"); + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] encoded = value.toByteArray(); + return encoded.length > 1 && encoded[0] == 0 + ? Arrays.copyOfRange(encoded, 1, encoded.length) + : encoded; + } + + private static String base64Url(byte[] value) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } finally { + Arrays.fill(value, (byte) 0); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java new file mode 100644 index 0000000000..dbbd1bcddd --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -0,0 +1,2435 @@ +package integration.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.output.StatusOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommitSignerFixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjection; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.ExecuteListener; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.postgresql.util.PSQLException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exercises Account's registered Coordination Redis scripts against isolated test-owned physical + * Redis and PostgreSQL fixtures. An explicitly supplied isolated loopback Redis pair remains + * supported. This test does not establish deployed ACL/TLS custody. + */ +class AccountGameplayDelegationRedisIntegrationTest { + private static final String REDIS_URI_ENV = "FIREMUD_ACCOUNT_REDIS_INTEGRATION_URI"; + private static final String FIXTURE_ADMIN_URI_ENV = "FIREMUD_ACCOUNT_REDIS_FIXTURE_ADMIN_URI"; + private static final String ACCOUNT_IDENTITY = "account_coord_app"; + private static final String FIXTURE_ADMIN_IDENTITY = "account_proof_fixture_admin"; + private static final String FIXTURE_ADMIN_PASSWORD = + UUID.randomUUID().toString().replace("-", ""); + private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final int REDIS_PORT = 6379; + private static final String SCHEMA_PREFIX = "acct_gameplay_active_"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final long PROJECTION_BYTES = + AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES; + private static final int REGISTRY_BYTES = + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Network REDIS_NETWORK = Network.newNetwork(); + private static final GenericContainer REDIS_PRIMARY = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .withNetworkAliases("account-gameplay-delegation-primary") + .withExposedPorts(REDIS_PORT) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + private static final GenericContainer REDIS_REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .dependsOn(REDIS_PRIMARY) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "account-gameplay-delegation-primary", + Integer.toString(REDIS_PORT)); + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); + private static RedisURI writerUri; + private static RedisURI fixtureAdminUri; + private static RedisClient redisBootstrapClient; + private static boolean ownsRedisFixture; + private String ownedPostgresSchema; + + @TempDir Path temporaryDirectory; + + @BeforeAll + static void startPhysicalFixtures() throws InterruptedException { + String configuredWriter = System.getenv(REDIS_URI_ENV); + String configuredAdmin = System.getenv(FIXTURE_ADMIN_URI_ENV); + boolean writerConfigured = configuredWriter != null && !configuredWriter.isBlank(); + boolean adminConfigured = configuredAdmin != null && !configuredAdmin.isBlank(); + if (writerConfigured != adminConfigured) { + throw new IllegalStateException( + REDIS_URI_ENV + " and " + FIXTURE_ADMIN_URI_ENV + " must be configured together"); + } + + if (writerConfigured) { + writerUri = requireLoopbackUri(configuredWriter, ACCOUNT_IDENTITY); + fixtureAdminUri = requireLoopbackUri(configuredAdmin, FIXTURE_ADMIN_IDENTITY); + if (writerUri.getPort() != fixtureAdminUri.getPort()) { + throw new IllegalArgumentException( + "The Account writer and fixture administrator must address the same Redis primary"); + } + } else { + assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "Docker is unavailable; physical Account Redis proof is skipped"); + ownsRedisFixture = true; + REDIS_PRIMARY.start(); + REDIS_REPLICA.start(); + int primaryPort = REDIS_PRIMARY.getMappedPort(REDIS_PORT); + redisBootstrapClient = redisClient("127.0.0.1", primaryPort, null, null); + try (var connection = redisBootstrapClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + configureAccountUser(commands); + configureFixtureAdmin(commands); + awaitLocalAndReplicaAof(commands); + } + writerUri = authenticatedUri(primaryPort, ACCOUNT_IDENTITY, ACCOUNT_PASSWORD); + fixtureAdminUri = + authenticatedUri(primaryPort, FIXTURE_ADMIN_IDENTITY, FIXTURE_ADMIN_PASSWORD); + } + + POSTGRES.start(); + } + + @AfterAll + static void stopPhysicalFixtures() { + POSTGRES.stop(); + if (redisBootstrapClient != null) { + redisBootstrapClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + if (ownsRedisFixture) { + if (REDIS_REPLICA.isRunning()) REDIS_REPLICA.stop(); + if (REDIS_PRIMARY.isRunning()) REDIS_PRIMARY.stop(); + REDIS_NETWORK.close(); + } + } + + @AfterEach + void dropOwnedPostgresSchema() { + if (ownedPostgresSchema == null) return; + if (!ownedPostgresSchema.startsWith(SCHEMA_PREFIX) + || !ownedPostgresSchema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned Account proof schema"); + } + try { + new JdbcTemplate(POSTGRES.dataSource()) + .execute("DROP SCHEMA IF EXISTS \"" + ownedPostgresSchema + "\" CASCADE"); + } finally { + ownedPostgresSchema = null; + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenantBound) + throws Exception { + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + StatefulRedisConnection adminConnection = null; + Set ownedKeys = new LinkedHashSet<>(); + try { + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(FIXTURE_ADMIN_IDENTITY); + + UUID accountId = UUID.randomUUID(); + PendingFixture pending = pendingFixture(accountId, tenantBound ? UUID.randomUUID() : null); + String pendingKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + pending.record().tokenHash(); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER; + String accountKey = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + for (String key : List.of(pendingKey, issuerKey, accountKey)) { + assertThat(admin.get(ascii(key))) + .as("isolated fixture key is absent before this test owns it") + .isNull(); + } + + TrackedProvider writerProvider = new TrackedProvider(writer); + AccountGameplayDelegationRedisClient redis = redisClient(writerProvider); + ownedKeys.add(pendingKey); + + int pendingCreateConnection = writerProvider.openedConnections(); + var created = + redis.registerPending( + pending.record().tokenHash(), pending.recordBytes(), pending.absoluteExpiryMillis()); + assertThat(created.outcome()).isEqualTo(PendingRegistrationOutcome.CREATED); + assertThat(created.localAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(created.replicaAofCount()).isGreaterThanOrEqualTo(1L); + assertSingleConnectionTrace( + writerProvider, + pendingCreateConnection, + "aclWhoami", + "scriptLoad", + "evalsha", + "dispatch", + "get", + "pexpiretime", + "close"); + assertThat(admin.get(ascii(pendingKey))).containsExactly(pending.recordBytes()); + assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); + + int pendingRetryConnection = writerProvider.openedConnections(); + var exactRetry = + redis.registerPending( + pending.record().tokenHash(), pending.recordBytes(), pending.absoluteExpiryMillis()); + assertThat(exactRetry.outcome()).isEqualTo(PendingRegistrationOutcome.EXACT_RETRY); + assertThat(exactRetry.absoluteExpiryMillis()).isEqualTo(pending.absoluteExpiryMillis()); + assertThat(exactRetry.localAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(exactRetry.replicaAofCount()).isGreaterThanOrEqualTo(1L); + assertSingleConnectionTrace( + writerProvider, + pendingRetryConnection, + "aclWhoami", + "scriptLoad", + "evalsha", + "dispatch", + "get", + "pexpiretime", + "close"); + + Map changedFields = new java.util.LinkedHashMap<>(pending.record().fields()); + changedFields.put("operationId", UUID.randomUUID().toString()); + changedFields.put("requestDigest", "b".repeat(64)); + byte[] changedRecord = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(changedFields)); + int changedBytesConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.registerPending( + pending.record().tokenHash(), changedRecord, pending.absoluteExpiryMillis())) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(changedBytesConnection)) + .containsSubsequence("aclWhoami", "scriptLoad", "evalsha", "close") + .doesNotContain("dispatch", "get", "pexpiretime"); + assertThat(admin.get(ascii(pendingKey))).containsExactly(pending.recordBytes()); + assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); + + int changedDeadlineConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.registerPending( + pending.record().tokenHash(), + pending.recordBytes(), + Math.addExact(pending.absoluteExpiryMillis(), 1_000L))) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(changedDeadlineConnection)) + .containsSubsequence("aclWhoami", "scriptLoad", "evalsha", "close") + .doesNotContain("dispatch", "get", "pexpiretime"); + assertThat(admin.get(ascii(pendingKey))).containsExactly(pending.recordBytes()); + assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); + + int insufficientReplicaAofConnection = writerProvider.openedConnections(); + AccountGameplayDelegationRedisClient insufficientReplicaAofClient = + redisClient(writerProvider, new AcknowledgementRequirements(1, 2, 250)); + assertThatThrownBy( + () -> + insufficientReplicaAofClient.registerPending( + pending.record().tokenHash(), + pending.recordBytes(), + pending.absoluteExpiryMillis())) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(insufficientReplicaAofConnection)) + .containsSubsequence("aclWhoami", "scriptLoad", "evalsha", "dispatch", "close") + .doesNotContain("get", "pexpiretime"); + assertThat(admin.get(ascii(pendingKey))).containsExactly(pending.recordBytes()); + assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); + + ownedKeys.add(issuerKey); + ownedKeys.add(accountKey); + byte[][] initialProjection = projectionPair(accountId, 7L, 7L, "issuer-base", "account-base"); + int projectionPublishConnection = writerProvider.openedConnections(); + assertThat( + redis.publishAuthorityProjections( + accountId, initialProjection[0], initialProjection[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertSingleConnectionTrace( + writerProvider, + projectionPublishConnection, + "aclWhoami", + "scriptLoad", + "evalsha", + "evalsha", + "dispatch", + "get", + "get", + "close"); + assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + + int projectionReadConnection = writerProvider.openedConnections(); + byte[][] observedProjection = redis.readAuthorityProjections(accountId); + assertThat(Arrays.equals(observedProjection[0], initialProjection[0])).isTrue(); + assertThat(Arrays.equals(observedProjection[1], initialProjection[1])).isTrue(); + assertSingleConnectionTrace( + writerProvider, projectionReadConnection, "aclWhoami", "get", "get", "close"); + String accountProjectionJson = new String(observedProjection[1], StandardCharsets.UTF_8); + var decodedAccount = AccountGenerationProjection.parse(accountProjectionJson); + assertThat(decodedAccount.accountAuthorityGeneration()).isEqualTo("7"); + assertThat(decodedAccount.outboxSequence()).isEqualTo("6"); + assertThat(decodedAccount.sourceEvent()).isPresent(); + + int projectionRetryConnection = writerProvider.openedConnections(); + assertThat( + redis.publishAuthorityProjections( + accountId, initialProjection[0], initialProjection[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertThat(writerProvider.trace(projectionRetryConnection)) + .containsSubsequence( + "aclWhoami", "scriptLoad", "evalsha", "evalsha", "dispatch", "get", "get", "close"); + + byte[][] regressedProjection = + projectionPair(accountId, 6L, 8L, "issuer-stale", "account-newer"); + byte[] accountBeforeIssuerRegression = admin.get(ascii(accountKey)); + int issuerRegressionConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, regressedProjection[0], regressedProjection[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(issuerRegressionConnection)) + .containsExactly("aclWhoami", "scriptLoad", "evalsha", "close"); + assertThat(admin.get(ascii(issuerKey))).containsExactly(initialProjection[0]); + assertThat(admin.get(ascii(accountKey))).containsExactly(accountBeforeIssuerRegression); + assertThat(admin.get(ascii(accountKey))).containsExactly(initialProjection[1]); + + byte[][] equalIssuerConflict = + projectionPair(accountId, 7L, 7L, "issuer-conflict", "account-base"); + int equalIssuerConflictConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, equalIssuerConflict[0], equalIssuerConflict[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(equalIssuerConflictConnection)) + .doesNotContain("dispatch", "get"); + assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + + byte[][] equalAccountConflict = + projectionPair(accountId, 7L, 7L, "issuer-base", "account-conflict"); + int equalAccountConflictConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, equalAccountConflict[0], equalAccountConflict[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(equalAccountConflictConnection)) + .contains("get") + .doesNotContain("dispatch"); + assertProjectionBytes(admin, issuerKey, accountKey, initialProjection); + + byte[][] signedBigintBoundary = + projectionPair( + accountId, Long.MAX_VALUE, Long.MAX_VALUE, "issuer-bigint-max", "account-bigint-max"); + assertThat(new String(signedBigintBoundary[0], StandardCharsets.UTF_8)) + .contains("\"issuerAuthGeneration\":\"9223372036854775807\""); + assertThat(new String(signedBigintBoundary[1], StandardCharsets.UTF_8)) + .contains("\"accountAuthorityGeneration\":\"9223372036854775807\"") + .contains("\"outboxSequence\":\"9223372036854775806\""); + int boundaryConnection = writerProvider.openedConnections(); + assertThat( + redis.publishAuthorityProjections( + accountId, signedBigintBoundary[0], signedBigintBoundary[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(writerProvider.trace(boundaryConnection)) + .containsSubsequence( + "aclWhoami", "scriptLoad", "evalsha", "evalsha", "dispatch", "get", "get", "close"); + assertProjectionBytes(admin, issuerKey, accountKey, signedBigintBoundary); + + byte[][] belowSignedBigintBoundary = + projectionPair( + accountId, + Long.MAX_VALUE - 1L, + Long.MAX_VALUE - 1L, + "issuer-below-max", + "account-below-max"); + int boundaryRegressionConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishAuthorityProjections( + accountId, belowSignedBigintBoundary[0], belowSignedBigintBoundary[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.trace(boundaryRegressionConnection)) + .doesNotContain("dispatch", "get"); + assertProjectionBytes(admin, issuerKey, accountKey, signedBigintBoundary); + + TrackedProvider wrongRoleProvider = new TrackedProvider(fixtureAdmin); + AccountGameplayDelegationRedisClient wrongRoleClient = redisClient(wrongRoleProvider); + int wrongRoleConnection = wrongRoleProvider.openedConnections(); + assertThatThrownBy( + () -> + wrongRoleClient.publishAuthorityProjections( + accountId, signedBigintBoundary[0], signedBigintBoundary[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(wrongRoleProvider.trace(wrongRoleConnection)) + .containsExactly("aclWhoami", "close"); + assertProjectionBytes(admin, issuerKey, accountKey, signedBigintBoundary); + + // Transport/script proof only: these pure event fixtures are not SQL currentness proof. + UUID selectedTenant = UUID.randomUUID(); + String tenantKey = "session:auth:generation:tenant:" + selectedTenant; + String memberKey = "session:auth:generation:membership:" + accountId + ":" + selectedTenant; + assertThat(admin.get(ascii(tenantKey))).isNull(); + assertThat(admin.get(ascii(memberKey))).isNull(); + ownedKeys.add(tenantKey); + ownedKeys.add(memberKey); + byte[][] selected = + selectedProjectionFixture(signedBigintBoundary, accountId, selectedTenant); + int selectedConnection = writerProvider.openedConnections(); + assertThat(redis.publishSelectedAuthorityProjections(accountId, selectedTenant, selected)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat( + writerProvider.trace(selectedConnection).stream().filter("evalsha"::equals).count()) + .isEqualTo(4L); + assertThat( + writerProvider.trace(selectedConnection).stream().filter("dispatch"::equals).count()) + .isEqualTo(1L); + assertThat(admin.get(ascii(tenantKey))).containsExactly(selected[2]); + assertThat(admin.get(ascii(memberKey))).containsExactly(selected[3]); + assertThat(admin.pttl(ascii(tenantKey))).isEqualTo(-1L); + assertThat(admin.pttl(ascii(memberKey))).isEqualTo(-1L); + assertThat(redis.publishSelectedAuthorityProjections(accountId, selectedTenant, selected)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertThat( + Arrays.deepEquals( + redis.readSelectedAuthorityProjections(accountId, selectedTenant), selected)) + .isTrue(); + byte[] tenantSequenceTwo = tenantProjectionFixture(selectedTenant, 3L, 3L, 2L); + byte[] membershipSequenceTwo = + membershipProjectionFixture(accountId, selectedTenant, "2", "3", "1"); + int beforeFirstPublicationAboveOne = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, null, membershipSequenceTwo)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(writerProvider.openedConnections()).isEqualTo(beforeFirstPublicationAboveOne); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, + selectedTenant, + false, + selected[3], + membershipProjectionFixture(accountId, selectedTenant, "3", "4", "1"))) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, true, selected[2], tenantSequenceTwo)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, true, selected[2], tenantSequenceTwo)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, selected[3], membershipSequenceTwo)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, selected[3], membershipSequenceTwo)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, null, membershipSequenceTwo)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, + selectedTenant, + false, + selected[3], + membershipProjectionFixture(accountId, selectedTenant, "3", "4", "1"))) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + admin.del(ascii(tenantKey)); + admin.del(ascii(memberKey)); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, true, selected[2], tenantSequenceTwo)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, selected[3], membershipSequenceTwo)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, true, null, selected[2])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, true, selected[2], tenantSequenceTwo)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, null, selected[3])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, selected[3], membershipSequenceTwo)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(admin.get(ascii(tenantKey))).containsExactly(tenantSequenceTwo); + assertThat(admin.get(ascii(memberKey))).containsExactly(membershipSequenceTwo); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, null, selected[3])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, true, null, selected[2])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + byte[][] gap = selected.clone(); + gap[3] = membershipProjectionFixture(accountId, selectedTenant, "3", "4", "1"); + assertThatThrownBy( + () -> redis.publishSelectedAuthorityProjections(accountId, selectedTenant, gap)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(memberKey))).containsExactly(membershipSequenceTwo); + admin.pexpire(ascii(memberKey), 60_000L); + assertThatThrownBy(() -> redis.readSelectedAuthorityProjections(accountId, selectedTenant)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThatThrownBy( + () -> redis.publishSelectedAuthorityProjections(accountId, selectedTenant, selected)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } finally { + if (adminConnection != null) { + RedisCommands admin = adminConnection.sync(); + for (String key : ownedKeys) { + admin.del(ascii(key)); + } + adminConnection.close(); + } + writer.shutdown(java.time.Duration.ZERO, java.time.Duration.ofSeconds(2)); + fixtureAdmin.shutdown(java.time.Duration.ZERO, java.time.Duration.ofSeconds(2)); + } + } + + @Test + void activeTransitionRequiresRealCommittedOwnerReadbackAndPreservesExactExpiry() + throws Exception { + exerciseActiveTransition(); + } + + @Test + void retainedPostgresPagesReplayToRedisWithCapturedHeadLossAndGapRecovery() { + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + StatefulRedisConnection adminConnection = null; + Set ownedKeys = new LinkedHashSet<>(); + try { + TestContext database = newPostgresContext(); + AccountAuthorityOutboxRepository outbox = + new AccountAuthorityOutboxRepository(database.dsl()); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + String stream = "account:auth-authority:v1:membership/" + accountId + "/" + tenantId; + String redisKey = + AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_PREFIX + accountId + ":" + tenantId; + TrackedProvider writerProvider = new TrackedProvider(writer); + AccountGameplayDelegationRedisClient redis = redisClient(writerProvider); + + for (long sequence = 1L; sequence <= 129L; sequence++) { + long requestedSequence = sequence; + String requestId = "member-request-" + requestedSequence; + inTransaction( + database, + () -> + outbox.append( + stream, + requestId, + actualSequence -> { + if (actualSequence != requestedSequence) { + throw new IllegalStateException("Unexpected outbox fixture sequence"); + } + var event = membershipOutboxEventFixture(accountId, tenantId, actualSequence); + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + })); + } + AccountAuthorityOutboxRepository.Checkpoint capturedHead = + inTransaction(database, () -> outbox.readCheckpoint(stream).orElseThrow()); + assertThat(capturedHead.outboxSequence()).isEqualTo(129L); + inTransaction( + database, + () -> + outbox.append( + stream, + "member-request-130", + actualSequence -> { + var event = membershipOutboxEventFixture(accountId, tenantId, actualSequence); + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + })); + + List firstPage = + inTransaction( + database, () -> outbox.findEventPage(stream, 0L, capturedHead.outboxSequence())); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(firstPage).hasSize(AccountAuthorityOutboxRepository.MAX_EVENT_HISTORY_PAGE_SIZE); + assertThat(firstPage.getFirst().outboxSequence()).isEqualTo(1L); + assertThat(firstPage.getLast().outboxSequence()).isEqualTo(128L); + List secondPage = + inTransaction( + database, + () -> + outbox.findEventPage( + stream, firstPage.getLast().outboxSequence(), capturedHead.outboxSequence())); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(secondPage).hasSize(1); + assertThat(secondPage.getFirst().outboxSequence()).isEqualTo(129L); + assertThat( + inTransaction( + database, + () -> + outbox.findEventPage( + stream, capturedHead.outboxSequence(), capturedHead.outboxSequence()))) + .isEmpty(); + assertThat( + inTransaction(database, () -> outbox.readCheckpoint(stream).orElseThrow()) + .outboxSequence()) + .isEqualTo(130L); + + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(FIXTURE_ADMIN_IDENTITY); + assertThat(admin.get(ascii(redisKey))).isNull(); + ownedKeys.add(redisKey); + + List firstCandidates = + firstPage.stream() + .map(row -> membershipProjectionFromOutboxRow(row, accountId, tenantId)) + .toList(); + List secondCandidates = + secondPage.stream() + .map(row -> membershipProjectionFromOutboxRow(row, accountId, tenantId)) + .toList(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat( + redis.publishSelectedAuthorityEventPage( + accountId, tenantId, false, null, firstCandidates)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(writerProvider.openedConnections()).isEqualTo(1); + assertThat(writerProvider.trace(0).stream().filter("aclWhoami"::equals).count()) + .isEqualTo(1L); + assertThat(writerProvider.trace(0).stream().filter("scriptLoad"::equals).count()) + .isEqualTo(1L); + assertThat(writerProvider.trace(0).stream().filter("evalsha"::equals).count()) + .isEqualTo(128L); + assertThat(writerProvider.dispatchedCommands(0)).containsExactly("WAITAOF"); + assertThat(writerProvider.trace(0).getLast()).isEqualTo("close"); + byte[] beforeFinalBytes = firstCandidates.getLast(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat( + redis.publishSelectedAuthorityEventPage( + accountId, tenantId, false, beforeFinalBytes, secondCandidates)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(writerProvider.openedConnections()).isEqualTo(2); + assertThat(writerProvider.trace(1).stream().filter("evalsha"::equals).count()).isEqualTo(1L); + assertThat(writerProvider.dispatchedCommands(1)).containsExactly("WAITAOF"); + assertThat(writerProvider.trace(1).getLast()).isEqualTo("close"); + byte[] finalBytes = secondCandidates.getLast(); + assertThat(admin.get(ascii(redisKey))).containsExactly(finalBytes); + assertThat(admin.pttl(ascii(redisKey))).isEqualTo(-1L); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, tenantId, false, beforeFinalBytes, finalBytes)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + + // Redis loss is recovered from the real retained SQL prefix. Deliberately presenting the + // sequence-three event with sequence two as its predecessor while Redis holds sequence one + // exercises the server CAS gap fence; replaying two and three then repairs the lost head. + admin.del(ascii(redisKey)); + assertThat(admin.get(ascii(redisKey))).isNull(); + List recoveryPrefix = + inTransaction(database, () -> outbox.findEventPage(stream, 0L, 3L)); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(recoveryPrefix).hasSize(3); + byte[] sequenceOne = + membershipProjectionFromOutboxRow(recoveryPrefix.get(0), accountId, tenantId); + byte[] sequenceTwo = + membershipProjectionFromOutboxRow(recoveryPrefix.get(1), accountId, tenantId); + byte[] sequenceThree = + membershipProjectionFromOutboxRow(recoveryPrefix.get(2), accountId, tenantId); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(redis.publishSelectedAuthorityEvent(accountId, tenantId, false, null, sequenceOne)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThatThrownBy( + () -> + redis.publishSelectedAuthorityEvent( + accountId, tenantId, false, sequenceTwo, sequenceThree)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(redisKey))).containsExactly(sequenceOne); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, tenantId, false, sequenceOne, sequenceTwo)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat( + redis.publishSelectedAuthorityEvent( + accountId, tenantId, false, sequenceTwo, sequenceThree)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(admin.get(ascii(redisKey))).containsExactly(sequenceThree); + } finally { + if (adminConnection != null) { + RedisCommands admin = adminConnection.sync(); + for (String key : ownedKeys) admin.del(ascii(key)); + adminConnection.close(); + } + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + private void exerciseActiveTransition() throws Exception { + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + StatefulRedisConnection adminConnection = null; + Set ownedKeys = new LinkedHashSet<>(); + try { + TestContext database = newPostgresContext(); + DSLContext dsl = database.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + var sourceSnapshot = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + long now = Instant.now().getEpochSecond(); + PendingIntent pending = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + Math.addExact(now, 180L), + new AccountAuthoritySnapshot( + accountId, + sourceSnapshot.issuer().generation(), + sourceSnapshot.issuer().sourceVersion(), + sourceSnapshot.account().generation(), + sourceSnapshot.account().sourceVersion(), + sourceSnapshot.issuanceFence().value(), + sourceSnapshot.issuanceFence().sourceVersion(), + Optional.empty()), + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()); + inTransaction(database, () -> issuance.beginPending(pending)); + + AccountResponseEnvelopeCryptography responseCryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring())); + AccountGameplayDelegationResponseEnvelopeService responseEnvelopes = + new AccountGameplayDelegationResponseEnvelopeService( + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, responseCryptography)); + AccountGameplayDelegationCommitSignerFixture signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + issuance, + responseEnvelopes, + database.manager(), + Clock.systemUTC()); + + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(FIXTURE_ADMIN_IDENTITY); + for (String key : List.of(issuerKey, accountKey)) { + assertThat(admin.get(ascii(key))) + .as("isolated authority projection key is absent before this test owns it") + .isNull(); + } + ownedKeys.add(issuerKey); + ownedKeys.add(accountKey); + + TrackedProvider writerProvider = new TrackedProvider(writer); + AccountGameplayDelegationRedisClient redis = redisClient(writerProvider); + AccountGameplayDelegationAuthorityProjection projection = + org.mockito.Mockito.spy( + new AccountGameplayDelegationAuthorityProjection(sources, database.manager(), redis)); + AccountGameplayDelegationTokenRegistry tokenRegistry = + new AccountGameplayDelegationTokenRegistry( + issuance, database.manager(), redis, Clock.systemUTC(), REGISTRY_BYTES, 30_000L); + AccountGameplayDelegationIssuanceCommitService commitService = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + tokenRegistry, + projection, + issuance, + database.manager(), + Clock.systemUTC()); + + signerFixture.preparePendingCandidate(pending.requestId()); + var durablePending = + inTransaction(database, () -> issuance.readPendingRegistryCandidate(pending.requestId())); + String tokenKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + durablePending.tokenHash(); + assertThat(admin.get(ascii(tokenKey))) + .as("isolated token registry key is absent before this test owns it") + .isNull(); + ownedKeys.add(tokenKey); + var pendingReceipt = tokenRegistry.registerPending(pending.requestId()); + assertThat(pendingReceipt.tokenKey()).isEqualTo(tokenKey); + assertThat(admin.get(ascii(tokenKey))).isNotNull(); + byte[] pendingBytes = admin.get(ascii(tokenKey)); + long originalDeadline = pendingReceipt.absoluteExpiryMillis(); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + + org.mockito.Mockito.doThrow( + new AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException()) + .when(projection) + .publishCurrent(accountId); + assertThatThrownBy(() -> commitService.commitPendingCandidate(pending.requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class) + .hasNoCause(); + var stillPending = + inTransaction( + database, + () -> issuance.readCurrentGameplayLoginReplay(pending.requestId()).orElseThrow()); + assertThat(stillPending.state()) + .isEqualTo(AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState.PENDING); + assertThat(stillPending.identity().operationId()).isEqualTo(pending.operationId()); + assertThat(stillPending.operation().operationId()).isEqualTo(pending.operationId()); + assertThat(stillPending.operation().requestId()).isEqualTo(pending.requestId()); + assertThat(stillPending.operation().candidateBound()).isTrue(); + assertThat(admin.get(ascii(tokenKey))).containsExactly(pendingBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + + org.mockito.Mockito.doCallRealMethod().when(projection).publishCurrent(accountId); + + var committedResult = commitService.commitPendingCandidate(pending.requestId()); + assertThat(committedResult.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + var committedOwner = + inTransaction( + database, () -> issuance.readCurrentCommittedCandidate(pending.requestId())); + assertThat(committedOwner.tokenSha256()).isEqualTo(pendingReceipt.tokenHash()); + assertThat(committedOwner.commitProofSha256()).isEqualTo(committedResult.proofSha256()); + assertThat(committedOwner.canonicalRegistryRecordSha256()) + .isEqualTo(pendingReceipt.canonicalRecordSha256()); + assertThat(committedOwner.toString()) + .isEqualTo("CommittedCandidateVerificationData[redacted]"); + assertThat(committedOwner.registryAbsoluteExpiryMillis()).isEqualTo(originalDeadline); + assertThat(committedOwner.registrationLocalAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committedOwner.registrationReplicaAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committedOwner.registrationOutcome()) + .isEqualTo(PendingRegistrationOutcome.EXACT_RETRY); + assertCurrentOwnerProjection(projection, admin, accountId, sourceSnapshot); + + AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + database.manager(), + Clock.systemUTC()); + + int activationConnection = writerProvider.openedConnections(); + var activeReceipt = committedIssuanceOwner.activateCommittedIssuance(pending.requestId()); + assertThat(activeReceipt.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.ACTIVATED); + assertThat(activeReceipt.operationId()).isEqualTo(pending.operationId()); + assertThat(activeReceipt.requestId()).isEqualTo(pending.requestId()); + assertThat(activeReceipt.accountId()).isEqualTo(accountId); + assertThat(activeReceipt.commitProofSha256()).isEqualTo(committedResult.proofSha256()); + assertThat(activeReceipt.registryVersion()).isEqualTo(2L); + assertThat(activeReceipt.absoluteExpiryMillis()).isEqualTo(originalDeadline); + assertThat(writerProvider.trace(activationConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + assertThat(writerProvider.trace(activationConnection + 1)) + .containsSubsequence( + "aclWhoami", + "scriptLoad", + "get", + "pexpiretime", + "evalsha", + "dispatch", + "get", + "pexpiretime", + "close"); + byte[] activeBytes = admin.get(ascii(tokenKey)); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + assertThat(new String(activeBytes, StandardCharsets.UTF_8)).doesNotContain("eyJ"); + var pendingRecord = + GameSessionAccountDelegationRegistryRecord.decode(pendingBytes, REGISTRY_BYTES); + var activeRecord = + GameSessionAccountDelegationRegistryRecord.decode(activeBytes, REGISTRY_BYTES); + assertThat(pendingRecord.state()).isEqualTo("pending"); + assertThat(activeRecord.state()).isEqualTo("active"); + assertThat(activeRecord.registryVersion()).isEqualTo(2L); + Map unchangedFields = new java.util.LinkedHashMap<>(pendingRecord.fields()); + unchangedFields.put("registryVersion", activeRecord.fields().get("registryVersion")); + unchangedFields.put("state", activeRecord.fields().get("state")); + assertThat(activeRecord.fields()).isEqualTo(unchangedFields); + + int retryConnection = writerProvider.openedConnections(); + AccountGameplayDelegationCommittedIssuanceOwner recoveredOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + database.manager(), + Clock.systemUTC()); + var exactRetry = recoveredOwner.activateCommittedIssuance(pending.requestId()); + assertThat(exactRetry.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.EXACT_RETRY); + assertThat(exactRetry.activeRecordSha256()).isEqualTo(activeReceipt.activeRecordSha256()); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + assertThat(writerProvider.trace(retryConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + assertThat(writerProvider.trace(retryConnection + 1)) + .containsSubsequence( + "aclWhoami", "scriptLoad", "evalsha", "dispatch", "get", "pexpiretime", "close"); + + int connectionsBeforeAuthorityChange = writerProvider.openedConnections(); + BeforeSecondTransactionManager postCheckRaceManager = + new BeforeSecondTransactionManager( + database.manager(), + () -> + inTransaction( + database, + () -> { + AccountRepository accounts = new AccountRepository(dsl, sources); + Account changed = accounts.findByAccountUuid(accountId).orElseThrow(); + changed.setEmailVerified(true); + accounts.save(changed); + return null; + })); + AccountGameplayDelegationCommittedIssuanceOwner postCheckRaceOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + postCheckRaceManager, + Clock.systemUTC()); + assertThatThrownBy(() -> postCheckRaceOwner.activateCommittedIssuance(pending.requestId())) + .isInstanceOf( + AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException.class) + .hasNoCause(); + var changedAccountAuthority = + inTransaction( + database, + () -> + authorities.read( + AccountAuthorityGenerationRepository.AuthorityScope.account(accountId))); + assertThat(changedAccountAuthority.generation()) + .isGreaterThan(sourceSnapshot.account().generation()); + assertThatThrownBy( + () -> + inTransaction( + database, + () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId))) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()) + .isEqualTo(connectionsBeforeAuthorityChange + 2); + assertThat(writerProvider.trace(connectionsBeforeAuthorityChange)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + assertThat(writerProvider.trace(connectionsBeforeAuthorityChange + 1)) + .containsSubsequence( + "aclWhoami", "scriptLoad", "evalsha", "dispatch", "get", "pexpiretime", "close"); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + + // The committed record is not returned as a credential and does not become an authorization + // result merely because the registry transition itself succeeded. + assertThat(activeReceipt.toString()).doesNotContain("eyJ"); + } finally { + if (adminConnection != null) { + RedisCommands admin = adminConnection.sync(); + for (String key : ownedKeys) admin.del(ascii(key)); + adminConnection.close(); + } + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @Test + void physicalCommittedResponseRecoverySurvivesOrdinarySignerRotationAndReturnsSameCredential() + throws Exception { + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + StatefulRedisConnection adminConnection = null; + Set ownedKeys = new LinkedHashSet<>(); + try { + TestContext database = newPostgresContext(); + DSLContext dsl = database.dsl(); + AccountAuthorityGenerationRepository authorities = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + IssuerAccountSourceSnapshot sourceSnapshot = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + long now = Instant.now().getEpochSecond(); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + PendingIntent pending = + new PendingIntent( + UUID.randomUUID(), + requestId, + CALLER_WORKLOAD, + callerContextId, + UUID.randomUUID(), + now, + now, + Math.addExact(now, 180L), + new AccountAuthoritySnapshot( + accountId, + sourceSnapshot.issuer().generation(), + sourceSnapshot.issuer().sourceVersion(), + sourceSnapshot.account().generation(), + sourceSnapshot.account().sourceVersion(), + sourceSnapshot.issuanceFence().value(), + sourceSnapshot.issuanceFence().sourceVersion(), + sourceSnapshot + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))), + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()); + inTransaction(database, () -> issuance.beginPending(pending)); + + AccountResponseEnvelopeCryptography responseCryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring())); + AccountGameplayDelegationResponseEnvelopeRepository responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, issuance, responseCryptography); + AccountGameplayDelegationResponseEnvelopeService responseEnvelopes = + new AccountGameplayDelegationResponseEnvelopeService(responseRepository); + AccountGameplayDelegationCommitSignerFixture signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + issuance, + responseEnvelopes, + database.manager(), + Clock.systemUTC()); + + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(FIXTURE_ADMIN_IDENTITY); + for (String key : List.of(issuerKey, accountKey)) { + assertThat(admin.get(ascii(key))) + .as("isolated Account projection key is absent before this test owns it") + .isNull(); + } + ownedKeys.add(issuerKey); + ownedKeys.add(accountKey); + + TrackedProvider writerProvider = new TrackedProvider(writer); + AccountGameplayDelegationRedisClient redis = redisClient(writerProvider); + AccountGameplayDelegationAuthorityProjection projection = + org.mockito.Mockito.spy( + new AccountGameplayDelegationAuthorityProjection(sources, database.manager(), redis)); + AccountGameplayDelegationTokenRegistry tokenRegistry = + new AccountGameplayDelegationTokenRegistry( + issuance, database.manager(), redis, Clock.systemUTC(), REGISTRY_BYTES, 30_000L); + AccountGameplayDelegationIssuanceCommitService commitService = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + tokenRegistry, + projection, + issuance, + database.manager(), + Clock.systemUTC()); + + signerFixture.preparePendingCandidate(requestId); + var pendingCandidate = + inTransaction(database, () -> issuance.readPendingRegistryCandidate(requestId)); + String tokenKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + pendingCandidate.tokenHash(); + assertThat(admin.get(ascii(tokenKey))) + .as("isolated committed-candidate registry key is absent before this test owns it") + .isNull(); + ownedKeys.add(tokenKey); + + org.mockito.Mockito.doThrow( + new AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException()) + .when(projection) + .publishCurrent(accountId); + assertThatThrownBy(() -> commitService.commitPendingCandidate(requestId)) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class) + .hasNoCause(); + var stillPending = + inTransaction( + database, () -> issuance.readCurrentGameplayLoginReplay(requestId).orElseThrow()); + assertThat(stillPending.state()) + .isEqualTo(AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState.PENDING); + assertThat(stillPending.identity().operationId()).isEqualTo(pending.operationId()); + assertThat(stillPending.operation().operationId()).isEqualTo(pending.operationId()); + assertThat(stillPending.operation().requestId()).isEqualTo(requestId); + assertThat(stillPending.operation().candidateBound()).isTrue(); + byte[] pendingRegistryBytes = admin.get(ascii(tokenKey)); + assertThat(pendingRegistryBytes).containsExactly(pendingCandidate.canonicalRecordBytes()); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode( + pendingRegistryBytes, REGISTRY_BYTES) + .state()) + .isEqualTo("pending"); + long originalRegistryDeadline = + Math.addExact(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L), 30_000L); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + assertThat(admin.get(ascii(issuerKey))).isNull(); + assertThat(admin.get(ascii(accountKey))).isNull(); + + org.mockito.Mockito.doCallRealMethod().when(projection).publishCurrent(accountId); + + var commit = commitService.commitPendingCandidate(requestId); + assertThat(commit.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + var committed = + inTransaction(database, () -> issuance.readCurrentCommittedCandidate(requestId)); + assertThat(committed.identity().operationId()).isEqualTo(pending.operationId()); + assertThat(committed.identity().requestId()).isEqualTo(requestId); + assertThat(committed.identity().accountId()).isEqualTo(accountId); + assertThat(committed.identity().callerWorkload()).isEqualTo(CALLER_WORKLOAD); + assertThat(committed.identity().callerContextId()).isEqualTo(callerContextId); + assertThat(committed.envelopeSha256()).isNotBlank(); + assertThat(committed.tokenSha256()).isEqualTo(pendingCandidate.tokenHash()); + assertCurrentOwnerProjection(projection, admin, accountId, sourceSnapshot); + assertThat(committed.registryAbsoluteExpiryMillis()).isEqualTo(originalRegistryDeadline); + long originalRecoveryExpiry = committed.responseRecoveryExpiryEpochMillis(); + assertThat(originalRecoveryExpiry) + .isEqualTo(Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L)); + pendingRegistryBytes = admin.get(ascii(tokenKey)); + assertThat(pendingRegistryBytes).isNotNull(); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode( + pendingRegistryBytes, REGISTRY_BYTES) + .state()) + .isEqualTo("pending"); + + assertThat(committed.signerGeneration()).isEqualTo("42"); + signerFixture.rotateToNextGenerationRetainingOriginalKey(); + assertThat(signerFixture.currentGeneration()).isEqualTo("43"); + assertThat(signerFixture.currentKid()).isEqualTo("account-key-43"); + assertThat( + inTransaction(database, () -> issuance.readCurrentCommittedCandidate(requestId)) + .signerGeneration()) + .isEqualTo("42"); + + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + database.manager(), + Clock.systemUTC()); + AccountGameplayDelegationResponseRecoveryOwner recoveryOwner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseRepository, committedOwner, database.manager()); + CallerIdentity caller = new CallerIdentity(CALLER_WORKLOAD, callerContextId); + + int connectionsBeforeCallerMismatch = writerProvider.openedConnections(); + assertThatThrownBy( + () -> + recoveryOwner.recoverInitialLoginResponse( + requestId, accountId, new CallerIdentity(CALLER_WORKLOAD, UUID.randomUUID()))) + .isInstanceOf(IdempotencyConflictException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + recoveryOwner.recoverInitialLoginResponse( + requestId, + accountId, + new CallerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", callerContextId))) + .isInstanceOf(IdempotencyConflictException.class) + .hasNoCause(); + assertThatThrownBy( + () -> recoveryOwner.recoverInitialLoginResponse(requestId, UUID.randomUUID(), caller)) + .isInstanceOf(IdempotencyConflictException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()).isEqualTo(connectionsBeforeCallerMismatch); + assertThat(admin.get(ascii(tokenKey))).containsExactly(pendingRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + + signerFixture.withdrawOriginalKeyFromCurrentJwks(); + int connectionsBeforeMissingHistoricalKey = writerProvider.openedConnections(); + assertThatThrownBy( + () -> recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()) + .isEqualTo(connectionsBeforeMissingHistoricalKey); + assertThat(admin.get(ascii(tokenKey))).containsExactly(pendingRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + signerFixture.restoreOriginalKeyInCurrentJwks(); + + int firstRecoveryConnection = writerProvider.openedConnections(); + RecoveredCredential first = + recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller); + assertThat(writerProvider.openedConnections()).isEqualTo(firstRecoveryConnection + 2); + assertThat(writerProvider.trace(firstRecoveryConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + assertThat(writerProvider.trace(firstRecoveryConnection + 1)) + .containsSubsequence( + "aclWhoami", + "scriptLoad", + "get", + "pexpiretime", + "evalsha", + "dispatch", + "get", + "pexpiretime", + "close"); + byte[] activeRegistryBytes = admin.get(ascii(tokenKey)); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode(activeRegistryBytes, REGISTRY_BYTES) + .state()) + .isEqualTo("active"); + assertThat(first.accountId()).isEqualTo(accountId); + assertThat(first.tokenJti()).isEqualTo(pending.tokenJti()); + assertThat(first.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(first.tokenSha256()).isEqualTo(committed.tokenSha256()); + assertThat(first.expiresAtEpochSecond()).isEqualTo(pending.expiresAtEpochSecond()); + assertThat(first.toString()).isEqualTo("RecoveredCredential[secret,redacted]"); + var currentCandidate = + committedOwner.requireCurrentActiveCommittedCandidateByJti(pending.tokenJti()); + assertThat(currentCandidate.tokenSha256()).isEqualTo(committed.tokenSha256()); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + + signerFixture.withdrawOriginalKeyFromCurrentJwks(); + int connectionsBeforeCurrentnessMissingHistoricalKey = writerProvider.openedConnections(); + assertThatThrownBy( + () -> committedOwner.requireCurrentActiveCommittedCandidateByJti(pending.tokenJti())) + .isInstanceOf( + AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()) + .isEqualTo(connectionsBeforeCurrentnessMissingHistoricalKey); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + signerFixture.restoreOriginalKeyInCurrentJwks(); + + byte[] originalCredentialBytes = first.compactJwtBytes(); + assertThat(originalCredentialBytes).isNotEmpty(); + String originalCompactJwt = new String(originalCredentialBytes, StandardCharsets.US_ASCII); + String[] originalJwtSegments = originalCompactJwt.split("\\.", -1); + assertThat(originalJwtSegments) + .hasSize(3) + .allSatisfy(segment -> assertThat(segment).isNotEmpty()); + String originalHeader = + new String(Base64.getUrlDecoder().decode(originalJwtSegments[0]), StandardCharsets.UTF_8); + assertThat(originalHeader).contains("\"kid\":\"account-key-42\""); + + int retryConnection = writerProvider.openedConnections(); + RecoveredCredential exactRetry = + recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller); + assertThat(writerProvider.openedConnections()).isEqualTo(retryConnection + 2); + assertThat(Arrays.equals(exactRetry.compactJwtBytes(), originalCredentialBytes)).isTrue(); + assertThat(exactRetry.tokenSha256()).isEqualTo(first.tokenSha256()); + assertThat(exactRetry.expiresAtEpochSecond()).isEqualTo(first.expiresAtEpochSecond()); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + + var committedAfterRetry = + inTransaction(database, () -> issuance.readCurrentCommittedCandidate(requestId)); + assertThat(committedAfterRetry.commitProofSha256()).isEqualTo(committed.commitProofSha256()); + assertThat(committedAfterRetry.tokenSha256()).isEqualTo(committed.tokenSha256()); + assertThat(committedAfterRetry.signerGeneration()).isEqualTo(committed.signerGeneration()); + assertThat(committedAfterRetry.envelopeSha256()).isEqualTo(committed.envelopeSha256()); + assertThat(signerFixture.currentGeneration()).isEqualTo("43"); + assertThat(signerFixture.currentKid()).isEqualTo("account-key-43"); + assertThat(committedAfterRetry.responseRecoveryExpiryEpochMillis()) + .isEqualTo(originalRecoveryExpiry); + assertThat(committedAfterRetry.registryAbsoluteExpiryMillis()) + .isEqualTo(originalRegistryDeadline); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS envelope_count FROM " + + "account_gameplay_delegation_response_envelopes WHERE request_id = ?", + requestId), + "response envelope count query must return a row") + .get("envelope_count", Long.class)) + .isEqualTo(1L); + byte[] storedEnvelope = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT envelope_bytes FROM account_gameplay_delegation_response_envelopes " + + "WHERE request_id = ?", + requestId), + "stored response envelope query must return a row") + .get("envelope_bytes", byte[].class); + assertThat(containsSequence(storedEnvelope, originalCredentialBytes)).isFalse(); + assertThat(committedAfterRetry.toString()).doesNotContain("eyJ"); + + byte[] changedRegistryBytes = activeRegistryBytes.clone(); + changedRegistryBytes[0] = (byte) 'x'; + admin.set(ascii(tokenKey), changedRegistryBytes); + admin.pexpireat(ascii(tokenKey), originalRegistryDeadline); + assertThat(admin.get(ascii(tokenKey))).containsExactly(changedRegistryBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalRegistryDeadline); + int changedRegistryConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()).isEqualTo(changedRegistryConnection + 1); + assertThat(writerProvider.trace(changedRegistryConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + + admin.del(ascii(tokenKey)); + assertThat(admin.get(ascii(tokenKey))).isNull(); + int missingRegistryConnection = writerProvider.openedConnections(); + assertThatThrownBy( + () -> recoveryOwner.recoverInitialLoginResponse(requestId, accountId, caller)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + assertThat(writerProvider.openedConnections()).isEqualTo(missingRegistryConnection + 1); + assertThat(writerProvider.trace(missingRegistryConnection)) + .containsSubsequence("aclWhoami", "get", "pexpiretime", "close"); + } finally { + if (adminConnection != null) { + RedisCommands admin = adminConnection.sync(); + for (String key : ownedKeys) admin.del(ascii(key)); + adminConnection.close(); + } + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + private static RedisClient redisClient(RedisURI uri) { + RedisClient client = RedisClient.create(uri); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private static RedisClient redisClient(String host, int port, String username, String password) { + RedisURI.Builder uri = RedisURI.Builder.redis(host, port); + if (username != null) uri.withAuthentication(username, password); + RedisURI redisUri = uri.build(); + redisUri.setTimeout(Duration.ofSeconds(5)); + return redisClient(redisUri); + } + + private static RedisURI authenticatedUri(int port, String username, String password) { + RedisURI uri = + RedisURI.Builder.redis("127.0.0.1", port).withAuthentication(username, password).build(); + uri.setTimeout(Duration.ofSeconds(5)); + return uri; + } + + private static void configureAccountUser(RedisCommands commands) { + commands.aclSetuser( + ACCOUNT_IDENTITY, + new AclSetuserArgs() + .reset() + .on() + .addPassword(ACCOUNT_PASSWORD) + .keyPattern("session:auth:token:*") + .keyPattern("session:auth:generation:issuer:*") + .keyPattern("session:auth:generation:account:*") + .keyPattern("session:auth:generation:tenant:*") + .keyPattern("session:auth:generation:membership:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRETIME) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.TYPE)); + commands.dispatch( + TestAclSetuser.INSTANCE, + new StatusOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add(ACCOUNT_IDENTITY) + .add("+waitaof")); + } + + private static void configureFixtureAdmin(RedisCommands commands) { + commands.aclSetuser( + FIXTURE_ADMIN_IDENTITY, + new AclSetuserArgs() + .reset() + .on() + .addPassword(FIXTURE_ADMIN_PASSWORD) + .keyPattern("*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.DEL) + .addCommand(CommandType.PEXPIRE) + .addCommand(CommandType.PEXPIREAT) + .addCommand(CommandType.PEXPIRETIME) + .addCommand(CommandType.PTTL)); + } + + private static void awaitLocalAndReplicaAof(RedisCommands commands) + throws InterruptedException { + byte[] probeKey = ascii("test-only:account-gameplay-delegation-aof-probe:" + UUID.randomUUID()); + commands.set(probeKey, ascii("test-only-replication-probe")); + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + try { + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + TestWaitAof.INSTANCE, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add(1).add(1).add(500)); + if (hasAofCounts(counts, 1, 1)) return; + Thread.sleep(50); + } + throw new IllegalStateException("Test Coordination Redis replica did not acknowledge AOF"); + } finally { + commands.del(List.of(probeKey).toArray(byte[][]::new)); + } + } + + private static boolean hasAofCounts(List counts, long local, long replicas) { + return counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long observedLocal + && observedLocal >= local + && counts.get(1) instanceof Long observedReplicas + && observedReplicas >= replicas; + } + + private enum TestWaitAof implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private enum TestAclSetuser implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "ACL".getBytes(StandardCharsets.US_ASCII); + } + } + + /** + * Real Account/Redis component composition; external workload and Game Design origins are + * stipulated. + */ + /** Pure sealed transport fixtures, deliberately not SQL source/currentness evidence. */ + private static byte[][] selectedProjectionFixture(byte[][] initial, UUID account, UUID tenant) { + UUID creation = UUID.fromString("72a18e29-57c0-48be-a9e7-bd7b681d7720"); + UUID operation = UUID.fromString("a750fb1f-3e5d-40e6-b51e-160ef64d24ec"); + String digest = "sha256:" + "a".repeat(64); + var source = + new net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( + 1, + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW", + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.evidenceDigest( + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW")); + var request = + new DemoTenantEntitlementRequest( + UUID.fromString("15aad6f4-3c5b-4cd9-b1b9-654e6d9bc51a"), + tenant, + creation, + digest, + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(1L, 1L, 1L)); + var billing = DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billing); + return new byte[][] { + initial[0], + initial[1], + selectedProjectionBytes( + Map.of( + "schemaVersion", AccountSelectedGameplayAuthorityProjection.TENANT_SCHEMA, + "tenantId", event.tenantId().toString(), + "tenantAuthorityGeneration", Long.toString(event.tenantAuthorityGeneration()), + "sourceVersion", Long.toString(event.tenantAuthoritySourceVersion()), + "outboxStreamKey", event.outboxStreamKey(), + "outboxSequence", Long.toString(event.outboxSequence()), + "sourceEvent", new String(event.payload(), StandardCharsets.UTF_8)), + null, + tenant), + membershipProjectionFixture(account, tenant, "1", "2", "1") + }; + } + + private static net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .MembershipEvent + membershipOutboxEventFixture(UUID account, UUID tenant, long sequence) { + String sequenceText = Long.toString(sequence); + return net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .SCHEMA_VERSION), + Map.entry( + "eventType", + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .EVENT_TYPE), + Map.entry("eventId", "member-event-" + sequenceText), + Map.entry("requestId", "member-request-" + sequenceText), + Map.entry( + "outboxStreamKey", + "account:auth-authority:v1:membership/" + account + "/" + tenant), + Map.entry("outboxSequence", sequenceText), + Map.entry("sourceScope", "membership/" + account + "/" + tenant), + Map.entry("accountId", account.toString()), + Map.entry("tenantId", tenant.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(tenant.toString(), Long.toString(sequence + 1L))), + Map.entry("membershipAuthorityGeneration", "1"), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), "1"), + "privateRealmGrantVersions", + List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", List.of("player")), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + } + + private static byte[] membershipProjectionFromOutboxRow( + AccountAuthorityOutboxRepository.Event row, UUID account, UUID tenant) { + var event = + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.verify( + new String(row.payload(), StandardCharsets.UTF_8)); + long sequence = Long.parseLong(event.outboxSequence()); + if (!row.outboxStreamKey().equals(event.outboxStreamKey()) + || row.outboxSequence() != sequence + || !row.requestId().equals(event.requestId()) + || !row.eventId().equals(event.eventId()) + || !row.eventDigest().equals(event.eventDigest()) + || !account.toString().equals(event.accountId()) + || !tenant.toString().equals(event.tenantId()) + || !Arrays.equals(row.payload(), event.canonicalJsonUtf8())) { + throw new IllegalStateException("PostgreSQL retained membership row contradicts its event"); + } + return selectedProjectionBytes( + Map.of( + "schemaVersion", AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_SCHEMA, + "accountId", event.accountId(), + "tenantId", event.tenantId(), + "membershipAuthorityGeneration", event.membershipAuthorityGeneration(), + "membershipVersion", event.membershipVersion().get(event.tenantId()), + "sourceVersion", event.membershipAuthorityGeneration(), + "outboxStreamKey", event.outboxStreamKey(), + "outboxSequence", event.outboxSequence(), + "sourceEvent", event.canonicalJson()), + account, + tenant); + } + + private static byte[] membershipProjectionFixture( + UUID account, UUID tenant, String sequence, String version, String generation) { + var event = + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .SCHEMA_VERSION), + Map.entry( + "eventType", + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .EVENT_TYPE), + Map.entry("eventId", "member-event-" + sequence), + Map.entry("requestId", "member-request-" + sequence), + Map.entry( + "outboxStreamKey", + "account:auth-authority:v1:membership/" + account + "/" + tenant), + Map.entry("outboxSequence", sequence), + Map.entry("sourceScope", "membership/" + account + "/" + tenant), + Map.entry("accountId", account.toString()), + Map.entry("tenantId", tenant.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(tenant.toString(), version)), + Map.entry("membershipAuthorityGeneration", generation), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), generation), + "privateRealmGrantVersions", + List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", List.of("player")), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + return selectedProjectionBytes( + Map.of( + "schemaVersion", AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_SCHEMA, + "accountId", event.accountId(), + "tenantId", event.tenantId(), + "membershipAuthorityGeneration", event.membershipAuthorityGeneration(), + "membershipVersion", event.membershipVersion().get(event.tenantId()), + "sourceVersion", "1", + "outboxStreamKey", event.outboxStreamKey(), + "outboxSequence", event.outboxSequence(), + "sourceEvent", event.canonicalJson()), + account, + tenant); + } + + private static byte[] tenantProjectionFixture( + UUID tenant, long generation, long sourceVersion, long outboxSequence) { + UUID creation = UUID.fromString("72a18e29-57c0-48be-a9e7-bd7b681d7720"); + UUID operation = UUID.fromString("a750fb1f-3e5d-40e6-b51e-160ef64d24ec"); + String digest = "sha256:" + "a".repeat(64); + var source = + new net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( + 1, + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW", + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.evidenceDigest( + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW")); + UUID requestId = + UUID.nameUUIDFromBytes( + ("tenant-authority-request-" + outboxSequence).getBytes(StandardCharsets.UTF_8)); + var request = + new DemoTenantEntitlementRequest( + requestId, + tenant, + creation, + digest, + outboxSequence == 1L ? null : outboxSequence - 1L, + outboxSequence == 1L ? null : generation - 1L, + outboxSequence == 1L ? null : sourceVersion - 1L, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(1L, 1L, 1L)); + var billing = + DemoTenantEntitlementEventV1Codec.seal( + request, source, outboxSequence, generation, sourceVersion, outboxSequence); + var event = + TenantAuthorityEventV1Codec.seal( + request, source, generation, sourceVersion, outboxSequence, billing); + return selectedProjectionBytes( + Map.of( + "schemaVersion", AccountSelectedGameplayAuthorityProjection.TENANT_SCHEMA, + "tenantId", tenant.toString(), + "tenantAuthorityGeneration", Long.toString(event.tenantAuthorityGeneration()), + "sourceVersion", Long.toString(event.tenantAuthoritySourceVersion()), + "outboxStreamKey", event.outboxStreamKey(), + "outboxSequence", Long.toString(event.outboxSequence()), + "sourceEvent", new String(event.payload(), StandardCharsets.UTF_8)), + null, + tenant); + } + + private static byte[] selectedProjectionBytes( + Map fields, UUID account, UUID tenant) { + try { + byte[] canonical = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields)); + return AccountSelectedGameplayAuthorityProjection.decode(canonical, account, tenant) + .canonicalBytes(); + } catch (Exception malformedFixture) { + throw new IllegalStateException( + "Invalid sealed selected projection fixture", malformedFixture); + } + } + + private TestContext newPostgresContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + assertThat(schema.length()).isLessThanOrEqualTo(63); + ownedPostgresSchema = schema; + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + dsl.configuration() + .setAppending( + new DefaultExecuteListenerProvider( + ExecuteListener.onException( + context -> { + java.sql.SQLException sqlException = context.sqlException(); + if (sqlException == null) return; + String exceptionClass = sqlException.getClass().getSimpleName(); + if (!exceptionClass.matches("[A-Za-z0-9_$]+")) { + exceptionClass = "SQLException"; + } + String sqlState = sqlException.getSQLState(); + if (sqlState == null || !sqlState.matches("[A-Z0-9]{5}")) { + sqlState = "unknown"; + } + String constraint = "unknown"; + if (sqlException instanceof PSQLException postgresException) { + var serverError = postgresException.getServerErrorMessage(); + String candidateConstraint = + serverError == null ? null : serverError.getConstraint(); + if (candidateConstraint != null + && candidateConstraint.matches("[a-z][a-z0-9_]{0,62}")) { + constraint = candidateConstraint; + } + } + throw new AssertionError( + "Physical Account PostgreSQL failure: exceptionClass=" + + exceptionClass + + "; sqlState=" + + sqlState + + "; constraint=" + + constraint); + }))); + DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); + return new TestContext(dsl, manager, new TransactionTemplate(manager)); + } + + private static UUID createFreshAccount( + TestContext context, AccountAuthoritySourceEvidenceRepository sources) { + Account account = new Account(); + account.setUsername("game-session-" + UUID.randomUUID().toString().replace("-", "")); + account.setEmail("game-session-" + UUID.randomUUID() + "@example.test"); + account.setPasswordHash("integration-test-hash"); + account.setRole("player"); + return inTransaction( + context, + () -> { + sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); + }); + } + + private String writeResponseKeyring() throws Exception { + Path root = temporaryDirectory.resolve("response-keyring-" + UUID.randomUUID()); + Files.createDirectories(root); + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) key[index] = (byte) (index + 1); + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", + StandardCharsets.US_ASCII); + return root.toString(); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static void assertCurrentOwnerProjection( + AccountGameplayDelegationAuthorityProjection projection, + RedisCommands admin, + UUID accountId, + IssuerAccountSourceSnapshot ownerSnapshot) { + byte[][] expected = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(ownerSnapshot); + var expectedIssuer = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + expected[0], "issuer", ACCOUNT_ISSUER); + var expectedAccount = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + expected[1], "account", accountId.toString()); + var observation = projection.observeCurrent(accountId); + assertThat(observation.issuerGeneration()).isEqualTo(ownerSnapshot.issuer().generation()); + assertThat(observation.accountGeneration()).isEqualTo(ownerSnapshot.account().generation()); + assertThat(observation.issuerDigest()).isEqualTo(expectedIssuer.digest()); + assertThat(observation.accountDigest()).isEqualTo(expectedAccount.digest()); + assertThat( + admin.get( + ascii( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + ACCOUNT_ISSUER))) + .containsExactly(expected[0]); + assertThat( + admin.get( + ascii(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId))) + .containsExactly(expected[1]); + } + + private static AccountGameplayDelegationRedisClient redisClient( + AccountCoordinationPinnedConnectionProvider provider) { + return redisClient(provider, new AcknowledgementRequirements(1, 1, 5_000)); + } + + private static AccountGameplayDelegationRedisClient redisClient( + AccountCoordinationPinnedConnectionProvider provider, + AcknowledgementRequirements acknowledgements) { + return new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled( + AccountGameplayDelegationRedisIntegrationTest.class.getClassLoader()), + acknowledgements, + Clock.systemUTC(), + REGISTRY_BYTES, + AccountGameplayDelegationRedisIntegrationTest.class.getClassLoader()); + } + + private static RedisURI requireLoopbackUri(String raw, String expectedUsername) { + final URI parsed; + try { + parsed = URI.create(raw); + } catch (RuntimeException rejected) { + throw new IllegalArgumentException("Redis integration fixture URI is malformed"); + } + String userInfo = parsed.getRawUserInfo(); + String username = userInfo == null ? null : userInfo.split(":", 2)[0]; + String path = parsed.getPath(); + if (!"redis".equals(parsed.getScheme()) + || !"127.0.0.1".equals(parsed.getHost()) + || parsed.getPort() <= 0 + || (path != null && !path.isEmpty() && !"/0".equals(path)) + || parsed.getRawQuery() != null + || parsed.getRawFragment() != null + || !expectedUsername.equals(username)) { + throw new IllegalArgumentException( + "Redis integration fixture must be an exact loopback role URI"); + } + try { + RedisURI redisUri = RedisURI.create(raw); + redisUri.setTimeout(Duration.ofSeconds(5)); + return redisUri; + } catch (RuntimeException rejected) { + throw new IllegalArgumentException("Redis integration fixture URI is malformed"); + } + } + + private static void assertSingleConnectionTrace( + TrackedProvider provider, int expectedConnectionIndex, String... expectedSequence) { + assertThat(provider.openedConnections()).isEqualTo(expectedConnectionIndex + 1); + assertThat(provider.trace(expectedConnectionIndex)).containsSubsequence(expectedSequence); + } + + private static void assertProjectionBytes( + RedisCommands admin, String issuerKey, String accountKey, byte[][] expected) { + assertThat(admin.get(ascii(issuerKey))).containsExactly(expected[0]); + assertThat(admin.get(ascii(accountKey))).containsExactly(expected[1]); + } + + private static byte[][] projectionPair( + UUID accountId, + long issuerGeneration, + long accountGeneration, + String issuerEventMarker, + String accountEventMarker) { + String issuerStream = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + String accountStream = "account:auth-authority:v1:account/" + accountId; + String event = null; + if (accountGeneration > 1) { + String generation = Long.toString(accountGeneration); + String sequence = Long.toString(accountGeneration - 1); + UUID markerId = UUID.nameUUIDFromBytes(accountEventMarker.getBytes(StandardCharsets.UTF_8)); + String request = + new UUID( + (markerId.getMostSignificantBits() & ~0xf000L) | 0x4000L, + (markerId.getLeastSignificantBits() & 0x3fffffffffffffffL) | 0x8000000000000000L) + .toString(); + event = + AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + request), + Map.entry("requestId", request), + Map.entry("accountId", accountId.toString()), + Map.entry("sourceScope", "account/" + accountId), + Map.entry("outboxStreamKey", accountStream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", generation), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + accountStream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))) + .canonicalJson(); + } + Optional issuerSourceEvent = + issuerGeneration == 1 + ? Optional.empty() + : Optional.of( + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + "event-" + issuerEventMarker, + "event-" + issuerEventMarker, + issuerStream, + Long.toString(issuerGeneration - 1), + GameSessionAccountDelegationProfile.ISSUER, + Long.toString(issuerGeneration), + Long.toString(issuerGeneration), + "ISSUER_SECURITY_CHANGE"))); + var canonicalIssuer = + new net.firedevops.firemud.accountservice.service.IssuerGenerationProjection( + GameSessionAccountDelegationProfile.ISSUER, + Long.toString(issuerGeneration), + Long.toString(issuerGeneration), + issuerStream, + Long.toString(issuerGeneration - 1), + issuerSourceEvent.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::eventId), + issuerSourceEvent.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::eventDigest), + issuerSourceEvent.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::canonicalJson)); + return new byte[][] { + canonicalIssuer.toJson().getBytes(StandardCharsets.UTF_8), + new AccountGenerationProjection( + accountId.toString(), + Long.toString(accountGeneration), + Long.toString(accountGeneration), + accountStream, + Long.toString(accountGeneration - 1), + Optional.ofNullable(event)) + .toJson() + .getBytes(StandardCharsets.UTF_8) + }; + } + + private static PendingFixture pendingFixture(UUID accountId, UUID tenantId) throws Exception { + long issuedAt = Instant.now().getEpochSecond(); + long expiresAt = Math.addExact(issuedAt, 180L); + UUID tokenJti = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + String compactToken = compactToken(accountId, tokenJti, issuedAt, expiresAt, tenantId); + AccountAuthoritySnapshot snapshot = authoritySnapshot(accountId); + GameSessionAccountDelegationRegistryRecord record = + tenantId == null + ? GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compactToken, + "5", + new IssuanceBinding( + operationId.toString(), + requestId.toString(), + "a".repeat(64), + accountId.toString()), + snapshot, + new EvidenceBundleReference("1", "7", "6", "12345678", "d".repeat(64)), + issuedAt, + REGISTRY_BYTES) + : null; + if (tenantId != null) { + record = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( + compactToken, + "5", + new IssuanceBinding( + operationId.toString(), + requestId.toString(), + "a".repeat(64), + accountId.toString()), + snapshot, + new EvidenceBundleReference("1", "7", "6", "12345678", "d".repeat(64)), + tenantId.toString(), + boundTuple(accountId, tenantId), + Map.of(tenantId.toString(), "2"), + issuedAt, + REGISTRY_BYTES); + } + long absoluteExpiryMillis = Math.addExact(Math.multiplyExact(expiresAt, 1_000L), 30_000L); + return new PendingFixture( + accountId, + tokenJti, + operationId, + requestId, + issuedAt, + expiresAt, + compactToken, + record, + record.toCanonicalJsonBytes(REGISTRY_BYTES), + absoluteExpiryMillis); + } + + private static byte[] pendingRecordBytes( + String compactToken, + UUID accountId, + long issuedAt, + long expiresAt, + UUID operationId, + UUID requestId, + String requestDigest) { + return GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compactToken, + "5", + new IssuanceBinding( + operationId.toString(), requestId.toString(), requestDigest, accountId.toString()), + authoritySnapshot(accountId), + new EvidenceBundleReference("1", "7", "6", "12345678", "d".repeat(64)), + issuedAt, + REGISTRY_BYTES) + .toCanonicalJsonBytes(REGISTRY_BYTES); + } + + private static String compactToken( + UUID accountId, UUID tokenJti, long issuedAt, long expiresAt, UUID tenantId) + throws Exception { + var cutoff = accountCutoff(accountId, 7L); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", accountId.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("jti", tokenJti.toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", issuedAt), + Map.entry("nbf", issuedAt), + Map.entry("exp", expiresAt), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple(7L, 7L, Optional.of(cutoff))), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", "7")); + if (tenantId != null) { + claims = new java.util.LinkedHashMap<>(claims); + claims.put("tenantId", tenantId.toString()); + claims.put("authorityTuple", boundTuple(accountId, tenantId)); + claims.put("membershipVersion", Map.of(tenantId.toString(), "2")); + } + byte[] header = + JSON.writeValueAsBytes(Map.of("alg", "RS256", "kid", "fixture-key", "typ", "JWT")); + byte[] payload = JSON.writeValueAsBytes(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString(header) + + "." + + encoder.encodeToString(payload) + + "." + + encoder.encodeToString("non-authorizing-test-signature".getBytes(StandardCharsets.UTF_8)); + } + + private static Map boundTuple(UUID accountId, UUID tenantId) { + var tuple = + new java.util.LinkedHashMap( + GameSessionAccountDelegationProfile.authorityTuple( + 7L, 7L, Optional.of(accountCutoff(accountId, 7L)))); + tuple.put("tenantAuthorityGeneration", Map.of(tenantId.toString(), "2")); + tuple.put("membershipAuthorityGeneration", Map.of(tenantId.toString(), "1")); + return tuple; + } + + private static AccountAuthoritySnapshot authoritySnapshot(UUID accountId) { + return new AccountAuthoritySnapshot( + accountId, 7L, 7L, 7L, 7L, 7L, 7L, Optional.of(accountCutoff(accountId, 7L))); + } + + private static GameSessionAccountDelegationProfile.AccountSecurityCutoff accountCutoff( + UUID accountId, long generation) { + return new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + Long.toString(generation), + "account:auth-authority:v1:account/" + accountId, + Long.toString(generation - 1L)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static boolean containsSequence(byte[] value, byte[] sequence) { + if (sequence.length == 0 || sequence.length > value.length) return false; + for (int start = 0; start <= value.length - sequence.length; start++) { + if (Arrays.equals(Arrays.copyOfRange(value, start, start + sequence.length), sequence)) { + return true; + } + } + return false; + } + + private record PendingFixture( + UUID accountId, + UUID tokenJti, + UUID operationId, + UUID requestId, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String compactToken, + GameSessionAccountDelegationRegistryRecord record, + byte[] recordBytes, + long absoluteExpiryMillis) {} + + private record TestContext( + DSLContext dsl, PlatformTransactionManager manager, TransactionTemplate transaction) {} + + private static final class BeforeSecondTransactionManager implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private final Runnable beforeSecondTransaction; + private final AtomicInteger transactions = new AtomicInteger(); + + private BeforeSecondTransactionManager( + PlatformTransactionManager delegate, Runnable beforeSecondTransaction) { + this.delegate = delegate; + this.beforeSecondTransaction = beforeSecondTransaction; + } + + @Override + public org.springframework.transaction.TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + if (transactions.incrementAndGet() == 2) beforeSecondTransaction.run(); + return delegate.getTransaction(definition); + } + + @Override + public void commit(org.springframework.transaction.TransactionStatus status) { + delegate.commit(status); + } + + @Override + public void rollback(org.springframework.transaction.TransactionStatus status) { + delegate.rollback(status); + } + } + + private static final class TrackedProvider + implements AccountCoordinationPinnedConnectionProvider { + private final RedisClient client; + private final List> traces = new ArrayList<>(); + private final List> dispatchedCommands = new ArrayList<>(); + + private TrackedProvider(RedisClient client) { + this.client = client; + } + + @Override + public StatefulRedisConnection openPinnedConnection() { + StatefulRedisConnection connection = client.connect(ByteArrayCodec.INSTANCE); + if (!connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) { + connection.close(); + throw new IllegalStateException("Test Redis connection is not pinned"); + } + List trace = new ArrayList<>(); + traces.add(trace); + List dispatches = new ArrayList<>(); + dispatchedCommands.add(dispatches); + return observe(connection, trace, dispatches); + } + + private int openedConnections() { + return traces.size(); + } + + private List trace(int index) { + return List.copyOf(traces.get(index)); + } + + private List dispatchedCommands(int index) { + return List.copyOf(dispatchedCommands.get(index)); + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection observe( + StatefulRedisConnection delegate, + List trace, + List dispatches) { + return (StatefulRedisConnection) + Proxy.newProxyInstance( + StatefulRedisConnection.class.getClassLoader(), + new Class[] {StatefulRedisConnection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("sync") && method.getParameterCount() == 0) { + RedisCommands commands = + (RedisCommands) invoke(delegate, method, arguments); + return Proxy.newProxyInstance( + RedisCommands.class.getClassLoader(), + new Class[] {RedisCommands.class}, + (commandProxy, commandMethod, commandArguments) -> { + String name = commandMethod.getName(); + if (name.equals("dispatch") + && commandArguments != null + && commandArguments[0] + instanceof io.lettuce.core.protocol.ProtocolKeyword keyword) { + dispatches.add(new String(keyword.getBytes(), StandardCharsets.US_ASCII)); + } + if (List.of( + "aclWhoami", + "scriptLoad", + "evalsha", + "dispatch", + "get", + "pexpiretime") + .contains(name)) { + trace.add(name); + } + return invoke(commands, commandMethod, commandArguments); + }); + } + if (method.getName().equals("close")) trace.add("close"); + return invoke(delegate, method, arguments); + }); + } + + private static Object invoke(Object target, Method method, Object[] arguments) + throws Throwable { + try { + return method.invoke(target, arguments); + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java new file mode 100644 index 0000000000..2ff5640e6b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java @@ -0,0 +1,403 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Test; + +class AccountAuthEvidenceBundleTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + + @Test + void encodesAndReadsOnlyTheClosedCanonicalNonTenantProfile() { + AccountAuthEvidenceBundle value = AccountAuthEvidenceBundle.fromOwnerEvaluation(evaluation()); + + assertThat(value).isEqualTo(AccountAuthEvidenceBundle.parseCanonical(value.canonicalBytes())); + assertThat(AccountAuthEvidenceBundle.MAX_CANONICAL_BYTES).isEqualTo(8 * 1024); + assertThat(value.canonicalBytes()).hasSizeLessThanOrEqualTo(8 * 1024); + assertThat(value.canonicalSha256()).matches("[0-9a-f]{64}"); + assertThat(value.toString()).doesNotContain("account-auth-evidence"); + assertThat(value.fields()).containsEntry("schema", AccountAuthEvidenceBundle.SCHEMA); + assertThat(value.fields()).containsEntry("issuanceFence", "1"); + assertThat(((Map) value.fields().get("tokenIdentity")).get("tokenGeneration")) + .isEqualTo("1"); + Map authorityTuple = (Map) value.fields().get("authorityTuple"); + assertThat(authorityTuple.get("issuerAuthGeneration")).isEqualTo("1"); + assertThat(authorityTuple.get("accountAuthorityGeneration")).isEqualTo("1"); + assertThat((Map) value.fields().get("membershipVersion")).isEmpty(); + Map scope = (Map) value.fields().get("scope"); + assertThat(scope.get("kind")).isEqualTo("account"); + assertThat(scope.get("tenantIds")).isEqualTo(List.of()); + } + + @Test + void canonicalEvidenceCarrierHonorsItsProfileLimitWithinTheLargerEnvelopeBound() { + assertThatCode( + () -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[AccountAuthEvidenceBundle.MAX_CANONICAL_BYTES])) + .doesNotThrowAnyException(); + assertThatThrownBy(() -> AccountAuthEvidenceBundle.parseCanonical(new byte[8 * 1024 + 1])) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class) + .hasMessageContaining("byte bound"); + assertThatCode( + () -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[8 * 1024 + 1])) + .doesNotThrowAnyException(); + assertThatCode( + () -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[128 * 1024])) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[128 * 1024 + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("authority evidence bundle bytes"); + } + + @Test + void strictParserRejectsDuplicateTrailingUnknownNullAndNonCanonicalInput() { + byte[] valid = AccountAuthEvidenceBundle.fromOwnerEvaluation(evaluation()).canonicalBytes(); + String text = new String(valid, StandardCharsets.UTF_8); + + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + "{\"schema\":\"first\",\"schema\":\"second\"}" + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + (text + "{}\n").getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace("\"schema\":", "\"unknown\":null,\"schema\":") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace( + "\"audience\":\"account-service\"", + "\"audience\":\"account-service\",\"privateKey\":\"fixture\"") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + (" " + text).getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace(",\"sourceFence\":\"7\"", "").getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void profileRejectsTenantAuthorityAndNonCanonicalCounterRepresentations() { + String text = + new String( + AccountAuthEvidenceBundle.fromOwnerEvaluation(evaluation()).canonicalBytes(), + StandardCharsets.UTF_8); + String withTenantScope = + text.replace("\"tenantIds\":[]", "\"tenantIds\":[\"" + UUID.randomUUID() + "\"]"); + String numericFence = text.replace("\"issuanceFence\":\"1\"", "\"issuanceFence\":1"); + String numericSourceFence = text.replace("\"sourceFence\":\"7\"", "\"sourceFence\":7"); + String numericTokenGeneration = + text.replace("\"tokenGeneration\":\"1\"", "\"tokenGeneration\":1"); + String numericIssuerGeneration = + text.replace("\"issuerAuthGeneration\":\"1\"", "\"issuerAuthGeneration\":1"); + + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + withTenantScope.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + numericSourceFence.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + numericFence.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + numericTokenGeneration.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + numericIssuerGeneration.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void bundleReferenceUsesCanonicalCaptureTransactionAndFenceRanges() { + assertThatCode( + () -> + new BundleReference("1", "18446744073709551615", "9223372036854775807", "12345678")) + .doesNotThrowAnyException(); + assertThatThrownBy(() -> new BundleReference("1", "18446744073709551616", "1", "12345678")) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy(() -> new BundleReference("1", "1", "9223372036854775808", "12345678")) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy(() -> new BundleReference("1", "01", "1", "12345678")) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void checkpointsMustBeExactAndSortedOwnerEvidenceShapes() { + OwnerEvaluation value = evaluation(); + OwnerEvaluation reversed = + new OwnerEvaluation( + value.bundleReference(), + value.snapshotIdentity(), + value.evaluationIdentity(), + value.accountId(), + value.operation(), + value.token(), + value.authorityTuple(), + value.issuanceFence(), + value.authoritySourceVersions(), + value.accountIdentitySource(), + List.of(value.outboxCheckpoints().get(1), value.outboxCheckpoints().get(0))); + + assertThatThrownBy(() -> AccountAuthEvidenceBundle.fromOwnerEvaluation(reversed)) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + assertThatThrownBy( + () -> + new OutboxCheckpoint( + "account:auth-authority:v1:account/" + value.accountId(), + 0L, + "event", + "sha256:" + "a".repeat(64))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void explicitZeroCheckpointIsEncodedWithoutEventIdentityButIsNotSourceProof() { + OwnerEvaluation positive = evaluation(); + String accountStream = "account:auth-authority:v1:account/" + positive.accountId(); + OutboxCheckpoint zeroBaseline = new OutboxCheckpoint(accountStream, 0L, null, null); + OwnerEvaluation zeroShape = + new OwnerEvaluation( + positive.bundleReference(), + positive.snapshotIdentity(), + positive.evaluationIdentity(), + positive.accountId(), + positive.operation(), + positive.token(), + positive.authorityTuple(), + positive.issuanceFence(), + positive.authoritySourceVersions(), + positive.accountIdentitySource(), + List.of(zeroBaseline, positive.outboxCheckpoints().get(1))); + + // These fixtures exercise only closed wire shape; they are not owner rows, event history, or + // proof that Account initialized and exhaustively retained this stream. + AccountAuthEvidenceBundle encoded = AccountAuthEvidenceBundle.fromOwnerEvaluation(zeroShape); + AccountAuthEvidenceBundle decoded = + AccountAuthEvidenceBundle.parseCanonical(encoded.canonicalBytes()); + List checkpoints = (List) decoded.fields().get("outboxCheckpoints"); + Map encodedZero = (Map) checkpoints.get(0); + assertThat(encodedZero.size()).isEqualTo(2); + assertThat(encodedZero.containsKey("sourceEventId")).isFalse(); + assertThat(encodedZero.containsKey("sourceEventDigest")).isFalse(); + assertThat(encodedZero.get("outboxStreamKey")).isEqualTo(accountStream); + assertThat(encodedZero.get("outboxSequence")).isEqualTo("0"); + + String claimedEventAtZero = + new String(encoded.canonicalBytes(), StandardCharsets.UTF_8) + .replace( + "\"outboxSequence\":\"0\"", + "\"outboxSequence\":\"0\",\"sourceEventId\":\"fabricated\"," + + "\"sourceEventDigest\":\"sha256:" + + "a".repeat(64) + + "\""); + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + claimedEventAtZero.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + @Test + void cutoffIsOptionalShapeOnlyAndMustMatchAccountScopeWhenPresent() { + OwnerEvaluation base = evaluation(); + Map tupleWithCutoff = new LinkedHashMap<>(base.authorityTuple()); + tupleWithCutoff.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "1", + "outboxStreamKey", "account:auth-authority:v1:account/" + base.accountId(), + "outboxSequence", "1")); + OwnerEvaluation withCutoff = + new OwnerEvaluation( + base.bundleReference(), + base.snapshotIdentity(), + base.evaluationIdentity(), + base.accountId(), + base.operation(), + base.token(), + tupleWithCutoff, + base.issuanceFence(), + base.authoritySourceVersions(), + base.accountIdentitySource(), + base.outboxCheckpoints()); + + assertThat( + ((Map) + AccountAuthEvidenceBundle.fromOwnerEvaluation(withCutoff) + .fields() + .get("authorityTuple")) + .containsKey("accountSecurityCutoff")) + .isTrue(); + Map mismatchedTuple = new LinkedHashMap<>(base.authorityTuple()); + mismatchedTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "1", + "outboxStreamKey", "account:auth-authority:v1:account/other", + "outboxSequence", "1")); + OwnerEvaluation mismatchedCutoff = + new OwnerEvaluation( + base.bundleReference(), + base.snapshotIdentity(), + base.evaluationIdentity(), + base.accountId(), + base.operation(), + base.token(), + mismatchedTuple, + base.issuanceFence(), + base.authoritySourceVersions(), + base.accountIdentitySource(), + base.outboxCheckpoints()); + assertThatThrownBy(() -> AccountAuthEvidenceBundle.fromOwnerEvaluation(mismatchedCutoff)) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + + Map uncoveredTuple = new LinkedHashMap<>(base.authorityTuple()); + uncoveredTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "1", + "outboxStreamKey", "account:auth-authority:v1:account/" + base.accountId(), + "outboxSequence", "2")); + OwnerEvaluation uncoveredCutoff = + new OwnerEvaluation( + base.bundleReference(), + base.snapshotIdentity(), + base.evaluationIdentity(), + base.accountId(), + base.operation(), + base.token(), + uncoveredTuple, + base.issuanceFence(), + base.authoritySourceVersions(), + base.accountIdentitySource(), + base.outboxCheckpoints()); + assertThatThrownBy(() -> AccountAuthEvidenceBundle.fromOwnerEvaluation(uncoveredCutoff)) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + + private static OwnerEvaluation evaluation() { + UUID accountId = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + String accountStream = "account:auth-authority:v1:account/" + accountId; + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + List checkpoints = + List.of( + new OutboxCheckpoint(accountStream, 1L, "account-event-1", "sha256:" + "a".repeat(64)), + new OutboxCheckpoint(issuerStream, 1L, "issuer-event-1", "sha256:" + "b".repeat(64))); + return new OwnerEvaluation( + new BundleReference("1", "18446744073709551615", "7", "12345678"), + "1".repeat(64), + "2".repeat(64), + accountId, + new OperationIdentity( + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + "3".repeat(64), + WORKLOAD, + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + accountId), + new TokenIdentity( + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), 1L, 100L, 100L, 220L), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 1L, + new AuthoritySourceVersions(1L, 1L, 1L), + new AccountIdentitySource(42L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, 42L), + checkpoints); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java new file mode 100644 index 0000000000..0a23a662b5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java @@ -0,0 +1,183 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +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.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Test; + +class InitialGameplayLoginResultTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CONTEXT_ID = UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID TOKEN_JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final Instant ISSUED_AT = Instant.parse("2027-01-15T12:00:00Z"); + private static final byte[] EXACT_JWT = + "header.payload.signature".getBytes(StandardCharsets.US_ASCII); + + @Test + void projectsExactRecoveredCredentialAndDistinctCanonicalAuthorityEvidence() { + AccountAuthEvidenceBundle bundle = evidenceBundle(); + InitialGameplayLoginResult result = + InitialGameplayLoginResult.fromRecoveredCredential(credential(bundle)); + + assertThat(result.compactJwtBytes()).containsExactly(EXACT_JWT); + assertThat(result.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(result.tokenJti()).isEqualTo(TOKEN_JTI); + assertThat(result.tokenSha256()).isEqualTo("a".repeat(64)); + assertThat(result.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(result.issuedAtEpochSecond()).isEqualTo(ISSUED_AT.getEpochSecond()); + assertThat(result.notBeforeEpochSecond()).isEqualTo(ISSUED_AT.getEpochSecond()); + assertThat(result.expiresAtEpochSecond()) + .isEqualTo( + ISSUED_AT.getEpochSecond() + + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); + assertThat(result.tokenGeneration()).isEqualTo("1"); + assertThat(result.issuanceFence()).isEqualTo("7"); + assertThat(result.requestId()).isEqualTo(REQUEST_ID); + assertThat(result.callerContextId()).isEqualTo(CONTEXT_ID); + + String checkpoints = + new String(result.outboxCheckpointsCanonicalJson(), StandardCharsets.UTF_8); + assertThat(checkpoints) + .contains("account:auth-authority:v1:account/" + ACCOUNT_ID) + .contains("\"outboxSequence\":\"0\"") + .contains("account:auth-authority:v1:issuer/firemud-account-service") + .contains("\"outboxSequence\":\"1\""); + String sourceEvents = + new String(result.outboxSourceEventEvidenceCanonicalJson(), StandardCharsets.UTF_8); + assertThat(sourceEvents) + .contains("issuer-event-1") + .contains("sha256:" + "b".repeat(64)) + .doesNotContain("\"outboxSequence\":\"0\"") + .doesNotContain("account:auth-authority:v1:account/" + ACCOUNT_ID); + assertThat(new String(result.authorityTupleCanonicalJson(), StandardCharsets.UTF_8)) + .contains("accountAuthorityGeneration"); + assertThat(result.toString()).doesNotContain(new String(EXACT_JWT, StandardCharsets.US_ASCII)); + } + + @Test + void credentialAndEvidenceBytesAreDefensiveCopies() { + InitialGameplayLoginResult result = + InitialGameplayLoginResult.fromRecoveredCredential(credential(evidenceBundle())); + byte[] jwt = result.compactJwtBytes(); + byte[] checkpoints = result.outboxCheckpointsCanonicalJson(); + byte[] authority = result.authorityTupleCanonicalJson(); + jwt[0] = 'x'; + checkpoints[0] = 'x'; + authority[0] = 'x'; + + assertThat(result.compactJwtBytes()).containsExactly(EXACT_JWT); + assertThat(result.outboxCheckpointsCanonicalJson()[0]).isNotEqualTo((byte) 'x'); + assertThat(result.authorityTupleCanonicalJson()[0]).isNotEqualTo((byte) 'x'); + } + + @Test + void rejectsRecoveredCredentialThatContradictsStoredEvidence() { + AccountAuthEvidenceBundle bundle = evidenceBundle(); + assertThatThrownBy( + () -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential( + bundle, UUID.randomUUID(), TOKEN_JTI, "a".repeat(64), expectedExpiry()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); + assertThatThrownBy( + () -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential( + bundle, ACCOUNT_ID, UUID.randomUUID(), "a".repeat(64), expectedExpiry()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); + assertThatThrownBy( + () -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential( + bundle, ACCOUNT_ID, TOKEN_JTI, "a".repeat(64), expectedExpiry() + 1L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); + assertThatThrownBy( + () -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential(bundle, ACCOUNT_ID, TOKEN_JTI, "not-a-hash", expectedExpiry()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); + } + + private static RecoveredCredential credential(AccountAuthEvidenceBundle bundle) { + return credential(bundle, ACCOUNT_ID, TOKEN_JTI, "a".repeat(64), expectedExpiry()); + } + + private static RecoveredCredential credential( + AccountAuthEvidenceBundle bundle, + UUID accountId, + UUID tokenJti, + String tokenHash, + long expiresAt) { + RecoveredCredential credential = mock(RecoveredCredential.class); + when(credential.compactJwtBytes()).thenAnswer(invocation -> EXACT_JWT.clone()); + when(credential.accountId()).thenReturn(accountId); + when(credential.tokenJti()).thenReturn(tokenJti); + when(credential.tokenSha256()).thenReturn(tokenHash); + when(credential.profile()).thenReturn(GameSessionAccountDelegationProfile.PROFILE); + when(credential.expiresAtEpochSecond()).thenReturn(expiresAt); + when(credential.authEvidenceBundle()).thenReturn(bundle); + return credential; + } + + private static long expectedExpiry() { + return ISSUED_AT.getEpochSecond() + + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS; + } + + private static AccountAuthEvidenceBundle evidenceBundle() { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new OwnerEvaluation( + new BundleReference("1", "1", "7", "12345678"), + "1".repeat(64), + "2".repeat(64), + ACCOUNT_ID, + new OperationIdentity( + UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"), + REQUEST_ID, + "3".repeat(64), + WORKLOAD, + CONTEXT_ID, + ACCOUNT_ID), + new TokenIdentity( + TOKEN_JTI, + 1L, + ISSUED_AT.getEpochSecond(), + ISSUED_AT.getEpochSecond(), + ISSUED_AT.getEpochSecond() + + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 7L, + new AuthoritySourceVersions(1L, 1L, 1L), + new AccountIdentitySource(42L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, 42L), + List.of( + new OutboxCheckpoint(accountStream, 0L, null, null), + new OutboxCheckpoint( + issuerStream, 1L, "issuer-event-1", "sha256:" + "b".repeat(64))))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java new file mode 100644 index 0000000000..a8e2d5ce02 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java @@ -0,0 +1,159 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.ArgumentMatchers.eq; +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 java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountAuthEvidenceBundleRepositoryTest { + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresWritableAccountTransactionBeforeAnyOwnerRead() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthEvidenceBundleRepository repository = + new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + + assertThatThrownBy(() -> repository.captureAndPersist(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + verifyNoInteractions(dsl, generations, outbox); + } + + @Test + void absentOwnerOperationDeniesWithoutWritingOrAcceptingCallerBundleBytes() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthEvidenceBundleRepository repository = + new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + UUID requestId = UUID.randomUUID(); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(null); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.captureAndPersist(requestId)) + .isInstanceOf(AccountAuthEvidenceBundleRepository.OperationNotFoundException.class); + verify(dsl) + .fetchOne( + contains("FROM account_gameplay_delegation_issuance_operations"), any(Object[].class)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + verifyNoInteractions(generations, outbox); + } + + @Test + void locksAccountAndAuthorityBeforeLockingAndRevalidatingOperation() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthEvidenceBundleRepository repository = + new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + Record preliminary = mock(Record.class); + when(preliminary.get("request_id", UUID.class)).thenReturn(requestId); + when(preliminary.get("operation_id", UUID.class)).thenReturn(operationId); + when(preliminary.get("account_uuid", UUID.class)).thenReturn(accountId); + + Record account = mock(Record.class); + when(account.get("id", Long.class)).thenReturn(1L); + when(account.get("account_uuid", UUID.class)).thenReturn(accountId); + when(account.get("account_uuid_provenance", String.class)) + .thenReturn(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name()); + when(account.get("account_uuid_source_numeric_id", Long.class)).thenReturn(1L); + + Record lockedOperation = mock(Record.class); + when(lockedOperation.get("request_id", UUID.class)).thenReturn(requestId); + when(lockedOperation.get("operation_id", UUID.class)).thenReturn(operationId); + when(lockedOperation.get("account_uuid", UUID.class)).thenReturn(accountId); + when(lockedOperation.get("caller_context_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(lockedOperation.get("token_jti", UUID.class)).thenReturn(UUID.randomUUID()); + when(lockedOperation.get("request_digest", String.class)).thenReturn("a".repeat(64)); + when(lockedOperation.get("caller_workload", String.class)) + .thenReturn("spiffe://firemud/ns/test/sa/game-session-service"); + when(lockedOperation.get("status", String.class)).thenReturn("COMMITTED"); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenReturn(preliminary, account, lockedOperation); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.captureAndPersist(requestId)) + .isInstanceOf(AccountAuthEvidenceBundleRepository.OwnerEvidenceUnavailableException.class); + + var order = inOrder(dsl, generations); + order + .verify(dsl) + .fetchOne( + argThat( + sql -> + sql.contains("SELECT operation_id, request_id, account_uuid") + && sql.contains("FROM account_gameplay_delegation_issuance_operations") + && !sql.contains("FOR UPDATE")), + any(Object[].class)); + order + .verify(dsl) + .fetchOne( + argThat(sql -> sql.contains("FROM accounts") && sql.contains("FOR SHARE")), + any(Object[].class)); + order + .verify(generations) + .readCompositeSnapshot( + eq(GameSessionAccountDelegationProfile.ISSUER), + eq(accountId), + eq(java.util.List.of()), + eq(java.util.List.of())); + order + .verify(dsl) + .fetchOne( + argThat( + sql -> + sql.contains("FROM account_gameplay_delegation_issuance_operations") + && sql.contains("FOR UPDATE")), + any(Object[].class)); + verifyNoInteractions(outbox); + } + + @Test + void storedValueReaderIsNonAuthorizingAndFailsClosedWhenNoReadbackExists() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthEvidenceBundleRepository repository = + new AccountAuthEvidenceBundleRepository( + dsl, + mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthorityOutboxRepository.class)); + UUID operationId = UUID.randomUUID(); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(null); + + assertThatThrownBy(() -> repository.readStoredNonAuthorizingValue(operationId)) + .isInstanceOf(AccountAuthEvidenceBundleRepository.StoredBundleUnavailableException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java new file mode 100644 index 0000000000..165e7d85fc --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java @@ -0,0 +1,910 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingSigningIdentity; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerPreimage; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationIssuanceRepositoryTest { + @Test + void invalidAccountUuidDeniesBeforeOwnerReadOrPendingWrite() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(dsl, sources); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + for (UUID accountId : + new UUID[] { + new UUID(0L, 0L), + UUID.fromString("4cae05e8-7a6b-3b14-9d44-665e3eec450b"), + UUID.fromString("4cae05e8-7a6b-4b14-7d44-665e3eec450b") + }) { + assertThatThrownBy( + () -> + repository.beginPendingForAccount( + UUID.randomUUID(), + accountId, + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A canonical version-4 Account UUID is required"); + } + verifyNoInteractions(dsl, sources); + } + + @Test + void committedProjectionProofRequiresCanonicalAccountBytesNotRecipientFenceSchema() + throws Exception { + var account = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 1L, + 1L, + new IssuanceFence(ACCOUNT_ID, 1L, 1L), + new SourceCheckpoint( + "account:auth-authority:v1:account/" + ACCOUNT_ID, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 42L, + "ACCOUNT_REPOSITORY_INSERT", + 2L, + 2L); + String issuerStream = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + String issuerRequestId = "be305426-4ea8-4f73-a571-4ef89b7ae864"; + var issuerEvent = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new IssuerPreimage( + issuerRequestId, + issuerRequestId, + issuerStream, + "6", + GameSessionAccountDelegationProfile.ISSUER, + "7", + "7", + "SIGNER_COMPROMISE")); + var issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER), + 7L, + 7L, + null, + new SourceCheckpoint( + issuerStream, + 6L, + Optional.of(issuerEvent.eventId()), + Optional.of(issuerEvent.eventDigest())), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 7L, + null); + var storedIssuerEvent = + new AccountAuthorityOutboxRepository.Event( + issuerStream, + issuerRequestId, + 6L, + issuerEvent.eventId(), + issuerEvent.eventDigest(), + issuerEvent.canonicalJsonUtf8()); + var issuerProjection = + IssuerGenerationProjection.fromSource( + new CanonicalIssuerSourceSnapshot(issuer, Optional.of(storedIssuerEvent))); + var accountProjection = + new AccountGenerationProjection( + ACCOUNT_ID.toString(), + "1", + "1", + account.checkpoint().outboxStreamKey(), + "0", + Optional.empty()); + var source = + new IssuerAccountSourceSnapshot( + issuer, account, account.issuanceFence(), accountProjection, issuerProjection); + var pair = + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + var issuerProjectionValue = + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + pair[0], "issuer", GameSessionAccountDelegationProfile.ISSUER); + var canonicalAccount = + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + pair[1], "account", ACCOUNT_ID.toString()); + Method method = + AccountGameplayDelegationIssuanceRepository.class.getDeclaredMethod( + "requireExactProjectionObservation", + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation.class, + IssuerAccountSourceSnapshot.class); + method.setAccessible(true); + method.invoke( + null, + new net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation( + issuerProjectionValue.digest(), canonicalAccount.digest(), 7L, 1L), + source); + assertThatThrownBy( + () -> + method.invoke( + null, + new net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation( + issuerProjectionValue.digest(), "b".repeat(64), 7L, 1L), + source)) + .hasCauseInstanceOf( + AccountGameplayDelegationIssuanceRepository.StaleAuthorityException.class); + } + + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID OPERATION_ID = UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final Instant NOW = Instant.parse("2027-01-15T12:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requestDigestBindsTheExactCallerContextAndImmutableTokenIdentity() { + PendingIntent intent = intent(authoritySnapshot(11L)); + PendingIntent changedCaller = + new PendingIntent( + OPERATION_ID, + REQUEST_ID, + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.fromString("c46b58cf-4204-468b-a499-2de0eb8ce5fc"), + JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + intent.authoritySnapshot(), + AccountGameplayCredentialRequestBindingFixture.binding()); + + assertThat(AccountGameplayDelegationIssuanceRepository.requestDigest(intent)) + .isEqualTo(AccountGameplayDelegationIssuanceRepository.requestDigest(intent)) + .isNotEqualTo(AccountGameplayDelegationIssuanceRepository.requestDigest(changedCaller)); + assertThat(intent.toString()).doesNotContain(ACCOUNT_ID.toString(), JTI.toString()); + } + + @Test + void currentCommittedOwnerReadRequiresWritableAccountTransactionBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(dsl, sources); + + assertThatThrownBy(() -> repository.readCurrentCommittedCandidate(REQUEST_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + + verifyNoInteractions(dsl, sources); + } + + @Test + void currentGameplayLoginReplayRequiresItsOwnerWritableTransaction() throws Exception { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository(dsl, sources); + Method method = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "readCurrentGameplayLoginReplay", UUID.class); + Transactional transaction = method.getAnnotation(Transactional.class); + + assertThat(transaction).isNotNull(); + assertThat(transaction.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(transaction.readOnly()).isFalse(); + assertThatThrownBy(() -> repository.readCurrentGameplayLoginReplay(REQUEST_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + verifyNoInteractions(dsl, sources); + } + + @Test + void currentGameplayLoginReplayRejectsCommittedRowWithoutCanonicalCommitProof() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + IssuerAccountSourceSnapshot current = sources(); + PendingIntent intent = intent(authoritySnapshot(11L)); + Record committedWithoutProof = + operationRecord(intent, AccountGameplayDelegationIssuanceRepository.requestDigest(intent)); + when(committedWithoutProof.get("status", String.class)).thenReturn("COMMITTED"); + when(committedWithoutProof.get("token_hash", String.class)).thenReturn("a".repeat(64)); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenReturn(committedWithoutProof, committedWithoutProof); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(current); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, Clock.fixed(NOW, ZoneOffset.UTC)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.readCurrentGameplayLoginReplay(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.StorageUnavailableException.class); + + verify(sources) + .readCurrentIssuerAccountSources(GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID); + } + + @Test + void committedVerificationDataCanOnlyComeFromTheMandatoryOwnerRead() throws Exception { + Method readMethod = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "readCurrentCommittedCandidate", UUID.class); + Transactional transaction = readMethod.getAnnotation(Transactional.class); + + assertThat(transaction).isNotNull(); + assertThat(transaction.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat( + Arrays.stream( + AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData + .class + .getDeclaredConstructors()) + .allMatch(constructor -> Modifier.isPrivate(constructor.getModifiers()))) + .isTrue(); + } + + @Test + void requestDigestCanonicallyBindsTheApplicableAccountSecurityCutoff() throws Exception { + PendingIntent intent = intent(authoritySnapshot(11L)); + Map tuple = + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff()); + assertThat(tuple).containsKey("accountSecurityCutoff"); + + Map preimage = digestPreimage(intent, tuple); + assertThat(preimage.get("issuanceFence")) + .isEqualTo(Long.toString(intent.authoritySnapshot().issuanceFence())); + assertThat(preimage.get("iat")).isInstanceOf(Number.class); + assertThat(((Map) preimage.get("authorityTuple")).get("issuerAuthGeneration")) + .isEqualTo(Long.toString(intent.authoritySnapshot().issuerGeneration())); + Map tupleWithoutCutoff = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), 1L)); + tupleWithoutCutoff.put( + "accountAuthorityGeneration", intent.authoritySnapshot().accountGeneration()); + Map cutoffOmitted = digestPreimage(intent, tupleWithoutCutoff); + + assertThat(AccountGameplayDelegationIssuanceRepository.requestDigest(intent)) + .isEqualTo(digest(preimage)) + .isNotEqualTo(digest(cutoffOmitted)); + } + + @Test + void staleOrTenantScopedAuthorityCannotCreateDurableIntent() { + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", ACCOUNT_ID)) + .thenReturn(mock(Record.class)); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(sources()); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, Clock.fixed(NOW, ZoneOffset.UTC)); + AccountAuthoritySnapshot stale = authoritySnapshot(10L); + PendingIntent intent = intent(stale); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.beginPending(intent)) + .isInstanceOf(AccountGameplayDelegationIssuanceRepository.StaleAuthorityException.class); + verify(dsl, org.mockito.Mockito.never()) + .execute( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class)); + } + + @Test + void requiresAnOwnerWritableTransactionBeforeAnySqlAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, Clock.fixed(NOW, ZoneOffset.UTC)); + + assertThatThrownBy(() -> repository.beginPending(intent(authoritySnapshot(11L)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + verifyNoInteractions(dsl, sources); + } + + @Test + void pendingCandidateReadJoinsSigningTransactionBeforeResponseSealing() throws Exception { + Method readMethod = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "readPendingRegistryCandidate", UUID.class); + Transactional transaction = readMethod.getAnnotation(Transactional.class); + + assertThat(transaction).isNotNull(); + assertThat(transaction.propagation()).isEqualTo(Propagation.REQUIRED); + } + + @Test + void commitRequiresTheCallerWritableTransactionAndRetryReadUsesItsOwnShortTransaction() + throws Exception { + Method commitMethod = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "commitPendingCandidate", + UUID.class, + net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner + .PendingCandidateVerificationProof.class, + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationRedisClient.PendingRegistrationReceipt.class, + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation.class, + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationIssuanceCommitService.CommitProof.class); + Method readMethod = + AccountGameplayDelegationIssuanceRepository.class.getMethod( + "readCommittedProof", UUID.class); + Transactional commitTransaction = commitMethod.getAnnotation(Transactional.class); + Transactional readTransaction = readMethod.getAnnotation(Transactional.class); + + assertThat(commitTransaction).isNotNull(); + assertThat(commitTransaction.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(readTransaction).isNotNull(); + assertThat(readTransaction.propagation()).isEqualTo(Propagation.REQUIRES_NEW); + assertThat(readTransaction.readOnly()).isTrue(); + } + + @Test + void commitCannotStartWithoutWritableAccountTransactionOrTouchSql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, Clock.fixed(NOW, ZoneOffset.UTC)); + + assertThatThrownBy(() -> repository.commitPendingCandidate(REQUEST_ID, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + verifyNoInteractions(dsl, sources); + } + + @Test + void pendingSigningReadReturnsPersistedFullBundleAfterOwnerAndOperationLocks() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + IssuerAccountSourceSnapshot current = sources(); + AccountAuthoritySnapshot authority = authoritySnapshot(11L); + PendingIntent intent = intent(authority); + String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); + Record preliminary = operationRecord(intent, digest); + Record locked = operationRecord(intent, digest); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenReturn(preliminary, locked); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(current); + AccountAuthEvidenceBundle bundle = evidenceBundle(intent, current); + assertSigningBundleMatchesOwnerSnapshot(bundle, intent, authority, current); + when(bundles.captureAndPersist(REQUEST_ID)).thenReturn(bundle); + when(bundles.readStoredNonAuthorizingValue(OPERATION_ID)).thenReturn(bundle); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, bundles, Clock.fixed(NOW, ZoneOffset.UTC)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + PendingSigningIdentity result = repository.readPendingSigningIdentity(REQUEST_ID); + + assertThat(result.identity().operationId()).isEqualTo(OPERATION_ID); + assertThat(result.identity().requestId()).isEqualTo(REQUEST_ID); + assertThat(result.identity().callerContextId()).isEqualTo(CALLER_CONTEXT_ID); + assertThat(result.identity().tokenJti()).isEqualTo(JTI); + assertThat(result.authoritySnapshot()).isEqualTo(authority); + assertThat(result.evidenceBundle()).isEqualTo(bundle); + assertThat(result.toString()).doesNotContain(REQUEST_ID.toString(), JTI.toString()); + var order = inOrder(dsl, sources, bundles); + order + .verify(dsl) + .fetchOne( + org.mockito.ArgumentMatchers.eq( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?"), + org.mockito.ArgumentMatchers.any(Object[].class)); + order + .verify(dsl) + .fetchOne( + org.mockito.ArgumentMatchers.eq( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"), + org.mockito.ArgumentMatchers.any(Object[].class)); + order + .verify(sources) + .readCurrentIssuerAccountSources(GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID); + order + .verify(dsl) + .fetchOne( + org.mockito.ArgumentMatchers.eq( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ? FOR UPDATE"), + org.mockito.ArgumentMatchers.any(Object[].class)); + order.verify(bundles).captureAndPersist(REQUEST_ID); + order.verify(bundles).readStoredNonAuthorizingValue(OPERATION_ID); + order.verifyNoMoreInteractions(); + } + + @Test + void pendingSigningReadRejectsBundleForDifferentCallerAndDoesNotIssueIdentity() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + IssuerAccountSourceSnapshot current = sources(); + PendingIntent intent = intent(authoritySnapshot(11L)); + String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); + Record preliminary = operationRecord(intent, digest); + Record locked = operationRecord(intent, digest); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenReturn(preliminary, locked); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(current); + UUID changedContext = UUID.fromString("c46b58cf-4204-468b-a499-2de0eb8ce5fc"); + AccountAuthEvidenceBundle wrongCaller = evidenceBundle(intent, current, changedContext); + when(bundles.captureAndPersist(REQUEST_ID)).thenReturn(wrongCaller); + when(bundles.readStoredNonAuthorizingValue(OPERATION_ID)).thenReturn(wrongCaller); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, bundles, Clock.fixed(NOW, ZoneOffset.UTC)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.readPendingSigningIdentity(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.PendingCandidateUnavailableException.class); + verify(bundles).readStoredNonAuthorizingValue(OPERATION_ID); + } + + @Test + void pendingSigningReadRejectsBundleWithStaleIssuanceFence() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + IssuerAccountSourceSnapshot current = sources(); + AccountAuthoritySnapshot authority = authoritySnapshot(11L); + PendingIntent intent = intent(authority); + String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); + Record preliminary = operationRecord(intent, digest); + Record locked = operationRecord(intent, digest); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenReturn(preliminary, locked); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(current); + long staleFence = Math.addExact(current.issuanceFence().value(), 1L); + AccountAuthEvidenceBundle staleFenceBundle = + evidenceBundle(intent, current, CALLER_CONTEXT_ID, staleFence); + when(bundles.captureAndPersist(REQUEST_ID)).thenReturn(staleFenceBundle); + when(bundles.readStoredNonAuthorizingValue(OPERATION_ID)).thenReturn(staleFenceBundle); + AccountGameplayDelegationIssuanceRepository repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, bundles, Clock.fixed(NOW, ZoneOffset.UTC)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> repository.readPendingSigningIdentity(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.PendingCandidateUnavailableException.class); + verify(bundles).readStoredNonAuthorizingValue(OPERATION_ID); + } + + private static PendingIntent intent(AccountAuthoritySnapshot authority) { + return new PendingIntent( + OPERATION_ID, + REQUEST_ID, + "spiffe://firemud/ns/test/sa/game-session-service", + CALLER_CONTEXT_ID, + JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + authority, + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + private static AccountAuthoritySnapshot authoritySnapshot(long accountGeneration) { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + return new AccountAuthoritySnapshot( + ACCOUNT_ID, + 7L, + 7L, + accountGeneration, + accountGeneration, + accountGeneration, + accountGeneration, + Optional.of( + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + Long.toString(accountGeneration), + accountStream, + Long.toString(accountGeneration - 1L)))); + } + + private static IssuerAccountSourceSnapshot sources() { + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + IssuanceFence fence = new IssuanceFence(ACCOUNT_ID, 11L, 11L); + CurrentSourceEvidence issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER), + 7L, + 7L, + null, + checkpoint(issuerStream, 6L), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + CurrentSourceEvidence account = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 11L, + 11L, + fence, + checkpoint(accountStream, 10L), + Optional.of(new AccountSecurityCutoff("11", accountStream, "10")), + "ACCOUNT_REPOSITORY_INSERT", + 42L, + "ACCOUNT_REPOSITORY_INSERT", + 2L, + 2L); + return new IssuerAccountSourceSnapshot(issuer, account, fence); + } + + private static SourceCheckpoint checkpoint(String streamKey, long sequence) { + return new SourceCheckpoint( + streamKey, + sequence, + Optional.of("source-event-" + sequence), + Optional.of("sha256:" + "a".repeat(64))); + } + + private static Map digestPreimage( + PendingIntent intent, Map authorityTuple) { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-game-session-delegation-issuance/v2"); + value.put("operationId", intent.operationId().toString()); + value.put("requestId", intent.requestId().toString()); + value.put("accountId", intent.authoritySnapshot().accountId().toString()); + value.put("callerWorkload", intent.callerWorkload()); + value.put("callerContextId", intent.callerContextId().toString()); + value.put( + "credentialRequestBinding", + Map.of( + "digestSchemaVersion", + intent.credentialRequestBinding().digestSchemaVersion(), + "digestKeyId", + intent.credentialRequestBinding().digestKeyId(), + "credentialRequestDigest", + intent.credentialRequestBinding().credentialRequestDigest())); + value.put("jti", intent.tokenJti().toString()); + value.put("iat", intent.issuedAtEpochSecond()); + value.put("nbf", intent.notBeforeEpochSecond()); + value.put("exp", intent.expiresAtEpochSecond()); + value.put("authorityTuple", authorityTuple); + value.put("membershipVersion", Map.of()); + value.put("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence())); + value.put("authoritySourceVersions", intent.authoritySnapshot().sourceVersions()); + return value; + } + + private static Record operationRecord(PendingIntent intent, String digest) { + Record row = mock(Record.class); + when(row.get("operation_id", UUID.class)).thenReturn(intent.operationId()); + when(row.get("request_id", UUID.class)).thenReturn(intent.requestId()); + when(row.get("account_uuid", UUID.class)).thenReturn(ACCOUNT_ID); + when(row.get("caller_workload", String.class)).thenReturn(intent.callerWorkload()); + when(row.get("caller_context_id", UUID.class)).thenReturn(intent.callerContextId()); + when(row.get("request_digest_version", Short.class)).thenReturn((short) 2); + when(row.get("request_digest", String.class)).thenReturn(digest); + when(row.get("credential_request_digest_version", Short.class)) + .thenReturn((short) intent.credentialRequestBinding().digestSchemaVersion()); + when(row.get("credential_digest_key_id", String.class)) + .thenReturn(intent.credentialRequestBinding().digestKeyId()); + when(row.get("credential_request_digest", String.class)) + .thenReturn(intent.credentialRequestBinding().credentialRequestDigest()); + when(row.get("token_jti", UUID.class)).thenReturn(intent.tokenJti()); + when(row.get("token_generation", Long.class)).thenReturn(1L); + when(row.get("issued_at_epoch_second", Long.class)).thenReturn(intent.issuedAtEpochSecond()); + when(row.get("not_before_epoch_second", Long.class)).thenReturn(intent.notBeforeEpochSecond()); + when(row.get("expires_at_epoch_second", Long.class)).thenReturn(intent.expiresAtEpochSecond()); + when(row.get("authority_issuer_generation", Long.class)).thenReturn(7L); + when(row.get("authority_issuer_source_version", Long.class)).thenReturn(7L); + when(row.get("authority_account_generation", Long.class)).thenReturn(11L); + when(row.get("authority_account_source_version", Long.class)).thenReturn(11L); + when(row.get("issuance_fence", Long.class)).thenReturn(11L); + when(row.get("issuance_fence_source_version", Long.class)).thenReturn(11L); + when(row.get("authority_tuple_canonical_bytes", byte[].class)) + .thenReturn( + canonicalJson( + GameSessionAccountDelegationProfile.authorityTuple( + 7L, 11L, intent.authoritySnapshot().accountSecurityCutoff()))); + when(row.get("membership_version_canonical_bytes", byte[].class)) + .thenReturn("{}".getBytes(StandardCharsets.US_ASCII)); + when(row.get("authority_source_versions_canonical_bytes", byte[].class)) + .thenReturn(canonicalJson(intent.authoritySnapshot().sourceVersions())); + when(row.get("status", String.class)).thenReturn("PENDING"); + return row; + } + + private static AccountAuthEvidenceBundle evidenceBundle( + PendingIntent intent, IssuerAccountSourceSnapshot current) { + return evidenceBundle(intent, current, CALLER_CONTEXT_ID); + } + + private static AccountAuthEvidenceBundle evidenceBundle( + PendingIntent intent, IssuerAccountSourceSnapshot current, UUID callerContextId) { + return evidenceBundle(intent, current, callerContextId, current.issuanceFence().value()); + } + + private static AccountAuthEvidenceBundle evidenceBundle( + PendingIntent intent, + IssuerAccountSourceSnapshot current, + UUID callerContextId, + long issuanceFence) { + String issuerStream = current.issuer().checkpoint().outboxStreamKey(); + String accountStream = current.account().checkpoint().outboxStreamKey(); + Optional currentCutoff = + current + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new OwnerEvaluation( + new BundleReference("1", "11", "9", "3"), + "b".repeat(64), + "c".repeat(64), + ACCOUNT_ID, + new OperationIdentity( + OPERATION_ID, + REQUEST_ID, + AccountGameplayDelegationIssuanceRepository.requestDigest(intent), + intent.callerWorkload(), + callerContextId, + ACCOUNT_ID), + new TokenIdentity( + JTI, + 1L, + intent.issuedAtEpochSecond(), + intent.notBeforeEpochSecond(), + intent.expiresAtEpochSecond()), + GameSessionAccountDelegationProfile.authorityTuple( + current.issuer().generation(), current.account().generation(), currentCutoff), + issuanceFence, + new AuthoritySourceVersions( + current.issuer().sourceVersion(), + current.account().sourceVersion(), + current.issuanceFence().sourceVersion()), + new AccountIdentitySource( + current.account().accountSourceNumericId(), + AccountIdentityProvenance.valueOf(current.account().accountUuidProvenance()), + current.account().accountSourceNumericId()), + java.util.List.of( + new OutboxCheckpoint( + accountStream, + current.account().checkpoint().sequence(), + current.account().checkpoint().sourceEventId().orElseThrow(), + current.account().checkpoint().sourceEventDigest().orElseThrow()), + new OutboxCheckpoint( + issuerStream, + current.issuer().checkpoint().sequence(), + current.issuer().checkpoint().sourceEventId().orElseThrow(), + current.issuer().checkpoint().sourceEventDigest().orElseThrow())))); + } + + private static void assertSigningBundleMatchesOwnerSnapshot( + AccountAuthEvidenceBundle bundle, + PendingIntent intent, + AccountAuthoritySnapshot authority, + IssuerAccountSourceSnapshot current) { + Map fields = bundle.fields(); + assertThat(fields.get("schema")) + .as("bundle schema") + .isEqualTo(AccountAuthEvidenceBundle.SCHEMA); + assertThat(fields.get("issuer")) + .as("bundle issuer") + .isEqualTo(GameSessionAccountDelegationProfile.ISSUER); + assertThat(fields.get("profile")) + .as("bundle profile") + .isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(fields.get("audience")) + .as("bundle audience") + .isEqualTo(GameSessionAccountDelegationProfile.AUDIENCE); + + assertCanonicalBundleSubtree( + fields.get("scope"), + Map.of( + "kind", "account", + "accountId", intent.authoritySnapshot().accountId().toString(), + "tenantIds", java.util.List.of()), + "scope"); + assertCanonicalBundleSubtree( + fields.get("operation"), + Map.of( + "operationId", intent.operationId().toString(), + "requestId", intent.requestId().toString(), + "requestDigest", AccountGameplayDelegationIssuanceRepository.requestDigest(intent), + "callerWorkload", intent.callerWorkload(), + "callerContextId", intent.callerContextId().toString(), + "accountId", intent.authoritySnapshot().accountId().toString()), + "operation"); + assertCanonicalBundleSubtree( + fields.get("tokenIdentity"), + Map.of( + "jti", intent.tokenJti().toString(), + "tokenGeneration", "1", + "iat", intent.issuedAtEpochSecond(), + "nbf", intent.notBeforeEpochSecond(), + "exp", intent.expiresAtEpochSecond()), + "token identity"); + assertCanonicalBundleSubtree( + fields.get("authorityTuple"), + GameSessionAccountDelegationProfile.authorityTuple( + current.issuer().generation(), + current.account().generation(), + current + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))), + "authority tuple and Account cutoff"); + assertCanonicalBundleSubtree(fields.get("membershipVersion"), Map.of(), "membership version"); + assertThat(fields.get("issuanceFence")) + .as("persisted bundle issuance fence is its canonical decimal string") + .isEqualTo(Long.toString(authority.issuanceFence())); + assertCanonicalBundleSubtree( + fields.get("authoritySourceVersions"), + Map.of( + "issuerSourceVersion", Long.toString(authority.issuerSourceVersion()), + "accountSourceVersion", Long.toString(authority.accountSourceVersion()), + "issuanceFenceSourceVersion", Long.toString(authority.issuanceFenceSourceVersion())), + "authority source versions"); + assertCanonicalBundleSubtree( + fields.get("accountIdentitySource"), + Map.of( + "sourceRowId", Long.toString(current.account().accountSourceNumericId()), + "provenance", current.account().accountUuidProvenance(), + "sourceNumericId", Long.toString(current.account().accountSourceNumericId())), + "Account identity provenance"); + assertCanonicalBundleSubtree( + fields.get("outboxCheckpoints"), + java.util.List.of( + checkpointFields(current.account().checkpoint()), + checkpointFields(current.issuer().checkpoint())), + "exact owner outbox checkpoints"); + } + + private static Map checkpointFields(SourceCheckpoint checkpoint) { + Map value = new LinkedHashMap<>(); + value.put("outboxStreamKey", checkpoint.outboxStreamKey()); + value.put("outboxSequence", Long.toString(checkpoint.sequence())); + if (checkpoint.sequence() > 0L) { + value.put("sourceEventId", checkpoint.sourceEventId().orElseThrow()); + value.put("sourceEventDigest", checkpoint.sourceEventDigest().orElseThrow()); + } + return Map.copyOf(value); + } + + private static void assertCanonicalBundleSubtree(Object actual, Object expected, String label) { + assertThat(Arrays.equals(canonicalJson(actual), canonicalJson(expected))) + .as("persisted bundle %s matches exact owner readback", label) + .isTrue(); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static String digest(Map preimage) throws Exception { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java new file mode 100644 index 0000000000..17a001174d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java @@ -0,0 +1,1076 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner.ActiveCommittedIssuanceObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.support.AopUtils; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationResponseEnvelopeRepositoryTest { + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID OPERATION_ID = UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final Instant NOW = Instant.ofEpochSecond(Instant.now().getEpochSecond()); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void repositorySupportsSpringClassProxyForTransactionalInstrumentation() throws Exception { + Fixture fixture = fixture(NOW); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any())) + .thenThrow(new IllegalTransactionStateException("No existing transaction")); + + ProxyFactory proxyFactory = new ProxyFactory(fixture.repository()); + proxyFactory.setProxyTargetClass(true); + proxyFactory.addAdvice( + new TransactionInterceptor(transactionManager, new AnnotationTransactionAttributeSource())); + + AccountGameplayDelegationResponseEnvelopeRepository proxiedRepository = + (AccountGameplayDelegationResponseEnvelopeRepository) proxyFactory.getProxy(); + + assertThat(AopUtils.isCglibProxy(proxiedRepository)).isTrue(); + assertThatThrownBy(() -> proxiedRepository.preflightCommittedRecovery(null, null, null)) + .isInstanceOf(IllegalTransactionStateException.class); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactionManager).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); + verifyNoInteractions(fixture.dsl()); + } + + @Test + void exactRetryReturnsExistingSealedMetadataWithoutResealingOrReturningJwt() throws Exception { + Fixture fixture = fixture(NOW); + // The owner bundle and encrypted response are mocked components. This proves only local + // binding/CAS/readback orchestration; it is not a source, signer, or successful-issuance proof. + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) { + assertThat(sql).contains("FOR SHARE").doesNotContain("FOR UPDATE"); + return fixture.accountRow(); + } + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeReads().getAndIncrement() == 0 + ? null + : fixture.envelopeRow(); + } + throw new AssertionError("Unexpected SQL in component fixture"); + }); + when(fixture.dsl().execute(anyString(), any(Object[].class))).thenReturn(1); + when(fixture.bundles().captureAndPersist(REQUEST_ID)).thenReturn(fixture.bundle()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + when(fixture.crypto().encrypt(any(Binding.class), any(byte[].class), any(Instant.class))) + .thenReturn(fixture.sealed()); + + SealedCandidateObservation first = + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt())); + SealedCandidateObservation retry = + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt())); + + assertThat(retry).isEqualTo(first); + assertThat(first.operationId()).isEqualTo(OPERATION_ID); + assertThat(first.requestId()).isEqualTo(REQUEST_ID); + assertThat(first.responseRecoveryExpiryEpochMillis()) + .isEqualTo((NOW.getEpochSecond() + 120L) * 1_000L); + assertThat(first.toString()).doesNotContain(fixture.compactJwt()); + verify(fixture.crypto(), times(1)) + .encrypt(any(Binding.class), any(byte[].class), any(Instant.class)); + verify(fixture.dsl(), times(1)).execute(anyString(), any(Object[].class)); + + ArgumentCaptor binding = ArgumentCaptor.forClass(Binding.class); + verify(fixture.crypto()).encrypt(binding.capture(), any(byte[].class), any(Instant.class)); + assertThat(binding.getValue().operation()) + .isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(binding.getValue().requestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(binding.getValue().callerWorkload()).isEqualTo(WORKLOAD); + assertThat(binding.getValue().bindingId()).isEqualTo(OPERATION_ID.toString()); + assertThat(binding.getValue().lineageId()).isEmpty(); + assertThat(binding.getValue().replacementId()).isEmpty(); + assertThat(binding.getValue().leaseId()).isEmpty(); + assertThat(binding.getValue().issuanceFence()).isEqualTo(11L); + assertThat(binding.getValue().authorityEvidenceBundleCanonicalBytes()) + .isEqualTo(fixture.bundle().canonicalBytes()); + assertThat(binding.getValue().membershipVersionMapCanonicalBytes()) + .isEqualTo("{}".getBytes(StandardCharsets.US_ASCII)); + } + + @Test + void changedCallerOrCompactCandidateDeniesBeforeSourceReadOrEncryption() throws Exception { + Fixture fixture = fixture(NOW); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow()); + CallerIdentity wrongCaller = + new CallerIdentity("spiffe://firemud/ns/other/sa/game-session-service", CALLER_CONTEXT_ID); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, wrongCaller, fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + + CallerIdentity wrongContext = + new CallerIdentity(WORKLOAD, UUID.fromString("c46b58cf-4204-468b-a499-2de0eb8ce5fc")); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, wrongContext, fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt() + "A"))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); + verifyNoInteractions(fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); + verify(fixture.dsl(), never()).execute(anyString(), any(Object[].class)); + } + + @Test + void committedRecoveryReturnsOnlyExactHashMatchedJwtAfterActiveOwnerEvidence() throws Exception { + Fixture fixture = fixture(NOW); + AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + CommittedCandidateVerificationData committed = committedCandidate(fixture); + ActiveCommittedIssuanceObservation active = activeObservation(fixture); + when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected recovery SQL in component fixture"); + }); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(fixture.snapshot()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + when(issuance.readCurrentCommittedCandidate(REQUEST_ID)).thenReturn(committed); + when(fixture + .crypto() + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) + .thenReturn(fixture.compactJwt().getBytes(StandardCharsets.US_ASCII)); + AccountGameplayDelegationResponseEnvelopeRepository repository = + new AccountGameplayDelegationResponseEnvelopeRepository( + fixture.dsl(), fixture.sourceEvidence(), fixture.bundles(), issuance, fixture.crypto()); + + var recovered = + inWritableOwnerTransaction( + () -> + repository.recoverCommittedResponse( + REQUEST_ID, ACCOUNT_ID, fixture.caller(), active)); + + assertThat(recovered.compactJwtBytes()) + .containsExactly(fixture.compactJwt().getBytes(StandardCharsets.US_ASCII)); + assertThat(recovered.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(recovered.tokenJti()).isEqualTo(JTI); + assertThat(recovered.tokenSha256()).isEqualTo(fixture.candidate().tokenHash()); + assertThat(recovered.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(recovered.expiresAtEpochSecond()).isEqualTo(fixture.intent().expiresAtEpochSecond()); + assertThat(recovered.authEvidenceBundle()).isSameAs(fixture.bundle()); + assertThat(recovered.toString()).doesNotContain(fixture.compactJwt()); + verify(issuance).readCurrentCommittedCandidate(REQUEST_ID); + verify(fixture.crypto()) + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class)); + } + + @Test + void committedRecoveryPreflightRejectsEveryCallerBindingMismatchBeforeOwnerReads() + throws Exception { + Fixture fixture = fixture(NOW); + when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow()); + AccountGameplayDelegationResponseEnvelopeRepository repository = + new AccountGameplayDelegationResponseEnvelopeRepository( + fixture.dsl(), fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + repository.preflightCommittedRecovery( + UUID.fromString("58102ea4-9245-4ddc-a68c-3ff41dcf96af"), + ACCOUNT_ID, + fixture.caller()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.OperationUnavailableException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + repository.preflightCommittedRecovery( + REQUEST_ID, + UUID.fromString("674cb504-8f4c-4d06-86c6-7b72f79cae74"), + fixture.caller()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + repository.preflightCommittedRecovery( + REQUEST_ID, + ACCOUNT_ID, + new CallerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + CALLER_CONTEXT_ID)))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + repository.preflightCommittedRecovery( + REQUEST_ID, + ACCOUNT_ID, + new CallerIdentity( + WORKLOAD, + UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"))))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) + .hasNoCause(); + + verifyNoInteractions(fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); + } + + @Test + void committedRecoveryPreflightRejectsAnExpiredOriginalDeadlineBeforeOwnerReads() + throws Exception { + Fixture fixture = fixture(NOW.minusSeconds(121L)); + when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow()); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, fixture.caller()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException + .class) + .hasNoCause(); + + verifyNoInteractions(fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); + } + + @Test + void committedRecoveryRejectsDecryptedDigestDriftAndMissingEnvelopeKey() throws Exception { + Fixture digestFixture = fixture(NOW); + RecoveryHarness digestHarness = recoveryHarness(digestFixture); + byte[] alteredJwt = (digestFixture.compactJwt() + "A").getBytes(StandardCharsets.US_ASCII); + when(digestFixture + .crypto() + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) + .thenReturn(alteredJwt); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + digestHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, + ACCOUNT_ID, + digestFixture.caller(), + digestHarness.active()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) + .hasNoCause(); + + Fixture missingKeyFixture = fixture(NOW); + RecoveryHarness missingKeyHarness = recoveryHarness(missingKeyFixture); + AccountResponseEnvelopeKeyring.KeyUnavailableException missingKey = + mock(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + when(missingKeyFixture + .crypto() + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) + .thenThrow(missingKey); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + missingKeyHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, + ACCOUNT_ID, + missingKeyFixture.caller(), + missingKeyHarness.active()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) + .hasNoCause(); + } + + @Test + void activeHashAndEnvelopeDigestDriftFailBeforeDecryption() throws Exception { + Fixture fixture = fixture(NOW); + RecoveryHarness harness = recoveryHarness(fixture); + when(harness.active().tokenSha256()).thenReturn("f".repeat(64)); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + harness + .repository() + .recoverCommittedResponse( + REQUEST_ID, ACCOUNT_ID, fixture.caller(), harness.active()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException + .class) + .hasNoCause(); + verify(fixture.crypto(), never()) + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class)); + + Fixture envelopeFixture = fixture(NOW); + RecoveryHarness envelopeHarness = recoveryHarness(envelopeFixture); + when(envelopeFixture.envelopeRow().get("envelope_sha256", String.class)) + .thenReturn("f".repeat(64)); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + envelopeHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, + ACCOUNT_ID, + envelopeFixture.caller(), + envelopeHarness.active()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) + .hasNoCause(); + verify(envelopeFixture.crypto(), never()) + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class)); + } + + @Test + void expiryAndMissingOwnerBundleDenyWithoutCreatingOrExposingEnvelope() throws Exception { + Fixture expired = fixture(NOW.minusSeconds(121L)); + when(expired.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(expired.operationRow()); + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + expired + .repository() + .sealPendingCandidate( + REQUEST_ID, expired.caller(), expired.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException + .class); + verifyNoInteractions(expired.sourceEvidence(), expired.bundles(), expired.crypto()); + verify(expired.dsl(), never()).execute(anyString(), any(Object[].class)); + + Fixture missing = fixture(NOW); + when(missing.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(missing.operationRow(), missing.operationRow(), missing.accountRow()); + when(missing + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(missing.snapshot()); + when(missing.bundles().captureAndPersist(REQUEST_ID)) + .thenThrow(new AccountAuthEvidenceBundleRepository.OwnerEvidenceUnavailableException()); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + missing + .repository() + .sealPendingCandidate( + REQUEST_ID, missing.caller(), missing.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException + .class); + verify(missing.crypto(), never()) + .encrypt(any(Binding.class), any(byte[].class), any(Instant.class)); + verify(missing.dsl(), never()).execute(anyString(), any(Object[].class)); + } + + @Test + void pendingCandidateResumeRejectsAlteredEncryptedEnvelopeBeforeDecryption() throws Exception { + Fixture fixture = fixture(NOW); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected pending-resume SQL in component fixture"); + }); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + when(fixture.envelopeRow().get("envelope_bytes", byte[].class)) + .thenReturn(new byte[] {9, 8, 7, 6, 5}); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> fixture.repository().openPendingCandidate(REQUEST_ID, fixture.caller()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) + .hasNoCause(); + verify(fixture.crypto(), never()) + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class)); + } + + private static RecoveryHarness recoveryHarness(Fixture fixture) throws Exception { + AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + CommittedCandidateVerificationData committed = committedCandidate(fixture); + ActiveCommittedIssuanceObservation active = activeObservation(fixture); + when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected recovery SQL in component fixture"); + }); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(fixture.snapshot()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + when(issuance.readCurrentCommittedCandidate(REQUEST_ID)).thenReturn(committed); + when(fixture + .crypto() + .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) + .thenReturn(fixture.compactJwt().getBytes(StandardCharsets.US_ASCII)); + return new RecoveryHarness( + new AccountGameplayDelegationResponseEnvelopeRepository( + fixture.dsl(), fixture.sourceEvidence(), fixture.bundles(), issuance, fixture.crypto()), + active); + } + + private static CommittedCandidateVerificationData committedCandidate(Fixture fixture) + throws Exception { + CommittedCandidateVerificationData committed = mock(CommittedCandidateVerificationData.class); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CALLER_CONTEXT_ID, + fixture.intent().credentialRequestBinding(), + fixture.digest(), + JTI, + fixture.intent().issuedAtEpochSecond(), + fixture.intent().notBeforeEpochSecond(), + fixture.intent().expiresAtEpochSecond()); + long expiresAtMillis = Math.multiplyExact(fixture.intent().expiresAtEpochSecond(), 1_000L); + when(committed.identity()).thenReturn(identity); + when(committed.authoritySnapshot()).thenReturn(fixture.intent().authoritySnapshot()); + when(committed.evidenceBundleReference()) + .thenReturn(fixture.candidate().evidenceBundleReference()); + when(committed.tokenSha256()).thenReturn(fixture.candidate().tokenHash()); + when(committed.signerKid()).thenReturn(fixture.candidate().kid()); + when(committed.signerGeneration()).thenReturn(fixture.candidate().signerGeneration()); + when(committed.canonicalRegistryRecordSha256()) + .thenReturn( + sha256( + fixture + .candidate() + .toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES))); + when(committed.commitProofSha256()).thenReturn("c".repeat(64)); + when(committed.envelopeKeyId()).thenReturn("response-key-1"); + String envelopeSha256 = fixture.envelopeRow().get("envelope_sha256", String.class); + when(committed.envelopeSha256()).thenReturn(envelopeSha256); + when(committed.envelopeBytesLength()).thenReturn(fixture.sealed().bytes().length); + when(committed.responseRecoveryExpiryEpochMillis()).thenReturn(expiresAtMillis); + when(committed.registryAbsoluteExpiryMillis()).thenReturn(expiresAtMillis + 30_000L); + when(committed.registrationLocalAofCount()).thenReturn(1L); + when(committed.registrationReplicaAofCount()).thenReturn(1L); + when(committed.registrationOutcome()) + .thenReturn(AccountGameplayDelegationRedisClient.PendingRegistrationOutcome.CREATED); + return committed; + } + + private static ActiveCommittedIssuanceObservation activeObservation(Fixture fixture) { + ActiveCommittedIssuanceObservation active = mock(ActiveCommittedIssuanceObservation.class); + when(active.operationId()).thenReturn(OPERATION_ID); + when(active.requestId()).thenReturn(REQUEST_ID); + when(active.accountId()).thenReturn(ACCOUNT_ID); + when(active.tokenSha256()).thenReturn(fixture.candidate().tokenHash()); + when(active.activeRecordSha256()).thenReturn("d".repeat(64)); + when(active.commitProofSha256()).thenReturn("c".repeat(64)); + when(active.registryVersion()).thenReturn(2L); + when(active.absoluteExpiryMillis()) + .thenReturn(Math.multiplyExact(fixture.intent().expiresAtEpochSecond(), 1_000L) + 30_000L); + when(active.outcome()).thenReturn(ActiveRegistrationOutcome.ACTIVATED); + when(active.observedAtEpochMillis()).thenReturn(NOW.toEpochMilli()); + return active; + } + + @Test + void sourceVersionOrFenceChangeDeniesBeforeBundleRead() throws Exception { + Fixture fixture = fixture(NOW); + IssuerAccountSourceSnapshot changed = sourceSnapshot(12L); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow(), fixture.operationRow()); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(changed); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.AuthorityChangedException.class); + verifyNoInteractions(fixture.bundles(), fixture.crypto()); + } + + @Test + void bundleReadbackMustMatchTheSameOwnerEvaluationBytes() throws Exception { + Fixture fixture = fixture(NOW); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenReturn(fixture.operationRow(), fixture.operationRow()); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(fixture.snapshot()); + when(fixture.bundles().captureAndPersist(REQUEST_ID)).thenReturn(fixture.bundle()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(bundle(fixture.digest(), "3".repeat(64))); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException + .class); + verify(fixture.crypto(), never()) + .encrypt(any(Binding.class), any(byte[].class), any(Instant.class)); + verify(fixture.dsl(), never()).execute(anyString(), any(Object[].class)); + } + + @Test + void tokenGenerationRequiresCanonicalOneStringAndRejectsOtherWireValues() throws Exception { + AccountAuthEvidenceBundle bundle = fixture(NOW).bundle(); + Object tokenGeneration = + ((Map) bundle.fields().get("tokenIdentity")).get("tokenGeneration"); + + assertThat(tokenGeneration).isInstanceOf(String.class).isEqualTo("1"); + assertThat(AccountAuthEvidenceBundle.parseCanonical(bundle.canonicalBytes())).isEqualTo(bundle); + + for (Object invalidTokenGeneration : List.of(1L, "01", "2")) { + assertThatThrownBy( + () -> + AccountAuthEvidenceBundle.parseCanonical( + bundleBytesWithTokenGeneration(bundle, invalidTokenGeneration))) + .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); + } + } + + @Test + void mismatchedStoredEnvelopeExpiryIsNotReplayed() throws Exception { + Fixture fixture = fixture(NOW); + Record mismatchedExpiry = + envelopeRow( + fixture.candidate(), + fixture.bundle(), + fixture.sealed().bytes(), + NOW.getEpochSecond() + 119L); + when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return mismatchedExpiry; + } + throw new AssertionError("Unexpected SQL in component fixture"); + }); + when(fixture + .sourceEvidence() + .readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(fixture.snapshot()); + when(fixture.bundles().captureAndPersist(REQUEST_ID)).thenReturn(fixture.bundle()); + when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) + .thenReturn(fixture.bundle()); + + assertThatThrownBy( + () -> + inWritableOwnerTransaction( + () -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + .isInstanceOf( + AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class); + verify(fixture.crypto(), never()) + .encrypt(any(Binding.class), any(byte[].class), any(Instant.class)); + verify(fixture.dsl(), never()).execute(anyString(), any(Object[].class)); + } + + private static Fixture fixture(Instant now) throws Exception { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + AccountResponseEnvelopeCryptography crypto = mock(AccountResponseEnvelopeCryptography.class); + IssuerAccountSourceSnapshot snapshot = sourceSnapshot(11L); + long issuedAtEpochSecond = now.getEpochSecond(); + PendingIntent intent = + new PendingIntent( + OPERATION_ID, + REQUEST_ID, + WORKLOAD, + CALLER_CONTEXT_ID, + JTI, + issuedAtEpochSecond, + issuedAtEpochSecond, + issuedAtEpochSecond + 120L, + new AccountAuthoritySnapshot( + ACCOUNT_ID, 7L, 7L, 11L, 11L, 11L, 11L, Optional.of(accountCutoff(11L))), + AccountGameplayCredentialRequestBindingFixture.binding()); + String digest = + net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository + .requestDigest(intent); + String compactJwt = compactCandidate(intent); + AccountAuthEvidenceBundle bundle = bundle(digest, "2".repeat(64)); + GameSessionAccountDelegationRegistryRecord candidate = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compactJwt, + "2", + new IssuanceBinding( + OPERATION_ID.toString(), REQUEST_ID.toString(), digest, ACCOUNT_ID.toString()), + intent.authoritySnapshot(), + new EvidenceBundleReference("1", "11", "9", "12345678", bundle.canonicalSha256()), + intent.issuedAtEpochSecond(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + byte[] candidateBytes = + candidate.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + byte[] sealedBytes = new byte[] {1, 2, 3, 4, 5}; + EncryptedResponseEnvelope sealed = new EncryptedResponseEnvelope(sealedBytes); + Record operationRow = operationRow(intent, digest, candidate, candidateBytes); + Record accountRow = mock(Record.class); + when(accountRow.get("id", Long.class)).thenReturn(42L); + when(accountRow.get("id")).thenReturn(42L); + when(accountRow.get("account_uuid", UUID.class)).thenReturn(ACCOUNT_ID); + when(accountRow.get("account_uuid_provenance", String.class)) + .thenReturn(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name()); + when(accountRow.get("account_uuid_source_numeric_id", Long.class)).thenReturn(42L); + when(accountRow.get("account_uuid_source_numeric_id")).thenReturn(42L); + when(sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(snapshot); + Record envelopeRow = envelopeRow(candidate, bundle, sealedBytes, intent.expiresAtEpochSecond()); + return new Fixture( + dsl, + sourceEvidence, + bundles, + crypto, + snapshot, + intent, + digest, + compactJwt, + candidate, + bundle, + sealed, + operationRow, + accountRow, + envelopeRow, + new AtomicInteger(), + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sourceEvidence, bundles, crypto)); + } + + private static Record operationRow( + PendingIntent intent, + String digest, + GameSessionAccountDelegationRegistryRecord candidate, + byte[] candidateBytes) { + Record row = mock(Record.class); + when(row.get("operation_id", UUID.class)).thenReturn(OPERATION_ID); + when(row.get("request_id", UUID.class)).thenReturn(REQUEST_ID); + when(row.get("account_uuid", UUID.class)).thenReturn(ACCOUNT_ID); + when(row.get("caller_workload", String.class)).thenReturn(WORKLOAD); + when(row.get("caller_context_id", UUID.class)).thenReturn(CALLER_CONTEXT_ID); + when(row.get("request_digest", String.class)).thenReturn(digest); + when(row.get("token_jti", UUID.class)).thenReturn(JTI); + when(row.get("status", String.class)).thenReturn("PENDING"); + when(row.get("request_digest_version")).thenReturn((short) 2); + when(row.get("credential_request_digest_version")) + .thenReturn((short) intent.credentialRequestBinding().digestSchemaVersion()); + when(row.get("credential_digest_key_id", String.class)) + .thenReturn(intent.credentialRequestBinding().digestKeyId()); + when(row.get("credential_request_digest", String.class)) + .thenReturn(intent.credentialRequestBinding().credentialRequestDigest()); + when(row.get("token_generation")).thenReturn(1L); + when(row.get("issued_at_epoch_second")).thenReturn(intent.issuedAtEpochSecond()); + when(row.get("not_before_epoch_second")).thenReturn(intent.notBeforeEpochSecond()); + when(row.get("expires_at_epoch_second")).thenReturn(intent.expiresAtEpochSecond()); + when(row.get("authority_issuer_generation")).thenReturn(7L); + when(row.get("authority_issuer_source_version")).thenReturn(7L); + when(row.get("authority_account_generation")).thenReturn(11L); + when(row.get("authority_account_source_version")).thenReturn(11L); + when(row.get("issuance_fence")).thenReturn(11L); + when(row.get("issuance_fence_source_version")).thenReturn(11L); + when(row.get("token_hash", String.class)).thenReturn(candidate.tokenHash()); + when(row.get("signer_kid", String.class)).thenReturn(candidate.kid()); + when(row.get("signer_generation", String.class)).thenReturn(candidate.signerGeneration()); + when(row.get("pending_registry_candidate_bytes", byte[].class)).thenReturn(candidateBytes); + when(row.get("authority_tuple_canonical_bytes", byte[].class)) + .thenReturn( + canonicalJson( + GameSessionAccountDelegationProfile.authorityTuple( + 7L, 11L, Optional.of(accountCutoff(11L))))); + when(row.get("membership_version_canonical_bytes", byte[].class)) + .thenReturn("{}".getBytes(StandardCharsets.US_ASCII)); + return row; + } + + private static Record envelopeRow( + GameSessionAccountDelegationRegistryRecord candidate, + AccountAuthEvidenceBundle bundle, + byte[] envelope, + long expiryEpochSecond) + throws Exception { + Record row = mock(Record.class); + when(row.get("operation_id", UUID.class)).thenReturn(OPERATION_ID); + when(row.get("request_id", UUID.class)).thenReturn(REQUEST_ID); + when(row.get("token_hash", String.class)).thenReturn(candidate.tokenHash()); + when(row.get("signer_kid", String.class)).thenReturn(candidate.kid()); + when(row.get("signer_generation", String.class)).thenReturn(candidate.signerGeneration()); + when(row.get("authority_evidence_bundle_sha256", String.class)) + .thenReturn(bundle.canonicalSha256()); + when(row.get("issuance_fence", Long.class)).thenReturn(11L); + when(row.get("issuance_fence")).thenReturn(11L); + when(row.get("response_recovery_expiry_epoch_ms", Long.class)) + .thenReturn(Math.multiplyExact(expiryEpochSecond, 1_000L)); + when(row.get("response_recovery_expiry_epoch_ms")) + .thenReturn(Math.multiplyExact(expiryEpochSecond, 1_000L)); + when(row.get("envelope_sha256", String.class)).thenReturn(sha256(envelope)); + when(row.get("envelope_bytes", byte[].class)).thenReturn(envelope); + return row; + } + + private static AccountAuthEvidenceBundle bundle(String digest, String evaluationIdentity) { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new OwnerEvaluation( + new BundleReference("1", "11", "9", "12345678"), + "1".repeat(64), + evaluationIdentity, + ACCOUNT_ID, + new OperationIdentity( + OPERATION_ID, REQUEST_ID, digest, WORKLOAD, CALLER_CONTEXT_ID, ACCOUNT_ID), + new TokenIdentity( + JTI, 1L, NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120L), + GameSessionAccountDelegationProfile.authorityTuple( + 7L, 11L, Optional.of(accountCutoff(11L))), + 11L, + new AuthoritySourceVersions(7L, 11L, 11L), + new AccountIdentitySource( + 42L, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L), + List.of( + new OutboxCheckpoint( + accountStream, 10L, "fixture-account-event", "sha256:" + "a".repeat(64)), + new OutboxCheckpoint( + issuerStream, 6L, "fixture-issuer-event", "sha256:" + "b".repeat(64))))); + } + + private static byte[] bundleBytesWithTokenGeneration( + AccountAuthEvidenceBundle bundle, Object tokenGeneration) { + Map fields = new LinkedHashMap<>(bundle.fields()); + Map tokenIdentity = new LinkedHashMap<>(); + ((Map) fields.get("tokenIdentity")) + .forEach((field, value) -> tokenIdentity.put((String) field, value)); + tokenIdentity.put("tokenGeneration", tokenGeneration); + fields.put("tokenIdentity", tokenIdentity); + return canonicalJson(fields); + } + + private static IssuerAccountSourceSnapshot sourceSnapshot(long accountGeneration) { + long accountSourceVersion = accountGeneration; + long issuerGeneration = 7L; + long accountFence = accountGeneration; + IssuanceFence issuanceFence = new IssuanceFence(ACCOUNT_ID, accountFence, accountSourceVersion); + CurrentSourceEvidence issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER), + issuerGeneration, + issuerGeneration, + null, + new SourceCheckpoint( + "account:auth-authority:v1:issuer/firemud-account-service", + issuerGeneration - 1L, + Optional.of("fixture-issuer-event"), + Optional.of("b".repeat(64))), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + CurrentSourceEvidence account = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + accountGeneration, + accountSourceVersion, + issuanceFence, + new SourceCheckpoint( + "account:auth-authority:v1:account/" + ACCOUNT_ID, + accountGeneration - 1L, + Optional.of("fixture-account-event"), + Optional.of("a".repeat(64))), + Optional.of(sourceAccountCutoff(accountGeneration)), + "ACCOUNT_REPOSITORY_INSERT", + 42L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name(), + 2L, + 2L); + return new IssuerAccountSourceSnapshot(issuer, account, issuanceFence); + } + + private static GameSessionAccountDelegationProfile.AccountSecurityCutoff accountCutoff( + long accountGeneration) { + return new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + Long.toString(accountGeneration), + "account:auth-authority:v1:account/" + ACCOUNT_ID, + Long.toString(accountGeneration - 1L)); + } + + private static AccountSecurityCutoff sourceAccountCutoff(long accountGeneration) { + return new AccountSecurityCutoff( + Long.toString(accountGeneration), + "account:auth-authority:v1:account/" + ACCOUNT_ID, + Long.toString(accountGeneration - 1L)); + } + + private static String compactCandidate(PendingIntent intent) throws Exception { + Map header = Map.of("alg", "RS256", "kid", "delegation-kid", "typ", "JWT"); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", ACCOUNT_ID.toString()), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("jti", JTI.toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", intent.expiresAtEpochSecond()), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence()))); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String head = encoder.encodeToString(canonicalJson(header)); + String payload = encoder.encodeToString(canonicalJson(claims)); + return head + "." + payload + "." + encoder.encodeToString(new byte[] {1, 2, 3}); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static String sha256(byte[] bytes) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static T inWritableOwnerTransaction(java.util.function.Supplier operation) { + boolean priorActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean priorReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + return operation.get(); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(priorReadOnly); + TransactionSynchronizationManager.setActualTransactionActive(priorActive); + } + } + + private record RecoveryHarness( + AccountGameplayDelegationResponseEnvelopeRepository repository, + ActiveCommittedIssuanceObservation active) {} + + private record Fixture( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository bundles, + AccountResponseEnvelopeCryptography crypto, + IssuerAccountSourceSnapshot snapshot, + PendingIntent intent, + String digest, + String compactJwt, + GameSessionAccountDelegationRegistryRecord candidate, + AccountAuthEvidenceBundle bundle, + EncryptedResponseEnvelope sealed, + Record operationRow, + Record accountRow, + Record envelopeRow, + AtomicInteger envelopeReads, + AccountGameplayDelegationResponseEnvelopeRepository repository) { + private CallerIdentity caller() { + return new CallerIdentity(WORKLOAD, CALLER_CONTEXT_ID); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java new file mode 100644 index 0000000000..59c347d389 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java @@ -0,0 +1,291 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Modifier; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository.TokenFenceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository.TokenRevokedException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameplayTokenIdentityFenceRepositoryTest { + private static final TokenIdentity IDENTITY = + new TokenIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + UUID.randomUUID(), + 1_800_000_000L, + 1L, + 11L); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void registrationIsNotAPublicAdoptionApi() throws Exception { + var method = + AccountGameplayTokenIdentityFenceRepository.class.getDeclaredMethod( + "registerCommittedIssuance", TokenIdentity.class); + assertThat(Modifier.isPublic(method.getModifiers())).isFalse(); + assertThat(Modifier.isProtected(method.getModifiers())).isFalse(); + } + + @Test + void writableAccountTransactionRequiredBeforeAnyRead() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayTokenIdentityFenceRepository(dsl); + assertThatThrownBy(() -> repository.requireActiveForUpdate(IDENTITY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.requireActiveForUpdate(IDENTITY)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void activeReadLocksAccountBeforeTokenAndIndependentlyReadsExactCommittedSource() { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record source = mock(Record.class); + Record token = tokenRow(State.ACTIVE); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, source); + transaction(); + var fence = + new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(IDENTITY); + assertThat(fence.identity()).isEqualTo(IDENTITY); + assertThat(fence.tokenIdentityFence()).isEqualTo(1L); + var ordered = inOrder(dsl); + ordered + .verify(dsl) + .fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + IDENTITY.accountId()); + ordered + .verify(dsl) + .fetchOne( + "SELECT account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " + + "not_before_epoch_second, token_generation, issuance_fence, token_identity_fence, " + + "state, revocation_request_id, revocation_digest " + + "FROM account_gameplay_token_identity_fences WHERE operation_id = ? FOR UPDATE", + IDENTITY.operationId()); + ordered + .verify(dsl) + .fetchOne( + "SELECT operation_id FROM account_gameplay_delegation_issuance_operations " + + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? AND token_hash = ? " + + "AND token_jti = ? AND not_before_epoch_second = ? AND token_generation = ? " + + "AND issuance_fence = ? AND status = 'COMMITTED'", + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.accountId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + IDENTITY.tokenGeneration(), + IDENTITY.issuanceFence()); + } + + @Test + void missingCommittedSourceCannotAuthorizeEvenWithActiveTokenRow() { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record token = tokenRow(State.ACTIVE); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, null); + transaction(); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(IDENTITY)) + .isInstanceOf(TokenFenceUnavailableException.class); + } + + @Test + void exactIdentityMismatchCannotUseAnotherActiveFence() { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record token = tokenRow(State.ACTIVE); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token); + transaction(); + TokenIdentity changedNbf = + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond() + 1L, + IDENTITY.tokenGeneration(), + IDENTITY.issuanceFence()); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(changedNbf)) + .isInstanceOf(TokenFenceUnavailableException.class); + } + + @Test + void pendingAndCommittedRevocationBothDenyAdmission() { + for (State state : new State[] {State.PENDING, State.COMMITTED}) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record token = tokenRow(state); + Record source = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, source); + transaction(); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(IDENTITY)) + .isInstanceOf(TokenRevokedException.class); + } + } + + @Test + void revocationDigestBindsEveryExactTokenIdentityAndRequestField() { + UUID requestId = UUID.randomUUID(); + String digest = + AccountGameplayTokenIdentityFenceRepository.revocationDigest(IDENTITY, requestId); + TokenIdentity[] changed = { + new TokenIdentity( + UUID.randomUUID(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + UUID.randomUUID(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + UUID.randomUUID(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + "b".repeat(64), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + UUID.randomUUID(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond() + 1L, + 1L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 2L, + 11L), + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + 12L) + }; + for (TokenIdentity identity : changed) { + assertThat(AccountGameplayTokenIdentityFenceRepository.revocationDigest(identity, requestId)) + .isNotEqualTo(digest); + } + assertThat( + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + IDENTITY, UUID.randomUUID())) + .isNotEqualTo(digest); + assertThat(IDENTITY.toString()) + .doesNotContain(IDENTITY.tokenSha256(), IDENTITY.tokenJti().toString()); + } + + @Test + void callerClaimedDigestCannotStartRevocationOrAcquireLocks() { + DSLContext dsl = mock(DSLContext.class); + transaction(); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(IDENTITY, UUID.randomUUID(), "b".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + private static Record tokenRow(State state) { + Record row = mock(Record.class); + when(row.get("account_uuid", UUID.class)).thenReturn(IDENTITY.accountId()); + when(row.get("operation_id", UUID.class)).thenReturn(IDENTITY.operationId()); + when(row.get("issuance_request_id", UUID.class)).thenReturn(IDENTITY.issuanceRequestId()); + when(row.get("token_hash", String.class)).thenReturn(IDENTITY.tokenSha256()); + when(row.get("token_jti", UUID.class)).thenReturn(IDENTITY.tokenJti()); + when(row.get("not_before_epoch_second", Long.class)) + .thenReturn(IDENTITY.notBeforeEpochSecond()); + when(row.get("token_generation", Long.class)).thenReturn(IDENTITY.tokenGeneration()); + when(row.get("issuance_fence", Long.class)).thenReturn(IDENTITY.issuanceFence()); + when(row.get("state", String.class)).thenReturn(state.name()); + when(row.get("token_identity_fence", Long.class)) + .thenReturn(state == State.ACTIVE ? 1L : state == State.PENDING ? 2L : 3L); + if (state != State.ACTIVE) { + when(row.get("revocation_request_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("revocation_digest", String.class)).thenReturn("b".repeat(64)); + } + return row; + } + + private static void transaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java new file mode 100644 index 0000000000..bccc9a219f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisScriptingCommands; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; + +class AccountGenerationProjectionRedisContractTest { + @Test + void registeredLuaBytesMatchTheOwnerPinnedSha256() throws Exception { + RedisScriptDescriptor descriptor = AccountGenerationProjectionRedisContract.descriptor(); + byte[] source; + try (var input = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(input).isNotNull(); + source = input.readAllBytes(); + } + + assertThat(sha256(source)).isEqualTo(descriptor.sha256()); + } + + @Test + void installedOwnerContributionDeclaresExactAccountCasContract() { + RedisScriptCatalog catalog = RedisScriptCatalog.loadInstalled(getClass().getClassLoader()); + RedisScriptDescriptor descriptor = + catalog.require(AccountGenerationProjectionRedisContract.SCRIPT_ID); + + assertThat(descriptor).isEqualTo(AccountGenerationProjectionRedisContract.descriptor()); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.scriptId()).isEqualTo("account.account-generation-projection.v1"); + assertThat(descriptor.resourcePath()).isEqualTo("redis/account_generation_projection_cas.lua"); + assertThat(descriptor.sha256()) + .isEqualTo(AccountGenerationProjectionRedisContract.RESOURCE_SHA256); + assertThat(descriptor.principal()).isEqualTo("account_coord_app"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(descriptor.keys()) + .containsExactly( + new RedisScriptDescriptor.KeySpec( + "accountGenerationProjection", + AccountGenerationProjectionRedisContract.KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)); + assertThat(descriptor.arguments()) + .containsExactly( + new RedisScriptDescriptor.ArgumentSpec("expectedMode"), + new RedisScriptDescriptor.ArgumentSpec("expectedBytes"), + new RedisScriptDescriptor.ArgumentSpec("candidateBytes")); + assertThat(descriptor.outcomes()) + .containsExactly( + outcome( + "APPLIED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "STALE", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "INVALID", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "TTL_PRESENT", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + assertThat(descriptor.resetSensitivity()) + .isEqualTo(RedisScriptDescriptor.ResetSensitivity.CLUSTER); + assertThat(descriptor.lossClass()) + .isEqualTo(RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP); + assertThat(descriptor.compatibilityLevel()) + .isEqualTo(RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET); + assertThat(descriptor.supportedCoexistence()) + .containsExactly(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")); + } + + @Test + void onlyCanonicalAccountKeysAndExactModeSpecificArgumentsAreAccepted() { + String key = + AccountGenerationProjectionRedisContract.KEY_PREFIX + + "c980fa44-619e-4ca4-8ad6-75b0538a66a3"; + AccountGenerationProjectionRedisContract.validateInvocation(key, "ABSENT", "", "candidate"); + AccountGenerationProjectionRedisContract.validateInvocation( + key, "PRESENT", "expected", "candidate"); + AccountGenerationProjectionRedisContract.validateInvocation(key, "VERIFY", "expected", ""); + + assertThatThrownBy( + () -> + AccountGenerationProjectionRedisContract.validateInvocation( + "session:auth:generation:issuer:c980fa44-619e-4ca4-8ad6-75b0538a66a3", + "ABSENT", + "", + "candidate")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGenerationProjectionRedisContract.validateInvocation( + key, "VERIFY", "expected", "candidate")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGenerationProjectionRedisContract.validateInvocation( + key, "ABSENT", "not-empty", "candidate")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void descriptorCannotSubstituteDifferentKeyPrefixOrArgumentOrder() { + RedisScriptDescriptor original = AccountGenerationProjectionRedisContract.descriptor(); + RedisScriptDescriptor wrongKeys = + new RedisScriptDescriptor( + original.scriptId(), + original.resourcePath(), + original.sha256(), + original.owner(), + original.principal(), + original.role(), + List.of( + new RedisScriptDescriptor.KeySpec( + "otherKey", + "session:auth:token:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + original.arguments(), + original.category(), + original.outcomes(), + original.resetSensitivity(), + original.lossClass(), + original.tailLossBehavior(), + original.compatibilityLevel(), + original.supportedCoexistence(), + original.legacyPayloadShape()); + + assertThatThrownBy( + () -> AccountGenerationProjectionRedisContract.requireSupportedDescriptor(wrongKeys)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void numericLuaOutcomesDecodeToExistingStoreTokensAndRejectUnexpectedReplies() { + assertThat(CurrentGenerationProjectionRedisSupport.decodeScriptResult(1L)).isEqualTo("APPLIED"); + assertThat(CurrentGenerationProjectionRedisSupport.decodeScriptResult("0")).isEqualTo("REPLAY"); + assertThat( + CurrentGenerationProjectionRedisSupport.decodeScriptResult( + "-3".getBytes(StandardCharsets.US_ASCII))) + .isEqualTo("TTL_PRESENT"); + + assertThatThrownBy(() -> CurrentGenerationProjectionRedisSupport.decodeScriptResult("APPLIED")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> CurrentGenerationProjectionRedisSupport.decodeScriptResult("1.0")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> CurrentGenerationProjectionRedisSupport.decodeScriptResult("9")) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void registeredCasUsesIntegerReplyTransportAndDecodesTheOutcome() throws Exception { + StringRedisTemplate template = mock(StringRedisTemplate.class); + RedisConnection connection = mock(RedisConnection.class); + RedisScriptingCommands scripting = mock(RedisScriptingCommands.class); + when(connection.scriptingCommands()).thenReturn(scripting); + when(scripting.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(scripting.evalSha(anyString(), eq(ReturnType.INTEGER), eq(1), any(byte[][].class))) + .thenReturn(1L); + when(template.execute(any(RedisCallback.class))) + .thenAnswer( + invocation -> ((RedisCallback) invocation.getArgument(0)).doInRedis(connection)); + + String key = + AccountGenerationProjectionRedisContract.KEY_PREFIX + + "c980fa44-619e-4ca4-8ad6-75b0538a66a3"; + String result = + CurrentGenerationProjectionRedisSupport.executeRegistered( + template, + AccountGenerationProjectionRedisContract.descriptor(), + key, + "ABSENT", + "", + "candidate"); + + assertThat(result).isEqualTo("APPLIED"); + verify(scripting).evalSha(anyString(), eq(ReturnType.INTEGER), eq(1), any(byte[][].class)); + } + + private static RedisScriptDescriptor.OutcomeSpec outcome( + String code, + RedisScriptDescriptor.OutcomeCategory category, + RedisScriptDescriptor.MutationEffect effect) { + return new RedisScriptDescriptor.OutcomeSpec(code, category, effect); + } + + private static String sha256(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static String sha1(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(value)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java new file mode 100644 index 0000000000..d72612c038 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java @@ -0,0 +1,638 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayReadback; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigester; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountMountedGameplayCredentialDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjection; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.stereotype.Component; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mock-based composition-unit proof; this class does not claim PostgreSQL or Redis execution. */ +class AccountGameplayCanonicalLoginOwnerTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_WORKLOAD = "spiffe://firemud/ns/other/sa/game-session-service"; + private static final long ACCOUNT_ROW_ID = 42L; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CONTEXT_ID = UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID OTHER_CONTEXT_ID = + UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"); + private static final UUID OPERATION_ID = UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"); + private static final UUID TOKEN_JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final long OTP_CHALLENGE_ID = 15L; + private static final Instant NOW = Instant.parse("2027-01-15T12:00:00Z"); + private static final String KEY_ID = "account-login-key-v1"; + private static final byte[] EXACT_JWT = + "header.payload.signature".getBytes(StandardCharsets.US_ASCII); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void absentAccountRunsDecoyVerificationButNeverIssuesOrActivates() { + Fixture fixture = new Fixture(); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)).thenReturn(Optional.empty()); + when(fixture.accounts.findByEmail("player@example.com")).thenReturn(Optional.empty()); + when(fixture.digestKeys.currentKey()).thenReturn(key(NOW.plusSeconds(600L))); + var verifier = mock(AccountGameplayCanonicalLoginOwner.CredentialVerifier.class); + + assertThatThrownBy(() -> fixture.owner.authenticate(request("secret"), WORKLOAD, verifier)) + .isInstanceOf(AuthenticationException.class) + .satisfies( + failure -> + assertThat(((AuthenticationException) failure).getCode()) + .isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS)); + + verify(verifier).verifyAbsentAccountCredential("secret"); + verify(verifier, never()).verify(any(), anyString()); + verify(verifier, never()).consumeOneTimeCredential(any(), any()); + verify(fixture.accounts, never()).findByIdForUpdate(any()); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + verifyNoInteractions(fixture.commitOwner, fixture.responseOwner); + } + + @Test + void privateGameplayIssuanceOwnersHaveNoComponentStereotypeRegistration() { + List> owners = + List.of( + AccountGameplayCanonicalLoginOwner.class, + AccountGameplayCredentialRequestDigester.class, + AccountGameplayDelegationAuthorityProjection.class, + AccountGameplayDelegationCommittedIssuanceOwner.class, + AccountGameplayDelegationIssuanceCommitService.class, + AccountGameplayDelegationRedisClient.class, + AccountGameplayDelegationRedisScriptContribution.class, + AccountGameplayDelegationResponseEnvelopeService.class, + AccountGameplayDelegationResponseRecoveryOwner.class, + AccountGameplayDelegationSigner.class, + AccountGameplayDelegationTokenRegistry.class, + AccountJwtJwksTrustedSource.class, + AccountMountedGameplayCredentialDigestKeySource.class, + AccountSelectedGameplayAuthorityProjection.class); + + for (Class owner : owners) { + assertThat(AnnotatedElementUtils.hasAnnotation(owner, Component.class)) + .as("%s must remain explicitly constructed in this source-only intake", owner.getName()) + .isFalse(); + } + } + + @Test + void exactRetryReturnsOriginalCredentialAndConsumesOtpOnlyInItsPendingTransaction() { + Fixture fixture = new Fixture(); + CredentialDigestKey key = key(NOW.plusSeconds(86_400L)); + when(fixture.digestKeys.currentKey()).thenReturn(key); + when(fixture.digestKeys.requireKey(KEY_ID)).thenReturn(key); + Account account = account(); + when(fixture.accounts.findByEmail("player@example.com")).thenReturn(Optional.of(account)); + when(fixture.accounts.findByIdForUpdate(ACCOUNT_ROW_ID)).thenReturn(Optional.of(account)); + + CanonicalGameplayLoginRequest request = request("246810"); + AccountGameplayCredentialRequestBinding binding = + AccountGameplayCredentialRequestDigester.bind( + key, request, "player@example.com", WORKLOAD, ACCOUNT_ID); + GameplayLoginReplayReadback newlyPending = mock(GameplayLoginReplayReadback.class); + when(newlyPending.created()).thenReturn(true); + GameplayLoginReplayReadback exactRetry = replay(binding); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty(), Optional.of(exactRetry)); + when(fixture.issuance.beginPendingForAccount( + eq(REQUEST_ID), eq(ACCOUNT_ID), eq(WORKLOAD), eq(CONTEXT_ID), eq(binding))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + fixture.transactions.events.add("pending-operation"); + return newlyPending; + }); + + AccountGameplayCanonicalLoginOwner.CredentialVerifier verifier = + new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public void verifyAbsentAccountCredential(String presentedCredential) { + throw new AssertionError("Absent-Account verifier must not run for this fixture"); + } + + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account candidate, String credential) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(candidate).isSameAs(account); + assertThat(credential).isEqualTo("246810"); + fixture.transactions.events.add("credential-verify"); + return new AccountGameplayCanonicalLoginOwner.CredentialVerification( + ACCOUNT_ID, OTP_CHALLENGE_ID); + } + + @Override + public void consumeOneTimeCredential( + Account candidate, + AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(candidate).isSameAs(account); + assertThat(verification.oneTimeChallengeId()).isEqualTo(OTP_CHALLENGE_ID); + fixture.transactions.events.add("otp-consume"); + } + }; + + RecoveredCredential response = recoveredCredential(); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + fixture.transactions.events.add("sign-registry-commit"); + return null; + }) + .when(fixture.commitOwner) + .commitPendingCandidate(REQUEST_ID); + when(fixture.responseOwner.recoverInitialLoginResponse( + eq(REQUEST_ID), eq(ACCOUNT_ID), any(CallerIdentity.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + fixture.transactions.events.add("activate-recover-response"); + return response; + }); + + InitialGameplayLoginResult first = fixture.owner.authenticate(request, WORKLOAD, verifier); + InitialGameplayLoginResult retry = fixture.owner.authenticate(request, WORKLOAD, verifier); + + assertThat(first.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(new String(first.compactJwtBytes(), StandardCharsets.US_ASCII)) + .isEqualTo("header.payload.signature"); + assertThat(retry.compactJwtBytes()).containsExactly(first.compactJwtBytes()); + assertThat(first.requestId()).isEqualTo(REQUEST_ID); + assertThat(first.callerContextId()).isEqualTo(CONTEXT_ID); + assertThat(first.authorityTupleCanonicalJson()) + .containsExactly(retry.authorityTupleCanonicalJson()); + assertThat(first.outboxCheckpointsCanonicalJson()) + .containsExactly(retry.outboxCheckpointsCanonicalJson()); + assertThat(first.outboxSourceEventEvidenceCanonicalJson()) + .containsExactly(retry.outboxSourceEventEvidenceCanonicalJson()); + assertThat(fixture.transactions.events) + .containsSubsequence( + "credential-verify", + "pending-operation", + "otp-consume", + "sql-commit", + "sign-registry-commit", + "activate-recover-response", + "sql-commit", + "sign-registry-commit", + "activate-recover-response"); + verify(fixture.issuance, times(1)) + .beginPendingForAccount(REQUEST_ID, ACCOUNT_ID, WORKLOAD, CONTEXT_ID, binding); + verify(fixture.commitOwner, times(2)).commitPendingCandidate(REQUEST_ID); + verify(fixture.responseOwner, times(2)) + .recoverInitialLoginResponse(eq(REQUEST_ID), eq(ACCOUNT_ID), any(CallerIdentity.class)); + } + + @Test + void changedCredentialEmailContextAndCallerConflictBeforeCredentialVerification() { + CanonicalGameplayLoginRequest original = request("original-secret"); + assertReplayConflict(request("changed-secret"), WORKLOAD); + assertReplayConflict( + new CanonicalGameplayLoginRequest( + REQUEST_ID, "other@example.com", original.credential(), original.sourceContext()), + WORKLOAD); + assertReplayConflict( + new CanonicalGameplayLoginRequest( + REQUEST_ID, + original.email(), + original.credential(), + new GameplayCredentialSourceContext(OTHER_CONTEXT_ID, "203.0.113.5", "TLS_TCP")), + WORKLOAD); + assertReplayConflict( + new CanonicalGameplayLoginRequest( + REQUEST_ID, + original.email(), + original.credential(), + new GameplayCredentialSourceContext(CONTEXT_ID, "203.0.113.6", "TLS_TCP")), + WORKLOAD); + assertReplayConflict(original, OTHER_WORKLOAD); + } + + @Test + void credentialDenialCommitsOtpAttemptEvidenceWithoutCreatingAnIssuance() { + Fixture fixture = new Fixture(); + CredentialDigestKey key = key(NOW.plusSeconds(86_400L)); + when(fixture.digestKeys.currentKey()).thenReturn(key); + stubNewLoginAccount(fixture); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + var verifier = + new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public void verifyAbsentAccountCredential(String presentedCredential) { + throw new AssertionError("Absent-Account verifier must not run for this fixture"); + } + + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String credential) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + fixture.transactions.events.add("otp-attempt-increment"); + throw new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials"); + } + + @Override + public void consumeOneTimeCredential( + Account account, + AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + throw new AssertionError("Denied credentials must not consume a challenge"); + } + }; + + assertThatThrownBy(() -> fixture.owner.authenticate(request("wrong-code"), WORKLOAD, verifier)) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Invalid credentials"); + + assertThat(fixture.transactions.events) + .containsSubsequence("otp-attempt-increment", "sql-commit") + .doesNotContain("sql-rollback"); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + verifyNoInteractions(fixture.commitOwner, fixture.responseOwner); + } + + @Test + void nonCredentialAuthenticationDenialsRollBackWithoutIssuanceOrCredentialRelease() { + assertNonCredentialAuthenticationFailureRollsBack(AuthenticationErrorCodes.ACCOUNT_LOCKED); + assertNonCredentialAuthenticationFailureRollsBack(AuthenticationErrorCodes.UNAVAILABLE); + } + + @Test + void invalidCallerAndUnavailableDigestKeysFailBeforeCredentialOwner() { + Fixture invalidCaller = new Fixture(); + var verifier = mock(AccountGameplayCanonicalLoginOwner.CredentialVerifier.class); + assertThatThrownBy(() -> invalidCaller.owner.authenticate(request("secret"), "", verifier)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(invalidCaller.issuance, invalidCaller.accounts, verifier); + + Fixture missingKey = new Fixture(); + stubNewLoginAccount(missingKey); + when(missingKey.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + when(missingKey.digestKeys.currentKey()).thenReturn(null); + assertUnavailableBeforeCredentialVerification(missingKey, verifier); + + Fixture shortRetention = new Fixture(); + stubNewLoginAccount(shortRetention); + when(shortRetention.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + when(shortRetention.digestKeys.currentKey()).thenReturn(key(NOW.plusSeconds(1L))); + assertUnavailableBeforeCredentialVerification(shortRetention, verifier); + + Fixture missingReplayKey = replayFixture(); + when(missingReplayKey.digestKeys.requireKey(KEY_ID)).thenReturn(null); + assertUnavailableReplayKey(missingReplayKey, verifier); + + Fixture shortReplayKey = replayFixture(); + when(shortReplayKey.digestKeys.requireKey(KEY_ID)).thenReturn(key(NOW.plusSeconds(1L))); + assertUnavailableReplayKey(shortReplayKey, verifier); + } + + @Test + void commitOrRecoveryFailureNeverReturnsTheCredential() { + Fixture commitFailure = replayFixture(); + doThrow(new IllegalStateException("private signer or registry detail")) + .when(commitFailure.commitOwner) + .commitPendingCandidate(REQUEST_ID); + assertThatThrownBy( + () -> + commitFailure.owner.authenticate( + request("original-secret"), WORKLOAD, unusedVerifier())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("private signer or registry detail"); + verify(commitFailure.responseOwner, never()).recoverInitialLoginResponse(any(), any(), any()); + + Fixture recoveryFailure = replayFixture(); + doThrow(new IllegalStateException("private recovery detail")) + .when(recoveryFailure.responseOwner) + .recoverInitialLoginResponse(any(), any(), any()); + assertThatThrownBy( + () -> + recoveryFailure.owner.authenticate( + request("original-secret"), WORKLOAD, unusedVerifier())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("private recovery detail"); + verify(recoveryFailure.commitOwner).commitPendingCandidate(REQUEST_ID); + verify(recoveryFailure.responseOwner) + .recoverInitialLoginResponse(eq(REQUEST_ID), eq(ACCOUNT_ID), any(CallerIdentity.class)); + } + + private static void assertReplayConflict( + CanonicalGameplayLoginRequest candidate, String callerWorkload) { + Fixture fixture = replayFixture(); + assertThatThrownBy( + () -> fixture.owner.authenticate(candidate, callerWorkload, unusedVerifier())) + .isInstanceOf(IdempotencyConflictException.class); + verify(fixture.commitOwner, never()).commitPendingCandidate(any()); + verifyNoInteractions(fixture.responseOwner, fixture.accounts); + } + + private static void assertNonCredentialAuthenticationFailureRollsBack(String errorCode) { + Fixture fixture = new Fixture(); + when(fixture.digestKeys.currentKey()).thenReturn(key(NOW.plusSeconds(86_400L))); + stubNewLoginAccount(fixture); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + var verifier = + new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public void verifyAbsentAccountCredential(String presentedCredential) { + throw new AssertionError("Absent-Account verifier must not run for this fixture"); + } + + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String credential) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + fixture.transactions.events.add("non-credential-denial"); + throw new AuthenticationException(errorCode, "Private authentication detail"); + } + + @Override + public void consumeOneTimeCredential( + Account account, + AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + throw new AssertionError("Denied authentication must not consume a challenge"); + } + }; + + AuthenticationException observed = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, + () -> fixture.owner.authenticate(request("secret"), WORKLOAD, verifier)); + assertThat(observed).hasMessage("Private authentication detail"); + assertThat(observed.getCode()).isEqualTo(errorCode); + + assertThat(fixture.transactions.events) + .containsSubsequence("non-credential-denial", "sql-rollback") + .doesNotContain("sql-commit"); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + verifyNoInteractions(fixture.commitOwner, fixture.responseOwner); + } + + private static void assertUnavailableBeforeCredentialVerification( + Fixture fixture, AccountGameplayCanonicalLoginOwner.CredentialVerifier verifier) { + assertThatThrownBy(() -> fixture.owner.authenticate(request("secret"), WORKLOAD, verifier)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account gameplay LOGIN is unavailable"); + verify(verifier, never()).verify(any(), any()); + verify(verifier, never()).consumeOneTimeCredential(any(), any()); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + verify(fixture.commitOwner, never()).commitPendingCandidate(any()); + verifyNoInteractions(fixture.responseOwner); + } + + private static void assertUnavailableReplayKey( + Fixture fixture, AccountGameplayCanonicalLoginOwner.CredentialVerifier verifier) { + assertThatThrownBy( + () -> fixture.owner.authenticate(request("original-secret"), WORKLOAD, verifier)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account gameplay LOGIN is unavailable"); + verify(verifier, never()).verify(any(), any()); + verify(verifier, never()).consumeOneTimeCredential(any(), any()); + verify(fixture.commitOwner, never()).commitPendingCandidate(any()); + verifyNoInteractions(fixture.responseOwner, fixture.accounts); + } + + private static Fixture replayFixture() { + Fixture fixture = new Fixture(); + CredentialDigestKey key = key(NOW.plusSeconds(86_400L)); + when(fixture.digestKeys.requireKey(KEY_ID)).thenReturn(key); + CanonicalGameplayLoginRequest request = request("original-secret"); + AccountGameplayCredentialRequestBinding binding = + AccountGameplayCredentialRequestDigester.bind( + key, request, "player@example.com", WORKLOAD, ACCOUNT_ID); + GameplayLoginReplayReadback replay = replay(binding); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.of(replay)); + return fixture; + } + + private static GameplayLoginReplayReadback replay( + AccountGameplayCredentialRequestBinding binding) { + GameplayLoginReplayReadback replay = mock(GameplayLoginReplayReadback.class); + when(replay.identity()) + .thenReturn( + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CONTEXT_ID, + binding, + "a".repeat(64), + TOKEN_JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.getEpochSecond() + + net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile + .MAX_TOKEN_LIFETIME_SECONDS)); + when(replay.state()).thenReturn(GameplayLoginReplayState.PENDING); + return replay; + } + + private static void stubNewLoginAccount(Fixture fixture) { + Account account = account(); + when(fixture.accounts.findByEmail("player@example.com")).thenReturn(Optional.of(account)); + when(fixture.accounts.findByIdForUpdate(ACCOUNT_ROW_ID)).thenReturn(Optional.of(account)); + } + + private static Account account() { + Account account = new Account(); + account.setId(ACCOUNT_ROW_ID); + account.setAccountUuid(ACCOUNT_ID); + account.setEmail("player@example.com"); + return account; + } + + private static RecoveredCredential recoveredCredential() { + RecoveredCredential response = mock(RecoveredCredential.class); + when(response.compactJwtBytes()).thenReturn(EXACT_JWT.clone()); + when(response.accountId()).thenReturn(ACCOUNT_ID); + when(response.tokenJti()).thenReturn(TOKEN_JTI); + when(response.tokenSha256()).thenReturn("a".repeat(64)); + when(response.profile()).thenReturn(GameSessionAccountDelegationProfile.PROFILE); + when(response.expiresAtEpochSecond()) + .thenReturn( + NOW.getEpochSecond() + + net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile + .MAX_TOKEN_LIFETIME_SECONDS); + when(response.authEvidenceBundle()).thenReturn(loginEvidenceBundle()); + return response; + } + + private static AccountAuthEvidenceBundle loginEvidenceBundle() { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new AccountAuthEvidenceBundle.OwnerEvaluation( + new AccountAuthEvidenceBundle.BundleReference("1", "1", "1", "12345678"), + "b".repeat(64), + "c".repeat(64), + ACCOUNT_ID, + new AccountAuthEvidenceBundle.OperationIdentity( + OPERATION_ID, REQUEST_ID, "d".repeat(64), WORKLOAD, CONTEXT_ID, ACCOUNT_ID), + new AccountAuthEvidenceBundle.TokenIdentity( + TOKEN_JTI, + 1L, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.getEpochSecond() + + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 1L, + new AccountAuthEvidenceBundle.AuthoritySourceVersions(1L, 1L, 1L), + new AccountAuthEvidenceBundle.AccountIdentitySource( + 42L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, 42L), + List.of( + new AccountAuthEvidenceBundle.OutboxCheckpoint(accountStream, 0L, null, null), + new AccountAuthEvidenceBundle.OutboxCheckpoint( + issuerStream, 1L, "issuer-event-1", "sha256:" + "e".repeat(64))))); + } + + private static CanonicalGameplayLoginRequest request(String credential) { + return new CanonicalGameplayLoginRequest( + REQUEST_ID, + "Player@Example.com", + credential, + new GameplayCredentialSourceContext(CONTEXT_ID, "203.0.113.5", "TLS_TCP")); + } + + private static CredentialDigestKey key(Instant retainedUntil) { + return new CredentialDigestKey( + KEY_ID, new SecretKeySpec(new byte[32], "HmacSHA256"), retainedUntil); + } + + private static AccountGameplayCanonicalLoginOwner.CredentialVerifier unusedVerifier() { + return new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { + @Override + public void verifyAbsentAccountCredential(String presentedCredential) { + throw new AssertionError("Absent-Account verifier must not run for this fixture"); + } + + @Override + public AccountGameplayCanonicalLoginOwner.CredentialVerification verify( + Account account, String presentedCredential) { + throw new AssertionError("Credential owner must not run for a denied replay"); + } + + @Override + public void consumeOneTimeCredential( + Account account, AccountGameplayCanonicalLoginOwner.CredentialVerification verification) { + throw new AssertionError("Credential owner must not consume a denied replay"); + } + }; + } + + private static final class Fixture { + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + private final AccountGameplayCredentialRequestDigestKeySource digestKeys = + mock(AccountGameplayCredentialRequestDigestKeySource.class); + private final AccountGameplayDelegationIssuanceCommitService commitOwner = + mock(AccountGameplayDelegationIssuanceCommitService.class); + private final AccountGameplayDelegationResponseRecoveryOwner responseOwner = + mock(AccountGameplayDelegationResponseRecoveryOwner.class); + private final RecordingTransactionManager transactions = new RecordingTransactionManager(); + private final AccountGameplayCanonicalLoginOwner owner = + new AccountGameplayCanonicalLoginOwner( + accounts, + issuance, + digestKeys, + commitOwner, + responseOwner, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final List events = new ArrayList<>(); + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Unexpected ambient Account transaction"); + } + events.add("sql-begin"); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("sql-commit"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("sql-rollback"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java new file mode 100644 index 0000000000..1ee19275d8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java @@ -0,0 +1,188 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigester; +import org.junit.jupiter.api.Test; + +class AccountGameplayCredentialRequestDigesterTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("674cb504-8f4c-4d06-86c6-7b72f79cae74"); + private static final Instant RETAINED_UNTIL = Instant.parse("2027-01-16T12:00:00Z"); + private static final CredentialDigestKey KEY = key("account-login-key-v1", new byte[32]); + private static final CanonicalGameplayLoginRequest REQUEST = + request( + UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"), + "Player@Example.com", + "one-time-secret", + new GameplayCredentialSourceContext( + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"), "203.0.113.5", "TLS_TCP")); + + @Test + void bindingIsDeterministicVersionedAndBindsTheExactCredentialOperation() { + AccountGameplayCredentialRequestBinding first = + bind(KEY, REQUEST, "player@example.com", WORKLOAD, ACCOUNT_ID); + AccountGameplayCredentialRequestBinding retry = + bind(KEY, REQUEST, "player@example.com", WORKLOAD, ACCOUNT_ID); + + assertThat(first).isEqualTo(retry); + assertThat(first.digestSchemaVersion()).isEqualTo(1); + assertThat(first.digestKeyId()).isEqualTo(KEY.keyId()); + assertThat(first.credentialRequestDigest()).matches("[0-9a-f]{64}"); + assertThat(AccountGameplayCredentialRequestDigester.matches(first, retry)).isTrue(); + assertThat(REQUEST.toString()).doesNotContain("one-time-secret"); + assertThat(REQUEST.sourceContext().toString()).doesNotContain("203.0.113.5"); + assertThat(first.toString()).doesNotContain(first.credentialRequestDigest()); + } + + @Test + void bindingChangesForEveryCredentialCallerAndSourceContextDimension() { + AccountGameplayCredentialRequestBinding baseline = + bind(KEY, REQUEST, "player@example.com", WORKLOAD, ACCOUNT_ID); + + assertDifferent( + baseline, + bind( + KEY, + request( + UUID.fromString("58102ea4-9245-4ddc-a68c-3ff41dcf96af"), + REQUEST.email(), + REQUEST.credential(), + REQUEST.sourceContext()), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + request( + REQUEST.requestId(), REQUEST.email(), "changed-secret", REQUEST.sourceContext()), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent(baseline, bind(KEY, REQUEST, "other@example.com", WORKLOAD, ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + REQUEST, + "player@example.com", + "spiffe://firemud/ns/other/sa/game-session-service", + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + request( + REQUEST.requestId(), + REQUEST.email(), + REQUEST.credential(), + new GameplayCredentialSourceContext( + UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"), + "203.0.113.5", + "TLS_TCP")), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + request( + REQUEST.requestId(), + REQUEST.email(), + REQUEST.credential(), + new GameplayCredentialSourceContext( + REQUEST.sourceContext().contextId(), "203.0.113.6", "TLS_TCP")), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + KEY, + request( + REQUEST.requestId(), + REQUEST.email(), + REQUEST.credential(), + new GameplayCredentialSourceContext( + REQUEST.sourceContext().contextId(), "203.0.113.5", "TLS_WEBSOCKET")), + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent(baseline, bind(KEY, REQUEST, "player@example.com", WORKLOAD, OTHER_ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + key("account-login-key-v2", new byte[32]), + REQUEST, + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + assertDifferent( + baseline, + bind( + key("account-login-key-v1", changedKeyMaterial()), + REQUEST, + "player@example.com", + WORKLOAD, + ACCOUNT_ID)); + } + + @Test + void rejectsUnverifiedOrNonGameSessionCallerIdentity() { + assertThatThrownBy(() -> bind(KEY, REQUEST, "player@example.com", null, ACCOUNT_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + bind( + KEY, + REQUEST, + "player@example.com", + "spiffe://firemud/ns/test/sa/tcp-proxy-service", + ACCOUNT_ID)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertDifferent( + AccountGameplayCredentialRequestBinding expected, + AccountGameplayCredentialRequestBinding candidate) { + assertThat(AccountGameplayCredentialRequestDigester.matches(expected, candidate)).isFalse(); + } + + private static AccountGameplayCredentialRequestBinding bind( + CredentialDigestKey key, + CanonicalGameplayLoginRequest request, + String normalizedEmail, + String callerWorkload, + UUID accountId) { + return AccountGameplayCredentialRequestDigester.bind( + key, request, normalizedEmail, callerWorkload, accountId); + } + + private static CanonicalGameplayLoginRequest request( + UUID requestId, String email, String credential, GameplayCredentialSourceContext source) { + return new CanonicalGameplayLoginRequest(requestId, email, credential, source); + } + + private static CredentialDigestKey key(String keyId, byte[] bytes) { + return new CredentialDigestKey(keyId, new SecretKeySpec(bytes, "HmacSHA256"), RETAINED_UNTIL); + } + + private static byte[] changedKeyMaterial() { + byte[] bytes = new byte[32]; + bytes[0] = 1; + return bytes; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java index b3e2c49bf0..9da76a75e1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java @@ -2,19 +2,42 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import tools.jackson.databind.json.JsonMapper; class AccountGameplayDelegationAuthorityProjectionTest { @Test @@ -103,4 +126,1166 @@ private static IssuerAccountSourceSnapshot sequenceZeroSnapshot(UUID accountId) 20L); return new IssuerAccountSourceSnapshot(issuer, account, fence); } + + @Nested + class DonorOwnerReadRegressions { + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void selectedOwnerObservationUsesActualCompositePairReceiptAndIndependentVersion() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenReturn(fixture.values); + var observation = fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant); + assertThat(observation.admitting()).isFalse(); + assertThat(observation.membershipVersion()).isEqualTo(2L); + assertThat(observation.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(java.util.Arrays.deepEquals(observation.canonicalProjections(), fixture.values)) + .isTrue(); + org.mockito.Mockito.verify(fixture.generations, org.mockito.Mockito.times(2)) + .readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + ACCOUNT_ID, + List.of(fixture.tenant), + List.of(fixture.tenant)); + org.mockito.Mockito.verify(fixture.tenantSources, org.mockito.Mockito.times(2)) + .readCurrentByTenant(fixture.tenant); + } + + @Test + void selectedIndependentVersionMismatchDeniesBeforeRedisEvenWhenGenerationMatches() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.member.getMembershipVersion()).thenReturn(3L); + assertThatThrownBy( + () -> fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verifyNoInteractions(fixture.redis); + } + + @Test + void selectedSourceChangedAfterExactRedisReadbackNeverReturnsObservation() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenAnswer( + invocation -> { + when(fixture.member.getMembershipVersion()).thenReturn(3L); + return fixture.values; + }); + assertThatThrownBy( + () -> fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verify(fixture.memberships, org.mockito.Mockito.times(2)) + .findFreshMembershipForUpdate(ACCOUNT_ID, fixture.tenant); + } + + @Test + void selectedPublicationRejectsMissingMembershipPrefixBeforeMembershipCas() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.publishAuthorityProjections( + eq(ACCOUNT_ID), any(byte[].class), any(byte[].class))) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + when(fixture.redis.readSelectedAuthorityHeads(ACCOUNT_ID, fixture.tenant)) + .thenReturn( + new byte[][] {null, null}, new byte[][] {fixture.values[2], fixture.values[3]}); + when(fixture.outbox.findEventPage( + "account:auth-authority:v1:membership/" + ACCOUNT_ID + "/" + fixture.tenant, 0L, 1L)) + .thenReturn(List.of()); + + assertThatThrownBy( + () -> fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verify(fixture.redis, org.mockito.Mockito.times(1)) + .publishSelectedAuthorityEventPage( + any(UUID.class), + any(UUID.class), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.nullable(byte[].class), + any(List.class)); + } + + @Test + void firstSelectedPublicationReplaysRetainedPrefixThroughCapturedHeadAboveOne() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.publishAuthorityProjections( + eq(ACCOUNT_ID), any(byte[].class), any(byte[].class))) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + + var eventOne = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.member( + ACCOUNT_ID, fixture.tenant, "1", "2", "1"); + var eventTwo = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.member( + ACCOUNT_ID, fixture.tenant, "2", "3", "1"); + String stream = eventOne.outboxStreamKey(); + var rowOne = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event( + stream, + eventOne.requestId(), + 1L, + eventOne.eventId(), + eventOne.eventDigest(), + eventOne.canonicalJsonUtf8()); + var rowTwo = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event( + stream, + eventTwo.requestId(), + 2L, + eventTwo.eventId(), + eventTwo.eventDigest(), + eventTwo.canonicalJsonUtf8()); + when(fixture.member.getMembershipVersion()).thenReturn(3L); + when(fixture.outbox.readCheckpoint(stream)) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityOutboxRepository.Checkpoint( + stream, 2L, eventTwo.eventId(), eventTwo.eventDigest()))); + when(fixture.outbox.findEvent(stream, 2L)).thenReturn(Optional.of(rowTwo)); + when(fixture.outbox.findEventPage(stream, 0L, 2L)).thenReturn(List.of(rowOne, rowTwo)); + var tenantEvent = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.tenant(fixture.tenant); + var provenance = + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvent.sourceEvidence().operationId(), + tenantEvent.sourceEvidence().evidenceDigest()); + when(fixture.pairs.readForUpdate(ACCOUNT_ID, fixture.tenant)) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.PairAuthority( + ACCOUNT_ID, + fixture.tenant, + provenance, + true, + 3L, + 1L, + 2L, + eventTwo.eventId(), + eventTwo.eventDigest(), + false))); + + byte[] currentMembership = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.membershipBytes( + ACCOUNT_ID, fixture.tenant, "2", "3", "1"); + when(fixture.redis.readSelectedAuthorityHeads(ACCOUNT_ID, fixture.tenant)) + .thenReturn( + new byte[][] {null, null}, new byte[][] {fixture.values[2], currentMembership}); + + fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant); + + org.mockito.ArgumentCaptor prior = org.mockito.ArgumentCaptor.forClass(byte[].class); + @SuppressWarnings("unchecked") + org.mockito.ArgumentCaptor> candidates = + (org.mockito.ArgumentCaptor>) + (org.mockito.ArgumentCaptor) org.mockito.ArgumentCaptor.forClass(List.class); + org.mockito.Mockito.verify(fixture.redis) + .publishSelectedAuthorityEventPage( + eq(ACCOUNT_ID), eq(fixture.tenant), eq(false), prior.capture(), candidates.capture()); + assertThat(prior.getValue()).isNull(); + assertThat(candidates.getValue()) + .containsExactly( + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.membershipBytes( + ACCOUNT_ID, fixture.tenant, "1", "2", "1"), + currentMembership); + } + + @Test + void selectedPublicationRejectsInterpublicationGapInRetainedPages() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.publishAuthorityProjections( + eq(ACCOUNT_ID), any(byte[].class), any(byte[].class))) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + when(fixture.redis.readSelectedAuthorityHeads(ACCOUNT_ID, fixture.tenant)) + .thenReturn(new byte[][] {null, null}); + + var eventOne = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.member( + ACCOUNT_ID, fixture.tenant, "1", "2", "1"); + var eventThree = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.member( + ACCOUNT_ID, fixture.tenant, "3", "4", "1"); + String stream = eventOne.outboxStreamKey(); + var rowOne = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event( + stream, + eventOne.requestId(), + 1L, + eventOne.eventId(), + eventOne.eventDigest(), + eventOne.canonicalJsonUtf8()); + var rowThree = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event( + stream, + eventThree.requestId(), + 3L, + eventThree.eventId(), + eventThree.eventDigest(), + eventThree.canonicalJsonUtf8()); + when(fixture.member.getMembershipVersion()).thenReturn(4L); + when(fixture.outbox.readCheckpoint(stream)) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityOutboxRepository.Checkpoint( + stream, 3L, eventThree.eventId(), eventThree.eventDigest()))); + when(fixture.outbox.findEvent(stream, 3L)).thenReturn(Optional.of(rowThree)); + when(fixture.outbox.findEventPage(stream, 0L, 3L)).thenReturn(List.of(rowOne, rowThree)); + var tenantEvent = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.tenant(fixture.tenant); + var provenance = + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvent.sourceEvidence().operationId(), + tenantEvent.sourceEvidence().evidenceDigest()); + when(fixture.pairs.readForUpdate(ACCOUNT_ID, fixture.tenant)) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.PairAuthority( + ACCOUNT_ID, + fixture.tenant, + provenance, + true, + 4L, + 1L, + 3L, + eventThree.eventId(), + eventThree.eventDigest(), + false))); + + assertThatThrownBy( + () -> fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verify(fixture.redis, org.mockito.Mockito.times(1)) + .publishSelectedAuthorityEventPage( + eq(ACCOUNT_ID), + eq(fixture.tenant), + eq(true), + org.mockito.ArgumentMatchers.nullable(byte[].class), + any(List.class)); + org.mockito.Mockito.verify(fixture.redis, org.mockito.Mockito.never()) + .publishSelectedAuthorityEventPage( + eq(ACCOUNT_ID), + eq(fixture.tenant), + eq(false), + org.mockito.ArgumentMatchers.nullable(byte[].class), + any(List.class)); + } + + @Test + void exactCachedSelectedHeadsSkipRetainedPrefixReadsAndCas() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.publishAuthorityProjections( + eq(ACCOUNT_ID), any(byte[].class), any(byte[].class))) + .thenReturn( + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + when(fixture.redis.readSelectedAuthorityHeads(ACCOUNT_ID, fixture.tenant)) + .thenReturn( + new byte[][] {fixture.values[2], fixture.values[3]}, + new byte[][] {fixture.values[2], fixture.values[3]}); + + var result = fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant); + + assertThat(result.publicationOutcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); + org.mockito.Mockito.verify(fixture.outbox, org.mockito.Mockito.never()) + .findEventPage( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(fixture.redis, org.mockito.Mockito.never()) + .publishSelectedAuthorityEventPage( + any(UUID.class), + any(UUID.class), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.nullable(byte[].class), + any(List.class)); + } + + @Test + void selectedPublicationRejectsCachedHeadThatDiffersFromRetainedEvent() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.publishAuthorityProjections( + eq(ACCOUNT_ID), any(byte[].class), any(byte[].class))) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + byte[] conflictingHead = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.membershipBytes( + ACCOUNT_ID, fixture.tenant, "1", "3", "1"); + when(fixture.redis.readSelectedAuthorityHeads(ACCOUNT_ID, fixture.tenant)) + .thenReturn(new byte[][] {fixture.values[2], conflictingHead}); + + assertThatThrownBy( + () -> fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verify(fixture.outbox, org.mockito.Mockito.never()) + .findEventPage( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(fixture.redis, org.mockito.Mockito.never()) + .publishSelectedAuthorityEventPage( + any(UUID.class), + any(UUID.class), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.nullable(byte[].class), + any(List.class)); + } + + @Test + void selectedPublicationContinuesBoundedPagesAcross128RetainedEvents() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.publishAuthorityProjections( + eq(ACCOUNT_ID), any(byte[].class), any(byte[].class))) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + String stream = "account:auth-authority:v1:membership/" + ACCOUNT_ID + "/" + fixture.tenant; + java.util.List< + net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event> + firstPage = new java.util.ArrayList<>(); + java.util.List< + net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event> + secondPage = new java.util.ArrayList<>(); + net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec + .MembershipEvent + lastEvent = null; + for (long sequence = 1L; sequence <= 130L; sequence++) { + var event = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.member( + ACCOUNT_ID, + fixture.tenant, + Long.toString(sequence), + Long.toString(sequence + 1L), + "1"); + var row = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event( + stream, + event.requestId(), + sequence, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()); + if (sequence <= 128L) firstPage.add(row); + else secondPage.add(row); + lastEvent = event; + } + when(fixture.member.getMembershipVersion()).thenReturn(131L); + when(fixture.outbox.readCheckpoint(stream)) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityOutboxRepository.Checkpoint( + stream, 130L, lastEvent.eventId(), lastEvent.eventDigest()))); + var lastRow = secondPage.getLast(); + when(fixture.outbox.findEvent(stream, 130L)).thenReturn(Optional.of(lastRow)); + when(fixture.outbox.findEventPage(stream, 0L, 130L)).thenReturn(firstPage); + when(fixture.outbox.findEventPage(stream, 128L, 130L)).thenReturn(secondPage); + var tenantEvent = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.tenant(fixture.tenant); + var provenance = + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvent.sourceEvidence().operationId(), + tenantEvent.sourceEvidence().evidenceDigest()); + when(fixture.pairs.readForUpdate(ACCOUNT_ID, fixture.tenant)) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.PairAuthority( + ACCOUNT_ID, + fixture.tenant, + provenance, + true, + 131L, + 1L, + 130L, + lastEvent.eventId(), + lastEvent.eventDigest(), + false))); + byte[] currentMembership = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.membershipBytes( + ACCOUNT_ID, fixture.tenant, "130", "131", "1"); + when(fixture.redis.readSelectedAuthorityHeads(ACCOUNT_ID, fixture.tenant)) + .thenReturn( + new byte[][] {null, null}, new byte[][] {fixture.values[2], currentMembership}); + + var result = fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant); + + assertThat(result.publicationOutcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + org.mockito.Mockito.verify(fixture.outbox).findEventPage(stream, 0L, 130L); + org.mockito.Mockito.verify(fixture.outbox).findEventPage(stream, 128L, 130L); + @SuppressWarnings("unchecked") + org.mockito.ArgumentCaptor> pageCaptor = + (org.mockito.ArgumentCaptor>) + (org.mockito.ArgumentCaptor) org.mockito.ArgumentCaptor.forClass(List.class); + org.mockito.Mockito.verify(fixture.redis, org.mockito.Mockito.times(2)) + .publishSelectedAuthorityEventPage( + eq(ACCOUNT_ID), + eq(fixture.tenant), + eq(false), + org.mockito.ArgumentMatchers.nullable(byte[].class), + pageCaptor.capture()); + assertThat(pageCaptor.getAllValues().stream().map(List::size).toList()) + .containsExactly(128, 2); + } + + @Test + void selectedPublicationRejectsTamperedOrOutOfOrderRetainedRows() { + for (boolean outOfOrder : List.of(false, true)) { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.publishAuthorityProjections( + eq(ACCOUNT_ID), any(byte[].class), any(byte[].class))) + .thenReturn( + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + when(fixture.redis.readSelectedAuthorityHeads(ACCOUNT_ID, fixture.tenant)) + .thenReturn(new byte[][] {null, null}); + var event = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.member( + ACCOUNT_ID, fixture.tenant, "1", "2", "1"); + var row = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event( + event.outboxStreamKey(), + event.requestId(), + outOfOrder ? 2L : 1L, + event.eventId(), + outOfOrder ? event.eventDigest() : event.eventDigest() + "-tampered", + event.canonicalJsonUtf8()); + when(fixture.outbox.findEventPage(event.outboxStreamKey(), 0L, 1L)) + .thenReturn(List.of(row)); + + assertThatThrownBy( + () -> fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verify(fixture.redis, org.mockito.Mockito.times(1)) + .publishSelectedAuthorityEventPage( + any(UUID.class), + any(UUID.class), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.nullable(byte[].class), + any(List.class)); + } + } + + @Test + void selectedPublicationRereadsOwnerCurrentnessAfterCasReplay() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.publishAuthorityProjections( + eq(ACCOUNT_ID), any(byte[].class), any(byte[].class))) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + when(fixture.redis.readSelectedAuthorityHeads(ACCOUNT_ID, fixture.tenant)) + .thenReturn( + new byte[][] {null, null}, new byte[][] {fixture.values[2], fixture.values[3]}); + when(fixture.redis.publishSelectedAuthorityEventPage( + any(UUID.class), + any(UUID.class), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.nullable(byte[].class), + any(List.class))) + .thenAnswer( + invocation -> { + @SuppressWarnings("unchecked") + List candidates = invocation.getArgument(4); + String candidate = new String(candidates.getLast(), StandardCharsets.UTF_8); + if (candidate.contains("\"accountId\"")) { + when(fixture.member.getMembershipVersion()).thenReturn(3L); + } + return AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED; + }); + + assertThatThrownBy( + () -> fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verify(fixture.redis, org.mockito.Mockito.times(2)) + .publishSelectedAuthorityEventPage( + any(UUID.class), + any(UUID.class), + org.mockito.ArgumentMatchers.anyBoolean(), + org.mockito.ArgumentMatchers.nullable(byte[].class), + any(List.class)); + } + + @Test + void selectedReachableMissingProjectionNeverUsesSqlAsRedisProof() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenReturn(new byte[][] {fixture.values[0], fixture.values[1], fixture.values[2], null}); + assertThatThrownBy( + () -> fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + } + + @Test + void historicalActiveMembershipRemainsValidAfterProvedClosedAccountSecurityChange() { + SelectedOwnerFixture fixture = + new SelectedOwnerFixture( + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT, + 1L, + 2L); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenReturn(fixture.values); + var observation = fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant); + Map current = decodeFields(observation.canonicalCurrentAuthorityTuple()); + assertThat(current.get("issuerAuthGeneration")).isEqualTo("1"); + assertThat(current.get("accountAuthorityGeneration")).isEqualTo("2"); + assertThat(current.get("accountSecurityCutoff")) + .isEqualTo( + Map.of( + "accountAuthorityGeneration", + "2", + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT_ID, + "outboxSequence", + "1")); + assertThat(current.get("tenantBillingCutoff")) + .isEqualTo( + Map.of( + fixture.tenant.toString(), + Map.of( + "tenantAuthorityGeneration", + "2", + "tenantBillingSequence", + "1", + "outboxStreamKey", + "account:tenant-entitlement:v1:tenant/" + fixture.tenant, + "outboxSequence", + "1"))); + assertThat(observation.issuanceFence()).isEqualTo(2L); + assertThat(observation.membershipVersion()).isEqualTo(2L); + assertThat(observation.membershipAuthorityGeneration()).isEqualTo(1L); + byte[] unchangedMember = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.membershipBytes( + ACCOUNT_ID, fixture.tenant, "1", "2", "1"); + assertThat(observation.canonicalProjections()[3]).containsExactly(unchangedMember); + assertThat(new String(unchangedMember, java.nio.charset.StandardCharsets.UTF_8)) + .contains("\\\"accountAuthorityGeneration\\\":\\\"1\\\""); + assertThat(observation.admitting()).isFalse(); + } + + @Test + void identicalUuidInIndependentAccountAndTenantDomainsIsNotRejected() { + SelectedOwnerFixture fixture = new SelectedOwnerFixture(ACCOUNT_ID, 1L, 1L); + when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) + .thenReturn(fixture.values); + assertThat(fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant).admitting()) + .isFalse(); + } + + @Test + void currentContradictoryCompositeOrUnsupportedClosedAccountSourceStillDenies() { + SelectedOwnerFixture contradictory = new SelectedOwnerFixture(); + when(contradictory.sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn( + snapshot(1L, 2L)); // The actual composite still proves 1, not this claimed head. + assertThatThrownBy( + () -> + contradictory.projection.observeSelectedCurrent(ACCOUNT_ID, contradictory.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verifyNoInteractions(contradictory.redis); + SelectedOwnerFixture unsupported = + new SelectedOwnerFixture( + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT, + 1L, + 2L); + var advanced = snapshot(1L, 2L); + when(unsupported.sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn( + new IssuerAccountSourceSnapshot( + advanced.issuer(), advanced.account(), advanced.issuanceFence())); + assertThatThrownBy( + () -> unsupported.projection.observeSelectedCurrent(ACCOUNT_ID, unsupported.tenant)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + org.mockito.Mockito.verifyNoInteractions(unsupported.redis); + } + + private static final class SelectedOwnerFixture { + final UUID tenant; + final AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + final net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + generations = + mock( + net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.class); + final net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository + memberships = + mock( + net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository + .class); + final net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository + pairs = + mock( + net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.class); + final net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + outbox = + mock( + net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .class); + final net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository + tenantSources = + mock( + net.firedevops.firemud.accountservice.repository + .AccountTenantAuthorityEventRepository.class); + final net.firedevops.firemud.accountservice.entity.AccountTenantMembership member = + mock(net.firedevops.firemud.accountservice.entity.AccountTenantMembership.class); + final AccountGameplayDelegationRedisClient redis = + mock(AccountGameplayDelegationRedisClient.class); + final AccountGameplayDelegationAuthorityProjection projection; + final byte[][] values; + + SelectedOwnerFixture() { + this( + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT, + 1L, + 1L); + } + + SelectedOwnerFixture(UUID tenant, long issuerGeneration, long accountGeneration) { + this.tenant = tenant; + var source = snapshot(issuerGeneration, accountGeneration); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(source); + var composite = + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.CompositeSnapshot( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + source.issuer().scope(), issuerGeneration, issuerGeneration, null), + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + source.account().scope(), + accountGeneration, + accountGeneration, + source.issuanceFence()), + List.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + AuthorityScope.tenant(tenant), 2L, 2L, null)), + List.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + AuthorityScope.membership(ACCOUNT_ID, tenant), 1L, 1L, null)), + source.issuanceFence()); + when(generations.readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + ACCOUNT_ID, + List.of(tenant), + List.of(tenant))) + .thenReturn(composite); + var tenantEvent = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.tenant(tenant); + when(tenantSources.readCurrentByTenant(tenant)).thenReturn(tenantEvent); + var event = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.member( + ACCOUNT_ID, tenant, "1", "2", "1"); + var provenance = + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.TenantProvenanceKind + .FRESH_GAME_DESIGN, + tenantEvent.sourceEvidence().operationId(), + tenantEvent.sourceEvidence().evidenceDigest()); + var pair = + new net.firedevops.firemud.accountservice.repository + .AccountMembershipPairAuthorityRepository.PairAuthority( + ACCOUNT_ID, + tenant, + provenance, + true, + 2L, + 1L, + 1L, + event.eventId(), + event.eventDigest(), + false); + when(pairs.readForUpdate(ACCOUNT_ID, tenant)).thenReturn(Optional.of(pair)); + when(memberships.findFreshMembershipForUpdate(ACCOUNT_ID, tenant)) + .thenReturn(Optional.of(member)); + when(member.getMembershipVersion()).thenReturn(2L); + when(member.getMembershipAuthorityGeneration()).thenReturn(1L); + when(member.getLifecycleState()).thenReturn("ACTIVE"); + when(member.isGameplayAdmissionAllowed()).thenReturn(true); + when(outbox.readCheckpoint(event.outboxStreamKey())) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityOutboxRepository.Checkpoint( + event.outboxStreamKey(), 1L, event.eventId(), event.eventDigest()))); + var memberRow = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event( + event.outboxStreamKey(), + event.requestId(), + 1L, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()); + when(outbox.findEvent(event.outboxStreamKey(), 1L)).thenReturn(Optional.of(memberRow)); + when(outbox.findEventPage(event.outboxStreamKey(), 0L, 1L)).thenReturn(List.of(memberRow)); + when(outbox.readCheckpoint(tenantEvent.outboxStreamKey())) + .thenReturn( + Optional.of( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityOutboxRepository.Checkpoint( + tenantEvent.outboxStreamKey(), + tenantEvent.outboxSequence(), + tenantEvent.eventId().toString(), + tenantEvent.eventDigest()))); + var tenantRow = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .Event( + tenantEvent.outboxStreamKey(), + tenantEvent.requestId().toString(), + tenantEvent.outboxSequence(), + tenantEvent.eventId().toString(), + tenantEvent.eventDigest(), + tenantEvent.payload()); + when(outbox.findEvent(tenantEvent.outboxStreamKey(), tenantEvent.outboxSequence())) + .thenReturn(Optional.of(tenantRow)); + when(outbox.findEventPage(tenantEvent.outboxStreamKey(), 0L, tenantEvent.outboxSequence())) + .thenReturn(List.of(tenantRow)); + values = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.selected( + canonicalProjectionPairForFixture(source), ACCOUNT_ID, tenant); + projection = + new AccountGameplayDelegationAuthorityProjection( + sources, + transactionManager(null), + redis, + generations, + memberships, + pairs, + outbox, + tenantSources); + } + + private static byte[][] canonicalProjectionPairForFixture( + IssuerAccountSourceSnapshot source) { + return AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + } + } + + @Test + void canonicalIssuerBaselineRejectsGenericAliasesAndAdvancedLocalSource() throws Exception { + byte[] issuer = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot(1, 1))[0]; + var canonical = + net.firedevops.firemud.accountservice.service.IssuerGenerationProjection.parse( + new String(issuer, java.nio.charset.StandardCharsets.UTF_8)); + assertThat(canonical.lastAppliedSourceOutboxSequence()).isEqualTo("0"); + assertThat(decodeFields(issuer)) + .doesNotContainKeys("schema", "scope", "digest", "checkpoint"); + Map altered = new LinkedHashMap<>(decodeFields(issuer)); + altered.put("schema", "account-auth-authority-projection/v1"); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsBytes(altered), + "issuer", + GameSessionAccountDelegationProfile.ISSUER)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair( + snapshot(2, 1))) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + + @Test + void freshAccountUsesOnlyCanonicalClosedAccountFields() { + byte[][] pair = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot(1, 1)); + Map fields = decodeFields(pair[1]); + assertThat(fields.get("schemaVersion")).isEqualTo(AccountGenerationProjection.SCHEMA_VERSION); + assertThat(fields.get("outboxSequence")).isEqualTo("0"); + assertThat(fields).doesNotContainKeys("sourceEvent", "issuanceFence", "digest", "generation"); + assertThat( + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + pair[1], "account", ACCOUNT_ID.toString()) + .generation()) + .isEqualTo(1L); + } + + @Test + void advancedAccountRetainsCompleteClosedSourceEventAndExactBytes() { + var source = snapshot(1, Long.MAX_VALUE); + byte[][] pair = AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + assertThat(new String(pair[1], java.nio.charset.StandardCharsets.UTF_8)) + .isEqualTo(source.canonicalAccountProjection().toJson()); + var decoded = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + pair[1], "account", ACCOUNT_ID.toString()); + assertThat(decoded.generationValue()).isEqualTo(BigInteger.valueOf(Long.MAX_VALUE)); + assertThat(decodeFields(pair[1]).get("sourceEvent")) + .isEqualTo(source.canonicalAccountProjection().sourceEvent().orElseThrow()); + } + + @Test + void rejectsLegacyAccountSchemaUnknownFieldsWrongIdentityAndMissingEvent() throws Exception { + byte[] account = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot(1, 11))[1]; + for (String field : List.of("issuanceFence", "digest", "generation")) { + Map altered = new LinkedHashMap<>(decodeFields(account)); + altered.put(field, "1"); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsString(altered) + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + "account", + ACCOUNT_ID.toString())) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + Map missing = new LinkedHashMap<>(decodeFields(account)); + missing.remove("sourceEvent"); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsString(missing) + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + "account", + ACCOUNT_ID.toString())) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + assertThatThrownBy( + () -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + account, "account", UUID.randomUUID().toString())) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + + @Test + void advancedSnapshotWithoutExactSourcePayloadFailsClosed() { + var complete = snapshot(1, 11); + var missing = + new IssuerAccountSourceSnapshot( + complete.issuer(), complete.account(), complete.issuanceFence()); + assertThatThrownBy( + () -> AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(missing)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); + } + + @Test + void canonicalAccountDecodePreservesArbitraryPrecisionCounters() throws Exception { + var base = snapshot(1, 11).canonicalAccountProjection(); + Map event = + new LinkedHashMap<>( + JSON.readValue( + base.sourceEvent().orElseThrow(), + new tools.jackson.core.type.TypeReference>() {})); + String generation = "92233720368547758081234567890"; + String sequence = "92233720368547758081234567889"; + event.remove("eventDigest"); + event.put("accountAuthorityGeneration", generation); + event.put("sourceVersion", generation); + event.put("outboxSequence", sequence); + event.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + base.outboxStreamKey(), + "outboxSequence", + sequence)); + var projection = + new AccountGenerationProjection( + ACCOUNT_ID.toString(), + generation, + generation, + base.outboxStreamKey(), + sequence, + Optional.of(AccountSecurityStateAuthorityEventV1Codec.seal(event).canonicalJson())); + var decoded = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + projection.toJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + "account", + ACCOUNT_ID.toString()); + assertThat(decoded.generationValue()).isEqualTo(new BigInteger(generation)); + } + + @Test + void rejectsPublicationWhenOwnerSourceAdvancesAcrossRedisWrite() { + var sources = mock(AccountAuthoritySourceEvidenceRepository.class); + var redis = mock(AccountGameplayDelegationRedisClient.class); + when(sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(snapshot(1, 11), snapshot(1, 12)); + when(redis.publishAuthorityProjections(any(UUID.class), any(byte[].class), any(byte[].class))) + .thenReturn(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + var projection = + new AccountGameplayDelegationAuthorityProjection( + sources, transactionManager(null), redis); + assertThatThrownBy(() -> projection.publishCurrent(ACCOUNT_ID)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + } + + @Test + void rejectsProjectionObservationWhenOwnerSourceAdvancesAcrossRedisRead() throws Exception { + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationRedisClient redis = mock(AccountGameplayDelegationRedisClient.class); + when(sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(snapshot(1L, 11L), snapshot(1L, 12L)); + when(redis.readAuthorityProjections(ACCOUNT_ID)) + .thenReturn( + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair( + snapshot(1L, 11L))); + AccountGameplayDelegationAuthorityProjection projection = + new AccountGameplayDelegationAuthorityProjection( + sourceEvidence, transactionManager(null), redis); + + assertThatThrownBy(() -> projection.observeCurrent(ACCOUNT_ID)) + .isInstanceOf( + AccountGameplayDelegationAuthorityProjection.StaleProjectionException.class); + } + + @Test + void publishesOnlyAfterOwnerSnapshotTransactionHasCompleted() { + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountGameplayDelegationRedisClient redis = mock(AccountGameplayDelegationRedisClient.class); + AtomicBoolean transactionActive = new AtomicBoolean(); + PlatformTransactionManager transactionManager = transactionManager(transactionActive); + when(sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) + .thenReturn(snapshot(1L, 11L)); + when(redis.publishAuthorityProjections(any(UUID.class), any(byte[].class), any(byte[].class))) + .thenAnswer( + invocation -> { + assertThat(transactionActive.get()).isFalse(); + return AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED; + }); + AccountGameplayDelegationAuthorityProjection projection = + new AccountGameplayDelegationAuthorityProjection( + sourceEvidence, transactionManager, redis); + + assertThat(projection.publishCurrent(ACCOUNT_ID).accountGeneration()).isEqualTo(11L); + assertThat(transactionActive.get()).isFalse(); + } + + static IssuerAccountSourceSnapshot snapshot(long issuerGeneration, long accountGeneration) { + String issuerStream = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + IssuanceFence fence = new IssuanceFence(ACCOUNT_ID, accountGeneration, accountGeneration); + CurrentSourceEvidence issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER), + issuerGeneration, + issuerGeneration, + null, + checkpoint(issuerStream, issuerGeneration - 1L), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 5L, + null); + Optional cutoff = + accountGeneration == 1L + ? Optional.empty() + : Optional.of( + new AccountSecurityCutoff( + Long.toString(accountGeneration), + accountStream, + Long.toString(accountGeneration - 1L))); + CurrentSourceEvidence account = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + accountGeneration, + accountGeneration, + fence, + checkpoint(accountStream, accountGeneration - 1L), + cutoff, + "ACCOUNT_REPOSITORY_INSERT", + 42L, + "ACCOUNT_REPOSITORY_INSERT", + 6L, + 6L); + String event = null; + if (accountGeneration > 1) { + String generation = Long.toString(accountGeneration); + String sequence = Long.toString(accountGeneration - 1); + String request = "11111111-1111-4111-8111-111111111111"; + event = + AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry( + "eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + request), + Map.entry("requestId", request), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", accountStream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", generation), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + accountStream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))) + .canonicalJson(); + } + return new IssuerAccountSourceSnapshot( + issuer, + account, + fence, + new AccountGenerationProjection( + ACCOUNT_ID.toString(), + Long.toString(accountGeneration), + Long.toString(accountGeneration), + accountStream, + Long.toString(accountGeneration - 1), + Optional.ofNullable(event))); + } + + private static SourceCheckpoint checkpoint(String stream, long sequence) { + return sequence == 0L + ? new SourceCheckpoint(stream, 0L, Optional.empty(), Optional.empty()) + : new SourceCheckpoint( + stream, + sequence, + Optional.of("event-" + sequence), + Optional.of("sha256:" + "a".repeat(64))); + } + + private static Map decodeFields(byte[] value) { + try { + return JSON.readValue(value, new tools.jackson.core.type.TypeReference<>() {}); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static byte[] canonical(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String digestWithoutDigest(Map fields) throws Exception { + Map preimage = new LinkedHashMap<>(fields); + preimage.remove("digest"); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonical(preimage))); + } + + private static Map mutableMap(Object value) { + if (!(value instanceof Map source)) throw new IllegalArgumentException(); + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + if (!(entry.getKey() instanceof String key)) throw new IllegalArgumentException(); + result.put(key, entry.getValue()); + } + return result; + } + + private static PlatformTransactionManager transactionManager(AtomicBoolean active) { + PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + TransactionStatus status = mock(TransactionStatus.class); + when(manager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + invocation -> { + if (active != null) active.set(true); + return status; + }); + doAnswer( + invocation -> { + if (active != null) active.set(false); + return null; + }) + .when(manager) + .commit(status); + doAnswer( + invocation -> { + if (active != null) active.set(false); + return null; + }) + .when(manager) + .rollback(status); + return manager; + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java new file mode 100644 index 0000000000..2c5fd85671 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java @@ -0,0 +1,337 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameplayDelegationCommittedIssuanceOwnerTest { + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final Instant NOW = Instant.parse("2026-10-05T00:00:00Z"); + private static final long TOKEN_EXPIRY_MILLIS = NOW.plusSeconds(120L).toEpochMilli(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void malformedRequestIsDeniedBeforeStartingOwnerReads() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, mock(PlatformTransactionManager.class)); + + assertThatThrownBy( + () -> + owner.inspectCurrentCommittedIssuance( + UUID.fromString("00000000-0000-0000-0000-000000000000"))) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(repository, signer, registry); + } + + @Test + void refusesToJoinAnAmbientAccountTransaction() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, mock(PlatformTransactionManager.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> owner.inspectCurrentCommittedIssuance(REQUEST_ID)) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(repository, signer, registry); + } + + @Test + void activationRefusesAmbientTransactionBeforeOwnerOrRedisReads() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, mock(PlatformTransactionManager.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> owner.activateCommittedIssuance(REQUEST_ID)) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(repository, signer, registry); + } + + @Test + void recoveryActivationChecksCurrentRetainedKeyOutsideSqlBeforeAndAfterActiveReadback() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + TestTransactionManager transactionManager = new TestTransactionManager(); + CommittedCandidateVerificationData committed = committedCandidate(); + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt receipt = activeReceipt(); + when(repository.readCurrentCommittedCandidate(REQUEST_ID)).thenReturn(committed, committed); + when(registry.activateCommittedCandidate(committed)).thenReturn(receipt); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + return null; + }) + .when(signer) + .requireCurrentCommittedRecoverySigner(committed); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return null; + }) + .when(signer) + .requireRetainedCommittedPublicKey(committed); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, transactionManager); + + var active = owner.activateCommittedIssuance(REQUEST_ID); + + org.assertj.core.api.Assertions.assertThat(active.tokenSha256()).isEqualTo("a".repeat(64)); + var sequence = inOrder(repository, signer, registry); + sequence.verify(repository).readCurrentCommittedCandidate(REQUEST_ID); + sequence.verify(signer).requireCurrentCommittedRecoverySigner(committed); + sequence.verify(signer).requireRetainedCommittedPublicKey(committed); + sequence.verify(registry).activateCommittedCandidate(committed); + sequence.verify(repository).readCurrentCommittedCandidate(REQUEST_ID); + sequence.verify(signer).requireCurrentCommittedRecoverySigner(committed); + sequence.verify(signer).requireRetainedCommittedPublicKey(committed); + verify(repository, times(2)).readCurrentCommittedCandidate(REQUEST_ID); + } + + @Test + void currentnessAllowsHistoricalSignerGenerationWhenOriginalKeyIsRetained() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + TestTransactionManager transactionManager = new TestTransactionManager(); + CommittedCandidateVerificationData committed = committedCandidate(); + UUID tokenJti = committed.identity().tokenJti(); + when(repository.readCurrentCommittedCandidateByJti(tokenJti)) + .thenReturn(Optional.of(committed)); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + return null; + }) + .when(signer) + .requireCurrentCommittedRecoverySigner(committed); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return null; + }) + .when(signer) + .requireRetainedCommittedPublicKey(committed); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, transactionManager); + + var current = owner.requireCurrentActiveCommittedCandidateByJti(tokenJti); + + org.assertj.core.api.Assertions.assertThat(current).isSameAs(committed); + var sequence = inOrder(repository, signer, registry); + sequence.verify(repository).readCurrentCommittedCandidateByJti(tokenJti); + sequence.verify(signer).requireCurrentCommittedRecoverySigner(committed); + sequence.verify(signer).requireRetainedCommittedPublicKey(committed); + sequence.verify(registry).requireExactActiveRecord(committed); + verify(signer, never()).requireCurrentCommittedSigner(committed); + } + + @Test + void missingRetainedKeyDeniesCurrentnessBeforeRedisRead() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + CommittedCandidateVerificationData committed = committedCandidate(); + UUID tokenJti = committed.identity().tokenJti(); + when(repository.readCurrentCommittedCandidateByJti(tokenJti)) + .thenReturn(Optional.of(committed)); + doAnswer(invocation -> null).when(signer).requireCurrentCommittedRecoverySigner(committed); + doAnswer( + invocation -> { + throw new IllegalStateException("retained signing key is unavailable"); + }) + .when(signer) + .requireRetainedCommittedPublicKey(committed); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, new TestTransactionManager()); + + assertThatThrownBy(() -> owner.requireCurrentActiveCommittedCandidateByJti(tokenJti)) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verify(registry, never()).requireExactActiveRecord(committed); + } + + @Test + void missingRetainedKeyDeniesBeforeRegistryActivation() { + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + CommittedCandidateVerificationData committed = committedCandidate(); + when(repository.readCurrentCommittedCandidate(REQUEST_ID)).thenReturn(committed); + doAnswer(invocation -> null).when(signer).requireCurrentCommittedRecoverySigner(committed); + doAnswer( + invocation -> { + throw new IllegalStateException("retained signing key is unavailable"); + }) + .when(signer) + .requireRetainedCommittedPublicKey(committed); + AccountGameplayDelegationCommittedIssuanceOwner owner = + owner(repository, signer, registry, new TestTransactionManager()); + + assertThatThrownBy(() -> owner.activateCommittedIssuance(REQUEST_ID)) + .isInstanceOf(OwnerUnavailableException.class) + .hasNoCause(); + + verify(registry, never()).activateCommittedCandidate(committed); + } + + private static CommittedCandidateVerificationData committedCandidate() { + UUID accountId = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + UUID operationId = UUID.fromString("c5c31332-e560-41c8-a55a-97674e7a317c"); + long expiresAt = TOKEN_EXPIRY_MILLIS / 1_000L; + var identity = + new AccountGameplayDelegationPendingIdentity( + operationId, + REQUEST_ID, + accountId, + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.fromString("e16fdce5-96eb-49e1-a9bd-3f429816cbf0"), + AccountGameplayCredentialRequestBindingFixture.binding(), + "b".repeat(64), + UUID.fromString("1a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), + NOW.getEpochSecond(), + NOW.getEpochSecond(), + expiresAt); + CommittedCandidateVerificationData committed = mock(CommittedCandidateVerificationData.class); + when(committed.identity()).thenReturn(identity); + when(committed.authoritySnapshot()) + .thenReturn( + new AccountAuthoritySnapshot(accountId, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty())); + when(committed.evidenceBundleReference()) + .thenReturn(new EvidenceBundleReference("1", "1", "2", "1", "c".repeat(64))); + when(committed.tokenSha256()).thenReturn("a".repeat(64)); + when(committed.signerKid()).thenReturn("account-key-42"); + when(committed.signerGeneration()).thenReturn("42"); + when(committed.canonicalRegistryRecordSha256()).thenReturn("d".repeat(64)); + when(committed.commitProofSha256()).thenReturn("e".repeat(64)); + when(committed.signerCorrespondence()) + .thenReturn(mock(AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence.class)); + when(committed.envelopeKeyId()).thenReturn("response-key-1"); + when(committed.envelopeSha256()).thenReturn("f".repeat(64)); + when(committed.envelopeBytesLength()).thenReturn(64); + when(committed.responseRecoveryExpiryEpochMillis()).thenReturn(expiresAt * 1_000L); + when(committed.registryAbsoluteExpiryMillis()).thenReturn(TOKEN_EXPIRY_MILLIS + 30_000L); + when(committed.registrationLocalAofCount()).thenReturn(1L); + when(committed.registrationReplicaAofCount()).thenReturn(1L); + when(committed.registrationOutcome()) + .thenReturn(AccountGameplayDelegationRedisClient.PendingRegistrationOutcome.CREATED); + return committed; + } + + private static AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt activeReceipt() { + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt receipt = + mock(AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt.class); + long expiry = TOKEN_EXPIRY_MILLIS + 30_000L; + when(receipt.tokenKey()) + .thenReturn(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + "a".repeat(64)); + when(receipt.tokenHash()).thenReturn("a".repeat(64)); + when(receipt.operationId()).thenReturn("c5c31332-e560-41c8-a55a-97674e7a317c"); + when(receipt.requestId()).thenReturn(REQUEST_ID.toString()); + when(receipt.accountId()).thenReturn("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + when(receipt.canonicalActiveRecordSha256()).thenReturn("1".repeat(64)); + when(receipt.commitProofSha256()).thenReturn("e".repeat(64)); + when(receipt.registryVersion()).thenReturn(2L); + when(receipt.absoluteExpiryMillis()).thenReturn(expiry); + when(receipt.localAofCount()).thenReturn(1L); + when(receipt.replicaAofCount()).thenReturn(1L); + when(receipt.outcome()) + .thenReturn(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.ACTIVATED); + return receipt; + } + + private static AccountGameplayDelegationCommittedIssuanceOwner owner( + AccountGameplayDelegationIssuanceRepository repository, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry registry, + PlatformTransactionManager transactionManager) { + return new AccountGameplayDelegationCommittedIssuanceOwner( + repository, signer, registry, transactionManager, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static final class TestTransactionManager extends AbstractPlatformTransactionManager { + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java new file mode 100644 index 0000000000..ec357308ee --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java @@ -0,0 +1,273 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +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 java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedIssuanceReadback; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection.ProjectionObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection.PublicationObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationReceipt; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSignerTestFixtureFactory; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSignerTestFixtureFactory.Fixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameplayDelegationIssuanceCommitServiceTest { + private static final UUID OPERATION_ID = UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final Clock SIGNING_CLOCK = + Clock.fixed(Instant.parse("2026-10-05T00:00:30Z"), ZoneOffset.UTC); + + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactCommittedRetryReturnsOnlyOwnerMetadataWithoutRemintOrRedisWrite() { + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationAuthorityProjection projection = + mock(AccountGameplayDelegationAuthorityProjection.class); + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + CommittedIssuanceReadback readback = + new CommittedIssuanceReadback( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + "a".repeat(64), + "b".repeat(64), + "account-kid-1", + "7", + "c".repeat(64)); + when(repository.readCommittedProof(REQUEST_ID)).thenReturn(Optional.of(readback)); + + AccountGameplayDelegationIssuanceCommitService service = + service(signer, registry, projection, repository); + AccountGameplayDelegationIssuanceCommitService.CommitResult result = + service.commitPendingCandidate(REQUEST_ID); + + assertThat(result.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.EXACT_RETRY); + assertThat(result.operationId()).isEqualTo(OPERATION_ID); + assertThat(result.requestId()).isEqualTo(REQUEST_ID); + assertThat(result.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(result.proofSha256()).isEqualTo("c".repeat(64)); + assertThat(result.toString()).doesNotContain("b".repeat(64)); + verify(repository).readCommittedProof(REQUEST_ID); + verifyNoInteractions(signer, registry, projection); + } + + @Test + void refusesToPerformNetworkWorkInsideAnAmbientAccountTransaction() { + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationAuthorityProjection projection = + mock(AccountGameplayDelegationAuthorityProjection.class); + AccountGameplayDelegationIssuanceRepository repository = + mock(AccountGameplayDelegationIssuanceRepository.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + + AccountGameplayDelegationIssuanceCommitService service = + service(signer, registry, projection, repository); + + assertThatThrownBy(() -> service.commitPendingCandidate(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class); + verifyNoInteractions(signer, registry, projection, repository); + } + + @Test + void genuineRsaSignerCompositionCannotCommitWithoutOwnerRegistrationReceipt() throws Exception { + Fixture signerFixture = + AccountGameplayDelegationSignerTestFixtureFactory.create(temporaryDirectory); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationAuthorityProjection projection = + mock(AccountGameplayDelegationAuthorityProjection.class); + AccountGameplayDelegationIssuanceRepository repository = signerFixture.issuanceRepository(); + when(repository.readCommittedProof(signerFixture.requestId())).thenReturn(Optional.empty()); + when(registry.registerPending(signerFixture.requestId())).thenReturn(null); + when(projection.publishCurrent(signerFixture.accountId())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new PublicationObservation( + "d".repeat(64), "e".repeat(64), 11L, 12L, ProjectionPublicationOutcome.PUBLISHED); + }); + when(projection.observeCurrent(signerFixture.accountId())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new ProjectionObservation("d".repeat(64), "e".repeat(64), 11L, 12L); + }); + + AccountGameplayDelegationIssuanceCommitService service = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + registry, + projection, + repository, + signerFixture.transactionManager(), + SIGNING_CLOCK); + + assertThatThrownBy(() -> service.commitPendingCandidate(signerFixture.requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + verify(repository).bindSignedCandidate(eq(signerFixture.requestId()), anyString(), eq("42")); + verify(signerFixture.responseEnvelopeService()) + .sealPendingCandidate(eq(signerFixture.requestId()), any(), anyString()); + verify(registry).registerPending(signerFixture.requestId()); + var order = inOrder(registry, projection); + order.verify(registry).registerPending(signerFixture.requestId()); + order.verify(projection).publishCurrent(signerFixture.accountId()); + order.verify(projection).observeCurrent(signerFixture.accountId()); + verify(projection).observeCurrent(signerFixture.accountId()); + verify(repository, never()).commitPendingCandidate(any(), any(), any(), any(), any()); + verify(repository).readCommittedProof(signerFixture.requestId()); + } + + @Test + void projectionPublicationFailureDeniesBeforeObservationOrAccountCommit() throws Exception { + Fixture signerFixture = + AccountGameplayDelegationSignerTestFixtureFactory.create(temporaryDirectory); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationAuthorityProjection projection = + mock(AccountGameplayDelegationAuthorityProjection.class); + AccountGameplayDelegationIssuanceRepository repository = signerFixture.issuanceRepository(); + when(repository.readCommittedProof(signerFixture.requestId())).thenReturn(Optional.empty()); + when(registry.registerPending(signerFixture.requestId())).thenReturn(null); + when(projection.publishCurrent(signerFixture.accountId())) + .thenThrow(new IllegalStateException("projection publication unavailable")); + + AccountGameplayDelegationIssuanceCommitService service = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + registry, + projection, + repository, + signerFixture.transactionManager(), + SIGNING_CLOCK); + + assertThatThrownBy(() -> service.commitPendingCandidate(signerFixture.requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + verify(projection).publishCurrent(signerFixture.accountId()); + verify(projection, never()).observeCurrent(any()); + verify(repository, never()).commitPendingCandidate(any(), any(), any(), any(), any()); + } + + @Test + void projectionObservationMustMatchPublishedDigestAndGeneration() throws Exception { + ProjectionObservation[] mismatches = { + new ProjectionObservation("c".repeat(64), "e".repeat(64), 11L, 12L), + new ProjectionObservation("d".repeat(64), "c".repeat(64), 11L, 12L), + new ProjectionObservation("d".repeat(64), "e".repeat(64), 10L, 12L), + new ProjectionObservation("d".repeat(64), "e".repeat(64), 11L, 13L) + }; + + for (int index = 0; index < mismatches.length; index++) { + ProjectionObservation mismatch = mismatches[index]; + Path fixtureDirectory = + Files.createDirectory(temporaryDirectory.resolve("mismatch-" + index)); + Fixture signerFixture = + AccountGameplayDelegationSignerTestFixtureFactory.create(fixtureDirectory); + AccountGameplayDelegationTokenRegistry registry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountGameplayDelegationAuthorityProjection projection = + mock(AccountGameplayDelegationAuthorityProjection.class); + AccountGameplayDelegationIssuanceRepository repository = signerFixture.issuanceRepository(); + PendingRegistrationReceipt receipt = mock(PendingRegistrationReceipt.class); + when(repository.readCommittedProof(signerFixture.requestId())).thenReturn(Optional.empty()); + when(registry.registerPending(signerFixture.requestId())).thenReturn(receipt); + when(projection.publishCurrent(signerFixture.accountId())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new PublicationObservation( + "d".repeat(64), + "e".repeat(64), + 11L, + 12L, + ProjectionPublicationOutcome.PUBLISHED); + }); + when(projection.observeCurrent(signerFixture.accountId())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return mismatch; + }); + + AccountGameplayDelegationIssuanceCommitService service = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + registry, + projection, + repository, + signerFixture.transactionManager(), + SIGNING_CLOCK); + + assertThatThrownBy(() -> service.commitPendingCandidate(signerFixture.requestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + .class) + .hasNoCause(); + + verify(projection).publishCurrent(signerFixture.accountId()); + verify(projection).observeCurrent(signerFixture.accountId()); + verifyNoInteractions(receipt); + verify(repository, never()).commitPendingCandidate(any(), any(), any(), any(), any()); + } + } + + private static AccountGameplayDelegationIssuanceCommitService service( + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry registry, + AccountGameplayDelegationAuthorityProjection projection, + AccountGameplayDelegationIssuanceRepository repository) { + return new AccountGameplayDelegationIssuanceCommitService( + signer, + registry, + projection, + repository, + mock(PlatformTransactionManager.class), + Clock.fixed(Instant.parse("2027-01-15T12:00:00Z"), ZoneOffset.UTC)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java new file mode 100644 index 0000000000..2d53209ccc --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java @@ -0,0 +1,1247 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationRedisClientTest { + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void selectedDescriptorsPinExistingExactByteCasAndDisjointCanonicalKeys() throws Exception { + var descriptors = new AccountGameplayDelegationRedisScriptContribution().descriptors(); + for (String id : + List.of( + AccountGameplayDelegationRedisClient.TENANT_PROJECTION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.MEMBERSHIP_PROJECTION_SCRIPT_ID)) { + var descriptor = + descriptors.stream() + .filter(value -> id.equals(value.scriptId())) + .findFirst() + .orElseThrow(); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.keys()).hasSize(1); + assertThat(descriptor.keys().getFirst().ownedPrefix()) + .isEqualTo( + id.equals(AccountGameplayDelegationRedisClient.TENANT_PROJECTION_SCRIPT_ID) + ? "session:auth:generation:tenant:" + : "session:auth:generation:membership:"); + assertThat( + descriptor.arguments().stream() + .map(RedisScriptDescriptor.ArgumentSpec::name) + .toList()) + .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); + try (var source = + getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(source).isNotNull(); + assertThat(sha256(source.readAllBytes())).isEqualTo(descriptor.sha256()); + } + } + } + + @Test + void selectedEventPageUsesOnePinnedConnectionAndOneDurabilityAckFor128OrderedCasCalls() + throws Exception { + UUID tenant = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT; + List candidates = membershipPage(tenant, 1, 128); + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + Map stored = new java.util.HashMap<>(); + AtomicInteger openedConnections = new AtomicInteger(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] keys = invocation.getArgument(2); + Object[] rawArguments = invocation.getRawArguments(); + if (rawArguments.length != 4 + || !(rawArguments[3] instanceof byte[][] arguments) + || arguments.length != 3) return -1L; + String key = new String(keys[0], StandardCharsets.UTF_8); + String mode = new String(arguments[0], StandardCharsets.US_ASCII); + byte[] current = stored.get(key); + if (current != null && Arrays.equals(current, arguments[2])) return 0L; + if (("ABSENT".equals(mode) && current != null) + || ("PRESENT".equals(mode) && !Arrays.equals(current, arguments[1]))) { + return -1L; + } + stored.put(key, arguments[2].clone()); + return 1L; + }); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> + stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); + AccountGameplayDelegationRedisClient client = + client( + () -> { + openedConnections.incrementAndGet(); + return connection; + }); + + assertThat( + client.publishSelectedAuthorityEventPage(ACCOUNT_ID, tenant, false, null, candidates)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + + ArgumentCaptor args = ArgumentCaptor.forClass(byte[][].class); + verify(commands, times(128)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), args.capture()); + assertThat(openedConnections.get()).isEqualTo(1); + verify(commands).aclWhoami(); + verify(commands, times(1)).scriptLoad(any(byte[].class)); + verify(commands, times(1)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(commands) + .get( + argThat( + key -> + Arrays.equals( + key, + ascii("session:auth:generation:membership:" + ACCOUNT_ID + ":" + tenant)))); + verify(connection).close(); + assertThat(args.getAllValues()).hasSize(128); + for (int index = 0; index < candidates.size(); index++) { + byte[][] actual = args.getAllValues().get(index); + assertThat(actual[0]).containsExactly(ascii(index == 0 ? "ABSENT" : "PRESENT")); + assertThat(actual[1]).containsExactly(index == 0 ? new byte[0] : candidates.get(index - 1)); + assertThat(actual[2]).containsExactly(candidates.get(index)); + } + assertThat(stored.get("session:auth:generation:membership:" + ACCOUNT_ID + ":" + tenant)) + .containsExactly(candidates.getLast()); + } + + @Test + void selectedEventPageDeniesPartialCasAndRecoversFromActualContiguousRedisHead() + throws Exception { + UUID tenant = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT; + List candidates = membershipPage(tenant, 1, 4); + String key = "session:auth:generation:membership:" + ACCOUNT_ID + ":" + tenant; + Map stored = new java.util.HashMap<>(); + StatefulRedisConnection failedConnection = connection(); + RedisCommands failedCommands = failedConnection.sync(); + AtomicInteger attempts = new AtomicInteger(); + when(failedCommands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(failedCommands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + int attempt = attempts.incrementAndGet(); + if (attempt == 3) return -1L; + Object[] rawArguments = invocation.getRawArguments(); + if (rawArguments.length != 4 + || !(rawArguments[3] instanceof byte[][] arguments) + || arguments.length != 3) return -1L; + stored.put(key, arguments[2].clone()); + return 1L; + }); + assertThatThrownBy( + () -> + client(failedConnection) + .publishSelectedAuthorityEventPage(ACCOUNT_ID, tenant, false, null, candidates)) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(stored.get(key)).containsExactly(candidates.get(1)); + verify(failedCommands, org.mockito.Mockito.never()) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(failedCommands, org.mockito.Mockito.never()).get(any(byte[].class)); + verify(failedConnection).close(); + + StatefulRedisConnection recoveryConnection = connection(); + RedisCommands recoveryCommands = recoveryConnection.sync(); + when(recoveryCommands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(recoveryCommands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + Object[] rawArguments = invocation.getRawArguments(); + if (rawArguments.length != 4 + || !(rawArguments[3] instanceof byte[][] arguments) + || arguments.length != 3) return -1L; + stored.put(key, arguments[2].clone()); + return 1L; + }); + doReturn(List.of(1L, 1L)) + .when(recoveryCommands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(recoveryCommands.get(any(byte[].class))) + .thenAnswer( + invocation -> + stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); + + assertThat( + client(recoveryConnection) + .publishSelectedAuthorityEventPage( + ACCOUNT_ID, tenant, false, candidates.get(1), candidates.subList(2, 4))) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + assertThat(stored.get(key)).containsExactly(candidates.getLast()); + verify(recoveryCommands, times(2)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + verify(recoveryCommands, times(1)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(recoveryConnection).close(); + } + + @Test + void selectedEventPageDeniesUnacknowledgedDurabilityAndIncorrectFinalReadback() throws Exception { + UUID tenant = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT; + List candidates = membershipPage(tenant, 1, 2); + for (boolean badReadback : List.of(false, true)) { + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L, 1L); + doReturn(badReadback ? List.of(1L, 1L) : List.of(1L, 0L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + if (badReadback) when(commands.get(any(byte[].class))).thenReturn(ascii("wrong head")); + + assertThatThrownBy( + () -> + client(connection) + .publishSelectedAuthorityEventPage( + ACCOUNT_ID, tenant, false, null, candidates)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(connection).close(); + if (badReadback) verify(commands).get(any(byte[].class)); + else verify(commands, org.mockito.Mockito.never()).get(any(byte[].class)); + } + } + + @Test + void selectedPublicationUsesFourCasCallsOnePinnedAckAndExactNoTtlReadback() throws Exception { + UUID tenant = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT; + byte[][] values = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.selected( + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()), + ACCOUNT_ID, + tenant); + var connection = connection(); + var commands = connection.sync(); + Map stored = new java.util.HashMap<>(); + stored.put("session:auth:generation:issuer:firemud-account-service", values[0]); + stored.put("session:auth:generation:account:" + ACCOUNT_ID, values[1]); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> + stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] keys = invocation.getArgument(2); + String key = new String(keys[0], StandardCharsets.UTF_8); + if (key.startsWith("session:auth:generation:tenant:")) { + stored.put(key, values[2]); + return 1L; + } + if (key.startsWith("session:auth:generation:membership:")) { + stored.put(key, values[3]); + return 1L; + } + return 0L; + }); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + assertThat(client(connection).publishSelectedAuthorityProjections(ACCOUNT_ID, tenant, values)) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + verify(commands, times(4)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + verify(commands, times(1)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(connection).close(); + assertThat(stored.get("session:auth:generation:membership:" + ACCOUNT_ID + ":" + tenant)) + .containsExactly(values[3]); + } + + @Test + void selectedObservationRejectsMissingMembershipAndAnySelectedTtl() throws Exception { + UUID tenant = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT; + byte[][] values = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.selected( + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()), + ACCOUNT_ID, + tenant); + for (boolean missing : List.of(true, false)) { + var connection = connection(); + var commands = connection.sync(); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.UTF_8); + if (key.contains(":issuer:")) return values[0]; + if (key.contains(":account:")) return values[1]; + if (key.contains(":tenant:")) return values[2]; + return missing ? null : values[3]; + }); + if (!missing) + when(commands.pttl(any(byte[].class))) + .thenAnswer( + invocation -> + new String(invocation.getArgument(0), StandardCharsets.UTF_8) + .contains(":membership:") + ? 500L + : -1L); + assertThatThrownBy( + () -> client(connection).readSelectedAuthorityProjections(ACCOUNT_ID, tenant)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(connection).close(); + } + } + + @Test + void authorityProjectionUsesTwoExactOneKeyCasCallsOneAofAckAndSameConnectionReadback() + throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L, 0L); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + byte[] key = invocation.getArgument(0); + if (Arrays.equals( + key, ascii("session:auth:generation:issuer:firemud-account-service"))) { + return values[0].clone(); + } + if (Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID))) { + return values[1].clone(); + } + return null; + }); + AccountGameplayDelegationRedisClient client = client(connection); + + assertThat(client.publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); + + ArgumentCaptor keys = ArgumentCaptor.forClass(byte[][].class); + ArgumentCaptor args = ArgumentCaptor.forClass(byte[][].class); + verify(commands, times(2)) + .evalsha(anyString(), eq(ScriptOutputType.INTEGER), keys.capture(), args.capture()); + assertThat(keys.getAllValues()).hasSize(2); + assertThat( + Arrays.equals( + keys.getAllValues().get(0)[0], + ascii("session:auth:generation:issuer:firemud-account-service"))) + .isTrue(); + assertThat( + Arrays.equals( + keys.getAllValues().get(1)[0], + ascii("session:auth:generation:account:" + ACCOUNT_ID))) + .isTrue(); + assertThat(Arrays.equals(args.getAllValues().get(0)[0], values[0])).isTrue(); + assertThat(new String(args.getAllValues().get(1)[0], StandardCharsets.US_ASCII)) + .isEqualTo("VERIFY"); + assertThat(args.getAllValues().get(1)[1]).containsExactly(values[1]); + assertThat(args.getAllValues().get(1)[2]).isEmpty(); + verify(commands).aclWhoami(); + verify(commands, times(1)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(commands) + .get( + argThat( + key -> + Arrays.equals( + key, ascii("session:auth:generation:issuer:firemud-account-service")))); + verify(commands, times(2)) + .get( + argThat( + key -> Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID)))); + verify(connection).close(); + } + + @Test + void wrongLiveAccountRoleDeniesProjectionBeforeScriptLoad() throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.aclWhoami()).thenReturn("account_coord_admin"); + + assertThatThrownBy( + () -> client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(commands).aclWhoami(); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(anyString(), any(), any(byte[][].class), any(byte[][].class)); + verify(connection).close(); + } + + @Test + void accountObservationRejectsProjectionWithAnyTtl() throws Exception { + byte[][] pair = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + var connection = connection(); + var commands = connection.sync(); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + byte[] key = invocation.getArgument(0); + return Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID)) + ? pair[1] + : pair[0]; + }); + when(commands.pttl(any(byte[].class))).thenReturn(1000L); + assertThatThrownBy(() -> client(connection).readAuthorityProjections(ACCOUNT_ID)) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(connection).close(); + } + + @Test + void authorityProjectionObservationRejectsIssuerOnlyTtl() throws Exception { + byte[][] pair = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + var connection = connection(); + var commands = connection.sync(); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + byte[] key = invocation.getArgument(0); + return Arrays.equals(key, issuerProjectionKey()) ? pair[0] : pair[1]; + }); + when(commands.pttl(any(byte[].class))) + .thenAnswer( + invocation -> + Arrays.equals(invocation.getArgument(0), issuerProjectionKey()) ? 1L : -1L); + + assertThatThrownBy(() -> client(connection).readAuthorityProjections(ACCOUNT_ID)) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(commands).pttl(argThat(key -> Arrays.equals(key, issuerProjectionKey()))); + verify(connection).close(); + } + + @Test + void authorityProjectionPublicationReadbackRejectsIssuerOnlyTtl() throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L, 0L); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + byte[] key = invocation.getArgument(0); + if (Arrays.equals(key, issuerProjectionKey())) return values[0].clone(); + if (Arrays.equals(key, accountProjectionKey())) return values[1].clone(); + return null; + }); + when(commands.pttl(any(byte[].class))) + .thenAnswer( + invocation -> + Arrays.equals(invocation.getArgument(0), issuerProjectionKey()) ? 1L : -1L); + + assertThatThrownBy( + () -> client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(commands).pttl(argThat(key -> Arrays.equals(key, issuerProjectionKey()))); + verify(connection).close(); + } + + @Test + void acknowledgementOrReadbackUncertaintyNeverReturnsProjectionSuccess() throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + StatefulRedisConnection noAckConnection = connection(); + RedisCommands noAckCommands = noAckConnection.sync(); + when(noAckCommands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(noAckCommands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L, 1L); + doReturn(List.of(1L, 0L)) + .when(noAckCommands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + + assertThatThrownBy( + () -> + client(noAckConnection) + .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(noAckCommands, times(1)).get(any(byte[].class)); + + StatefulRedisConnection readbackConnection = connection(); + RedisCommands readbackCommands = readbackConnection.sync(); + when(readbackCommands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(readbackCommands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L, 1L); + doReturn(List.of(1L, 1L)) + .when(readbackCommands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(readbackCommands.get(any(byte[].class))).thenReturn(null, ascii("wrong projection")); + + assertThatThrownBy( + () -> + client(readbackConnection) + .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } + + @Test + void staleOrConflictingIssuerProjectionStopsBeforeAccountWriteOrDurabilityAck() throws Exception { + byte[][] values = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot()); + for (long result : List.of(-1L, -2L, -4L, -5L)) { + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(result); + + assertThatThrownBy( + () -> + client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(commands, times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + verify(commands, org.mockito.Mockito.never()) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(commands, org.mockito.Mockito.never()).get(any(byte[].class)); + verify(connection).close(); + } + } + + @Test + void projectionDescriptorsPinExactRoleKeyArgumentAndLuaDigest() throws Exception { + List descriptors = + new AccountGameplayDelegationRedisScriptContribution() + .descriptors().stream() + .filter(descriptor -> descriptor.scriptId().contains("authority-project")) + .toList(); + assertThat(descriptors).hasSize(1); + RedisScriptDescriptor issuer = + descriptors.stream() + .filter( + descriptor -> + descriptor + .scriptId() + .equals(AccountGameplayDelegationRedisClient.ISSUER_PROJECTION_SCRIPT_ID)) + .findFirst() + .orElseThrow(); + RedisScriptDescriptor account = + net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract + .descriptor(); + assertThat(issuer.owner()).isEqualTo("account-service"); + assertThat(account.owner()).isEqualTo("account-service"); + assertThat(issuer.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(account.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(issuer.keys()).hasSize(1); + assertThat(account.keys()).hasSize(1); + assertThat(issuer.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(account.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(issuer.keys().getFirst().name()).isEqualTo("authorityProjection"); + assertThat(issuer.keys().getFirst().ownedPrefix()) + .isEqualTo(AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX); + assertThat(issuer.keys().getFirst().hashTagDeclaration()) + .isEqualTo(RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + assertThat(account.keys().getFirst().name()).isEqualTo("accountGenerationProjection"); + assertThat(account.keys().getFirst().ownedPrefix()) + .isEqualTo(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX); + assertThat(account.keys().getFirst().hashTagDeclaration()) + .isEqualTo(RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + assertThat(issuer.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) + .containsExactly("canonicalProjectionUtf8"); + assertThat(account.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) + .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); + assertThat(account.resourcePath()).isEqualTo("redis/account_generation_projection_cas.lua"); + assertThat(issuer.resourcePath()) + .isEqualTo("redis/lua/account-game-session-delegation-authority-project.lua"); + assertThat(issuer.sha256()).isNotEqualTo(account.sha256()); + + byte[] source; + try (var input = getClass().getClassLoader().getResourceAsStream(issuer.resourcePath())) { + assertThat(input).isNotNull(); + source = input.readAllBytes(); + } + String lua = new String(source, StandardCharsets.UTF_8); + assertThat(sha256(source)).isEqualTo(issuer.sha256()); + assertThat(lua) + .doesNotContain("MAX_SIGNED_BIGINT") + .contains("return string.len(left) > string.len(right)") + .contains("return left > right") + .contains("local function decrement_decimal(value)") + .contains("if type(stored) ~= 'table' or stored.ok ~= 'OK' then return -3 end") + .doesNotContain("stored ~= 'OK'") + .doesNotContain("tonumber(value.generation)") + .doesNotContain("tonumber(value.sourceVersion)") + .doesNotContain("tonumber(value.issuanceFence)"); + } + + @Test + void pendingRegistrationDescriptorAndLuaPinConditionalAbsoluteExpiry() throws Exception { + RedisScriptDescriptor descriptor = + new AccountGameplayDelegationRedisScriptContribution() + .descriptors().stream() + .filter( + item -> AccountGameplayDelegationRedisClient.SCRIPT_ID.equals(item.scriptId())) + .findFirst() + .orElseThrow(); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(descriptor.resourcePath()) + .isEqualTo("redis/lua/account-game-session-delegation-pending-register.lua"); + assertThat(descriptor.keys()).hasSize(1); + assertThat(descriptor.keys().getFirst().name()).isEqualTo("tokenRecord"); + assertThat(descriptor.keys().getFirst().ownedPrefix()) + .isEqualTo(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX); + assertThat( + descriptor.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) + .containsExactly("canonicalPendingRecordUtf8", "absoluteExpiryEpochMillis"); + + byte[] source; + try (var input = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(input).isNotNull(); + source = input.readAllBytes(); + } + String lua = new String(source, StandardCharsets.UTF_8); + assertThat(sha256(source)).isEqualTo(descriptor.sha256()); + assertThat(lua) + .contains("if current ~= record then") + .contains("if currentExpiry ~= targetExpiry then") + .contains("redis.call('SET', key, record, 'PXAT', ARGV[2], 'NX')") + .contains("if type(stored) ~= 'table' or stored.ok ~= 'OK' then") + .doesNotContain("stored ~= 'OK'"); + } + + @Test + void committedActivationDescriptorAndLuaPinOnlyExactLifecycleByteChange() throws Exception { + RedisScriptDescriptor descriptor = + new AccountGameplayDelegationRedisScriptContribution() + .descriptors().stream() + .filter( + item -> + item.scriptId() + .equals( + AccountGameplayDelegationRedisClient.ACTIVE_TRANSITION_SCRIPT_ID)) + .findFirst() + .orElseThrow(); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(descriptor.keys()).hasSize(1); + assertThat(descriptor.keys().getFirst().name()).isEqualTo("tokenRecord"); + assertThat(descriptor.keys().getFirst().ownedPrefix()) + .isEqualTo(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX); + assertThat(descriptor.keys().getFirst().hashTagDeclaration()) + .isEqualTo(RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + assertThat( + descriptor.arguments().stream().map(RedisScriptDescriptor.ArgumentSpec::name).toList()) + .containsExactly( + "exactCanonicalPendingRecordUtf8", + "exactCanonicalActiveRecordUtf8", + "originalAbsoluteExpiryEpochMillis"); + + byte[] source; + try (var input = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(input).isNotNull(); + source = input.readAllBytes(); + } + String lua = new String(source, StandardCharsets.UTF_8); + assertThat(sha256(source)).isEqualTo(descriptor.sha256()); + assertThat(lua) + .contains("string.gsub(pending, '\"registryVersion\":1', '\"registryVersion\":2')") + .contains("string.gsub(versioned, '\"state\":\"pending\"', '\"state\":\"active\"')") + .contains("if current == pending then") + .contains("if current == active then") + .contains("'PXAT', deadline, 'XX'") + .contains("if type(stored) ~= 'table' or stored.ok ~= 'OK' then") + .doesNotContain("cjson.decode", "cjson.encode", "redis.call('EXPIRE'", "PSETEX"); + } + + @Test + void committedActivationRequiresRepositoryProducedOwnerValueAndDoesNotOpenWithoutIt() { + StatefulRedisConnection connection = connection(); + AccountGameplayDelegationRedisClient client = client(connection); + + assertThatThrownBy(() -> client.activateCommittedPending(null, null)) + .isInstanceOf(NullPointerException.class); + + verify(connection, org.mockito.Mockito.never()).sync(); + verify(connection, org.mockito.Mockito.never()).close(); + } + + @Test + void committedActivationChangesOnlyLifecycleFieldsAndExactRetryKeepsAbsoluteDeadline() + throws Exception { + ActivationFixture fixture = activationFixture(); + + var activated = + fixture.client().activateCommittedPending(fixture.pendingReceipt(), fixture.owner()); + assertThat(activated.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.ACTIVATED); + assertThat(activated.absoluteExpiryMillis()).isEqualTo(fixture.absoluteExpiryMillis()); + assertThat(fixture.absoluteExpiry().get()).isEqualTo(fixture.absoluteExpiryMillis()); + var active = + GameSessionAccountDelegationRegistryRecord.decode( + fixture.registryValue().get(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + assertThat(active.state()).isEqualTo("active"); + assertThat(active.registryVersion()).isEqualTo(2L); + Map expected = new LinkedHashMap<>(fixture.pendingRecord().fields()); + expected.put("registryVersion", active.fields().get("registryVersion")); + expected.put("state", "active"); + assertThat( + active.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES)) + .containsExactly(canonicalBytes(expected)); + + var exactRetry = + fixture.client().activateCommittedPending(fixture.pendingReceipt(), fixture.owner()); + assertThat(exactRetry.outcome()) + .isEqualTo(AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome.EXACT_RETRY); + assertThat(exactRetry.canonicalActiveRecordSha256()) + .isEqualTo(activated.canonicalActiveRecordSha256()); + assertThat(fixture.absoluteExpiry().get()).isEqualTo(fixture.absoluteExpiryMillis()); + verify(fixture.commands(), times(3)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + verify(fixture.commands(), times(3)) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(fixture.connection(), times(3)).close(); + } + + @Test + void pendingRecordExpiryUsesInjectedClockAndRejectsExactExpiryBoundary() throws Exception { + ActivationFixture fixture = activationFixture(); + long expirySecond = fixture.pendingRecord().expiresAtEpochSecond(); + long expiryMillis = fixture.absoluteExpiryMillis(); + byte[] pendingBytes = fixture.registryValue().get().clone(); + when(fixture.commands().type(any(byte[].class))).thenReturn("string"); + when(fixture.commands().pttl(any(byte[].class))).thenReturn(1_000L); + + AccountGameplayDelegationRedisClient beforeExpiry = + client( + () -> fixture.connection(), + Clock.fixed(Instant.ofEpochSecond(expirySecond - 1L), ZoneOffset.UTC)); + beforeExpiry.requirePendingRecord( + fixture.pendingRecord().tokenHash(), pendingBytes, expiryMillis); + + AccountGameplayDelegationRedisClient atExpiry = + client( + () -> fixture.connection(), + Clock.fixed(Instant.ofEpochSecond(expirySecond), ZoneOffset.UTC)); + assertThatThrownBy( + () -> + atExpiry.requirePendingRecord( + fixture.pendingRecord().tokenHash(), pendingBytes, expiryMillis)) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } + + @Test + void pendingRecordAbsoluteExpiryRejectsExactMillisecondBoundary() throws Exception { + ActivationFixture fixture = activationFixture(); + AccountGameplayDelegationRedisClient atDeadline = + client( + () -> fixture.connection(), + Clock.fixed(Instant.ofEpochMilli(fixture.absoluteExpiryMillis()), ZoneOffset.UTC)); + + assertThatThrownBy( + () -> + atDeadline.requirePendingRecord( + fixture.pendingRecord().tokenHash(), + fixture.registryValue().get(), + fixture.absoluteExpiryMillis())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } + + @Test + void committedActivationRejectsOwnerExpiryAtExactSecondBoundary() throws Exception { + ActivationFixture fixture = + activationFixture(Clock.fixed(Instant.ofEpochSecond(1_800_000_180L), ZoneOffset.UTC)); + + assertThatThrownBy( + () -> + fixture + .client() + .activateCommittedPending(fixture.pendingReceipt(), fixture.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(fixture.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + } + + @Test + void committedActivationRejectsChangedOwnerRecordAndMissingOrStaleRegistryValues() + throws Exception { + ActivationFixture ownerMismatch = activationFixture(); + doReturn("f".repeat(64)).when(ownerMismatch.owner()).tokenSha256(); + assertThatThrownBy( + () -> + ownerMismatch + .client() + .activateCommittedPending( + ownerMismatch.pendingReceipt(), ownerMismatch.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(ownerMismatch.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + + ActivationFixture missing = activationFixture(); + missing.registryValue().set(null); + assertThatThrownBy( + () -> + missing + .client() + .activateCommittedPending(missing.pendingReceipt(), missing.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(missing.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + + ActivationFixture stale = activationFixture(); + Map revokedFields = new LinkedHashMap<>(stale.pendingRecord().fields()); + revokedFields.put("state", "revoked"); + stale.registryValue().set(canonicalBytes(revokedFields)); + assertThatThrownBy( + () -> stale.client().activateCommittedPending(stale.pendingReceipt(), stale.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(stale.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + } + + @Test + void committedActivationRejectsWrongRoleExpiryReadbackAndInsufficientAof() throws Exception { + ActivationFixture wrongRole = activationFixture(); + doReturn("account_coord_admin").when(wrongRole.commands()).aclWhoami(); + assertThatThrownBy( + () -> + wrongRole + .client() + .activateCommittedPending(wrongRole.pendingReceipt(), wrongRole.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(wrongRole.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + + ActivationFixture wrongExpiry = activationFixture(); + doReturn(wrongExpiry.absoluteExpiryMillis() + 1L) + .when(wrongExpiry.commands()) + .pexpiretime(any(byte[].class)); + assertThatThrownBy( + () -> + wrongExpiry + .client() + .activateCommittedPending(wrongExpiry.pendingReceipt(), wrongExpiry.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(wrongExpiry.commands(), times(1)) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + + ActivationFixture wrongReadback = activationFixture(); + AtomicInteger reads = new AtomicInteger(); + doAnswer( + invocation -> + reads.incrementAndGet() == 2 + ? ascii("unexpected-active-readback") + : wrongReadback.registryValue().get().clone()) + .when(wrongReadback.commands()) + .get(any(byte[].class)); + assertThatThrownBy( + () -> + wrongReadback + .client() + .activateCommittedPending( + wrongReadback.pendingReceipt(), wrongReadback.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(wrongReadback.absoluteExpiry().get()) + .isEqualTo(wrongReadback.absoluteExpiryMillis()); + + ActivationFixture insufficientAof = activationFixture(); + doReturn(List.of(1L, 0L)) + .when(insufficientAof.commands()) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + assertThatThrownBy( + () -> + insufficientAof + .client() + .activateCommittedPending( + insufficientAof.pendingReceipt(), insufficientAof.owner())) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode( + insufficientAof.registryValue().get(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES) + .state()) + .isEqualTo("active"); + verify(insufficientAof.commands(), times(2)).get(any(byte[].class)); + } + + /** Unit-only fake owner metadata exercises low-level Lua mechanics; it is not COMMITTED proof. */ + private static ActivationFixture activationFixture() throws Exception { + return activationFixture(Clock.fixed(Instant.ofEpochSecond(1_800_000_000L), ZoneOffset.UTC)); + } + + private static ActivationFixture activationFixture(Clock clock) throws Exception { + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + var authority = + new net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord + .AccountAuthoritySnapshot( + ACCOUNT_ID, + 7L, + 7L, + 11L, + 11L, + 11L, + 11L, + Optional.of( + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + "11", accountStream, "10"))); + long now = 1_800_000_000L; + PendingIntent intent = + new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + Math.addExact(now, 180L), + authority, + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()); + String compact = compactToken(intent); + EvidenceBundleReference bundle = + new EvidenceBundleReference("1", "11", "9", "12345678", "d".repeat(64)); + GameSessionAccountDelegationRegistryRecord pendingRecord = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact, + "42", + new IssuanceBinding( + intent.operationId().toString(), + intent.requestId().toString(), + AccountGameplayDelegationIssuanceRepository.requestDigest(intent), + ACCOUNT_ID.toString()), + authority, + bundle, + now, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + byte[] pendingBytes = + pendingRecord.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + long deadline = + Math.addExact(Math.multiplyExact(intent.expiresAtEpochSecond(), 1_000L), 30_000L); + + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + intent.operationId(), + intent.requestId(), + ACCOUNT_ID, + intent.callerWorkload(), + intent.callerContextId(), + intent.credentialRequestBinding(), + AccountGameplayDelegationIssuanceRepository.requestDigest(intent), + intent.tokenJti(), + intent.issuedAtEpochSecond(), + intent.notBeforeEpochSecond(), + intent.expiresAtEpochSecond()); + CommittedCandidateVerificationData owner = mock(CommittedCandidateVerificationData.class); + var signer = mock(AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence.class); + when(signer.promotionStatus()).thenReturn("COMMITTED"); + when(signer.targetKid()).thenReturn(pendingRecord.kid()); + when(signer.targetGeneration()).thenReturn(pendingRecord.signerGeneration()); + when(owner.identity()).thenReturn(identity); + when(owner.authoritySnapshot()).thenReturn(authority); + when(owner.evidenceBundleReference()).thenReturn(bundle); + when(owner.tokenSha256()).thenReturn(pendingRecord.tokenHash()); + when(owner.signerKid()).thenReturn(pendingRecord.kid()); + when(owner.signerGeneration()).thenReturn(pendingRecord.signerGeneration()); + when(owner.canonicalRegistryRecordSha256()).thenReturn(sha256(pendingBytes)); + when(owner.commitProofSha256()).thenReturn("c".repeat(64)); + when(owner.signerCorrespondence()).thenReturn(signer); + + StatefulRedisConnection connection = connection(); + RedisCommands commands = connection.sync(); + AtomicReference stored = new AtomicReference<>(pendingBytes.clone()); + AtomicLong observedExpiry = new AtomicLong(deadline); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L); + when(commands.get(any(byte[].class))) + .thenAnswer(invocation -> stored.get() == null ? null : stored.get().clone()); + when(commands.pexpiretime(any(byte[].class))).thenAnswer(invocation -> observedExpiry.get()); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + + AccountGameplayDelegationRedisClient client = client(() -> connection, clock); + var pendingReceipt = client.registerPending(pendingRecord.tokenHash(), pendingBytes, deadline); + doAnswer( + invocation -> { + Object[] rawArguments = invocation.getRawArguments(); + if (rawArguments.length != 4 + || !(rawArguments[3] instanceof byte[][] args) + || args.length != 3 + || !Arrays.equals( + args[2], Long.toString(deadline).getBytes(StandardCharsets.US_ASCII))) { + return -1L; + } + byte[] current = stored.get(); + if (Arrays.equals(current, args[0])) { + stored.set(args[1].clone()); + return 1L; + } + if (Arrays.equals(current, args[1])) { + return 0L; + } + return -1L; + }) + .when(commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + return new ActivationFixture( + client, + connection, + commands, + pendingRecord, + pendingReceipt, + owner, + stored, + observedExpiry, + deadline); + } + + private static String compactToken(PendingIntent intent) throws Exception { + Map header = Map.of("alg", "RS256", "kid", "fixture-key", "typ", "JWT"); + Map claims = + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", ACCOUNT_ID.toString()), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("jti", intent.tokenJti().toString()), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", intent.expiresAtEpochSecond()), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + intent.authoritySnapshot().issuerGeneration(), + intent.authoritySnapshot().accountGeneration(), + intent.authoritySnapshot().accountSecurityCutoff())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence()))); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString(canonicalBytes(header)) + + "." + + encoder.encodeToString(canonicalBytes(claims)) + + "." + + encoder.encodeToString(ascii("test-only-not-a-verified-signature")); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static List membershipPage(UUID tenant, int firstSequence, int lastSequence) { + List candidates = new java.util.ArrayList<>(lastSequence - firstSequence + 1); + for (int sequence = firstSequence; sequence <= lastSequence; sequence++) { + String sequenceText = Integer.toString(sequence); + candidates.add( + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.membershipBytes( + ACCOUNT_ID, tenant, sequenceText, Integer.toString(sequence + 1), "1")); + } + return List.copyOf(candidates); + } + + private static AccountGameplayDelegationRedisClient client( + StatefulRedisConnection connection) { + return client(() -> connection); + } + + private static AccountGameplayDelegationRedisClient client( + AccountCoordinationPinnedConnectionProvider connectionProvider) { + return client(connectionProvider, Clock.systemUTC()); + } + + private static AccountGameplayDelegationRedisClient client( + AccountCoordinationPinnedConnectionProvider connectionProvider, Clock clock) { + return new AccountGameplayDelegationRedisClient( + connectionProvider, + RedisScriptCatalog.fromContributions( + List.of( + new AccountGameplayDelegationRedisScriptContribution(), + new net.firedevops.firemud.accountservice.service + .AccountGenerationProjectionRedisScriptContribution())), + new AcknowledgementRequirements(1, 1, 1_000), + clock, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + AccountGameplayDelegationRedisClientTest.class.getClassLoader()); + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection connection() { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisCommands commands = mock(RedisCommands.class); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + when(commands.pttl(any(byte[].class))).thenReturn(-1L); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + return connection; + } + + private static IssuerAccountSourceSnapshot snapshot() { + return AccountGameplayDelegationAuthorityProjectionTest.DonorOwnerReadRegressions.snapshot( + 1L, 11L); + } + + private static SourceCheckpoint checkpoint(String stream, long sequence) { + return new SourceCheckpoint( + stream, + sequence, + Optional.of("event-" + sequence), + Optional.of("sha256:" + "a".repeat(64))); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static byte[] issuerProjectionKey() { + return ascii( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER); + } + + private static byte[] accountProjectionKey() { + return ascii(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + ACCOUNT_ID); + } + + private record ActivationFixture( + AccountGameplayDelegationRedisClient client, + StatefulRedisConnection connection, + RedisCommands commands, + GameSessionAccountDelegationRegistryRecord pendingRecord, + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt pendingReceipt, + CommittedCandidateVerificationData owner, + AtomicReference registryValue, + AtomicLong absoluteExpiry, + long absoluteExpiryMillis) {} + + private static String sha1(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(bytes)); + } + + private static String sha256(byte[] bytes) throws NoSuchAlgorithmException { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeServiceTest.java new file mode 100644 index 0000000000..a438e63d37 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeServiceTest.java @@ -0,0 +1,93 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.support.AopUtils; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.interceptor.TransactionInterceptor; + +class AccountGameplayDelegationResponseEnvelopeServiceTest { + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final CallerIdentity CALLER = + new CallerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436")); + + @Test + void delegatesCandidateSealingAndReturnsOnlyNonAuthorizingMetadata() + throws ReflectiveOperationException { + AccountGameplayDelegationResponseEnvelopeRepository repository = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationResponseEnvelopeService service = + new AccountGameplayDelegationResponseEnvelopeService(repository); + String transientJwt = "candidate.jwt.bytes"; + SealedCandidateObservation observation = + new SealedCandidateObservation( + UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"), + REQUEST_ID, + "a".repeat(64), + 13L, + 1_896_602_520_000L, + "b".repeat(64), + 64); + when(repository.sealPendingCandidate(REQUEST_ID, CALLER, transientJwt)).thenReturn(observation); + + assertThat(service.sealPendingCandidate(REQUEST_ID, CALLER, transientJwt)) + .isEqualTo(observation); + assertThat(observation.toString()).doesNotContain(transientJwt); + verify(repository).sealPendingCandidate(REQUEST_ID, CALLER, transientJwt); + + Transactional transaction = + AccountGameplayDelegationResponseEnvelopeService.class + .getMethod("sealPendingCandidate", UUID.class, CallerIdentity.class, String.class) + .getAnnotation(Transactional.class); + assertThat(transaction.propagation()).isEqualTo(Propagation.MANDATORY); + } + + @Test + void springClassProxyEnforcesMandatoryTransactionBeforeDelegating() { + AccountGameplayDelegationResponseEnvelopeRepository repository = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any())) + .thenThrow(new IllegalTransactionStateException("No existing transaction")); + + ProxyFactory proxyFactory = + new ProxyFactory(new AccountGameplayDelegationResponseEnvelopeService(repository)); + proxyFactory.setProxyTargetClass(true); + proxyFactory.addAdvice( + new TransactionInterceptor(transactionManager, new AnnotationTransactionAttributeSource())); + + AccountGameplayDelegationResponseEnvelopeService proxiedService = + (AccountGameplayDelegationResponseEnvelopeService) proxyFactory.getProxy(); + + assertThat(AopUtils.isCglibProxy(proxiedService)).isTrue(); + assertThatThrownBy(() -> proxiedService.sealPendingCandidate(REQUEST_ID, CALLER, "candidate")) + .isInstanceOf(IllegalTransactionStateException.class); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactionManager).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); + verifyNoInteractions(repository); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwnerTest.java new file mode 100644 index 0000000000..b29e53b04a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwnerTest.java @@ -0,0 +1,228 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveryPreflight; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner.ActiveCommittedIssuanceObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountGameplayDelegationResponseRecoveryOwnerTest { + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID OTHER_REQUEST_ID = + UUID.fromString("58102ea4-9245-4ddc-a68c-3ff41dcf96af"); + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("674cb504-8f4c-4d06-86c6-7b72f79cae74"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID OTHER_CONTEXT_ID = + UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"); + private static final CallerIdentity CALLER = + new CallerIdentity("spiffe://firemud/ns/test/sa/game-session-service", CALLER_CONTEXT_ID); + private static final byte[] EXACT_JWT = + "header.payload.signature".getBytes(StandardCharsets.US_ASCII); + private static final long ORIGINAL_EXPIRY_EPOCH_SECOND = 1_896_602_520L; + + @Test + void activatesBeforeEnvelopeRecoveryAndReturnsExactRepeatedCredentialWithoutRenewingExpiry() { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + ActiveCommittedIssuanceObservation active = mock(ActiveCommittedIssuanceObservation.class); + RecoveredCredential credential = credential(); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenReturn(preflight()); + when(committedOwner.activateCommittedIssuance(REQUEST_ID)).thenReturn(active); + when(responseEnvelopes.recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active)) + .thenReturn(credential); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(0)); + + RecoveredCredential first = owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER); + RecoveredCredential retry = owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER); + + assertThat(first.compactJwtBytes()).containsExactly(EXACT_JWT); + assertThat(retry.compactJwtBytes()).containsExactly(EXACT_JWT); + assertThat(first.expiresAtEpochSecond()).isEqualTo(ORIGINAL_EXPIRY_EPOCH_SECOND); + assertThat(retry.expiresAtEpochSecond()).isEqualTo(ORIGINAL_EXPIRY_EPOCH_SECOND); + InOrder sequence = inOrder(responseEnvelopes, committedOwner); + sequence.verify(responseEnvelopes).preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER); + sequence.verify(committedOwner).activateCommittedIssuance(REQUEST_ID); + sequence + .verify(responseEnvelopes) + .recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active); + sequence.verify(responseEnvelopes).preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER); + sequence.verify(committedOwner).activateCommittedIssuance(REQUEST_ID); + sequence + .verify(responseEnvelopes) + .recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active); + verify(committedOwner, times(2)).activateCommittedIssuance(REQUEST_ID); + } + + @Test + void requestWorkloadContextAndAccountMismatchNeverReachActivation() { + assertRejectedBeforeActivation(OTHER_REQUEST_ID, ACCOUNT_ID, CALLER); + assertRejectedBeforeActivation(REQUEST_ID, OTHER_ACCOUNT_ID, CALLER); + assertRejectedBeforeActivation( + REQUEST_ID, + ACCOUNT_ID, + new CallerIdentity("spiffe://firemud/ns/other/sa/game-session-service", CALLER_CONTEXT_ID)); + assertRejectedBeforeActivation( + REQUEST_ID, ACCOUNT_ID, new CallerIdentity(CALLER.workload(), OTHER_CONTEXT_ID)); + } + + @Test + void expiredOwnerHorizonNeverActivatesOrDecrypts() { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenThrow(new ResponseRecoveryExpiredException()); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(0)); + + assertThatThrownBy(() -> owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER)) + .isInstanceOf(ResponseRecoveryExpiredException.class) + .hasNoCause(); + + verify(committedOwner, never()).activateCommittedIssuance(any()); + verify(responseEnvelopes, never()).recoverCommittedResponse(any(), any(), any(), any()); + } + + @Test + void activationNetworkFailureReturnsNoCredentialAndSkipsEnvelopeRead() { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenReturn(preflight()); + when(committedOwner.activateCommittedIssuance(REQUEST_ID)) + .thenThrow(new AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException()); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(0)); + + assertThatThrownBy(() -> owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + + verify(responseEnvelopes, never()).recoverCommittedResponse(any(), any(), any(), any()); + } + + @Test + void sqlCommitFailureAfterDecryptionDoesNotReturnCredential() { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + ActiveCommittedIssuanceObservation active = mock(ActiveCommittedIssuanceObservation.class); + RecoveredCredential credential = credential(); + when(responseEnvelopes.preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, CALLER)) + .thenReturn(preflight()); + when(committedOwner.activateCommittedIssuance(REQUEST_ID)).thenReturn(active); + when(responseEnvelopes.recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active)) + .thenReturn(credential); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(2)); + + assertThatThrownBy(() -> owner.recoverInitialLoginResponse(REQUEST_ID, ACCOUNT_ID, CALLER)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + + verify(responseEnvelopes).recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, CALLER, active); + } + + private static void assertRejectedBeforeActivation( + UUID requestId, UUID accountId, CallerIdentity caller) { + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes = + mock(AccountGameplayDelegationResponseEnvelopeRepository.class); + AccountGameplayDelegationCommittedIssuanceOwner committedOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + when(responseEnvelopes.preflightCommittedRecovery(any(), any(), any())).thenReturn(preflight()); + AccountGameplayDelegationResponseRecoveryOwner owner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseEnvelopes, committedOwner, new TestTransactionManager(0)); + + assertThatThrownBy(() -> owner.recoverInitialLoginResponse(requestId, accountId, caller)) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class) + .hasNoCause(); + + verify(committedOwner, never()).activateCommittedIssuance(any()); + verify(responseEnvelopes, never()).recoverCommittedResponse(any(), any(), any(), any()); + } + + private static RecoveryPreflight preflight() { + return new RecoveryPreflight( + UUID.fromString("5414e55d-0393-4561-ac3d-cb916a08d3f0"), + REQUEST_ID, + ACCOUNT_ID, + CALLER.workload(), + CALLER.contextId(), + "a".repeat(64), + UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"), + ORIGINAL_EXPIRY_EPOCH_SECOND, + Math.multiplyExact(ORIGINAL_EXPIRY_EPOCH_SECOND, 1_000L)); + } + + private static RecoveredCredential credential() { + RecoveredCredential value = mock(RecoveredCredential.class); + when(value.compactJwtBytes()).thenReturn(EXACT_JWT.clone()); + when(value.expiresAtEpochSecond()).thenReturn(ORIGINAL_EXPIRY_EPOCH_SECOND); + return value; + } + + private static final class TestTransactionManager implements PlatformTransactionManager { + private final int failAtCommit; + private int commitCount; + + private TestTransactionManager(int failAtCommit) { + this.failAtCommit = failAtCommit; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + if (failAtCommit > 0 && commitCount == failAtCommit) { + throw new IllegalStateException("SQL commit failed"); + } + } + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java new file mode 100644 index 0000000000..447680ddc7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java @@ -0,0 +1,1450 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AccountIdentitySource; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.AuthoritySourceVersions; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.BundleReference; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OperationIdentity; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OutboxCheckpoint; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.OwnerEvaluation; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.BoundTokenCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingSigningIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.PendingCandidateCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountGameplayDelegationSignerTest { + private static final Instant NOW = Instant.parse("2026-10-05T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final String ENVIRONMENT = "staging"; + private static final String CLUSTER = "cluster-a"; + private static final String NAMESPACE = "firemud"; + private static final String MATERIALIZER_REVISION = "materializer-r1"; + private static final String API_REVISION = "api-revision-1"; + private static final String MATERIALIZER_DIGEST = "b".repeat(64); + private static final String API_DIGEST = "c".repeat(64); + private static final String SERVING_CA_DIGEST = "e".repeat(64); + private static final String CLUSTER_UID = "44444444-4444-4444-8444-444444444444"; + private static final String NAMESPACE_UID = "55555555-5555-4555-8555-555555555555"; + private static final String CONFIG_MAP_UID = "66666666-6666-4666-8666-666666666666"; + private static final String API_ORIGIN = "https://kubernetes.example.test:6443"; + private static final UUID ACCOUNT_ID = UUID.fromString("a6a2af33-2e50-4092-934b-43c5bce12f7b"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("c5c31332-e560-41c8-a55a-97674e7a317c"); + private static final UUID REQUEST_ID = UUID.fromString("f14ca47a-2316-47b7-a38f-f9b693ff8afc"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("e16fdce5-96eb-49e9-a1bd-3f429816cbf0"); + private static final UUID TOKEN_JTI = UUID.fromString("1a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"); + private static final UUID GENERATION_OPERATION_ID = + UUID.fromString("7af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final UUID PROMOTION_OPERATION_ID = + UUID.fromString("8af097ea-b1d1-42ea-9f24-46aeb211a779"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String GENERATION = "42"; + private static final String KID = "account-key-42"; + private static final String WORKLOAD = "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static KeyPair signerPair; + private static KeyPair mismatchedPair; + + @TempDir Path temporaryDirectory; + + @BeforeAll + static void generateEphemeralRsaPairs() throws Exception { + ensureEphemeralRsaPairs(); + } + + private static synchronized void ensureEphemeralRsaPairs() throws Exception { + if (signerPair != null && mismatchedPair != null) return; + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + signerPair = generator.generateKeyPair(); + mismatchedPair = generator.generateKeyPair(); + } + + @Test + void remainsUnwiredAndFailsClosedWithoutProtectedSignerTrust() { + AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtSignerMaterializerTrustBinding trust = + new AccountJwtSignerMaterializerTrustBinding(false, ""); + AccountJwtJwksApiBinding apiBinding = new AccountJwtJwksApiBinding(); + AccountGameplayDelegationResponseEnvelopeService envelopeService = + mock(AccountGameplayDelegationResponseEnvelopeService.class); + InertTransactionManager transactionManager = new InertTransactionManager(); + AccountJwtJwksConfigMapClient configMapClient = mock(AccountJwtJwksConfigMapClient.class); + AccountJwtJwksTrustedSource trustedJwksSource = + new AccountJwtJwksTrustedSource( + configMapClient, + trust, + desired, + mock(AccountJwtJwksPublicationRepository.class), + transactionManager); + AccountGameplayDelegationSigner signer = + new AccountGameplayDelegationSigner( + issuance, + desired, + trust, + apiBinding, + trustedJwksSource, + envelopeService, + transactionManager, + Clock.systemUTC()); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> signer.signPendingCandidate(UUID.randomUUID())); + assertFalse(AccountGameplayDelegationSigner.class.isAnnotationPresent(Service.class)); + verifyNoInteractions(issuance, desired, envelopeService); + verifyNoInteractions(configMapClient); + } + + @Test + void signsCanonicalPendingCandidateAndSealsOnlyMetadataWithLiveSourceOutsideTransactions() + throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + + // The owner/source collaborators are isolated mocks; this checks call placement and ordering, + // not Spring proxy propagation or live API availability. + AccountGameplayDelegationSigner.CandidateOutcome outcome = + fixture.signer.signPendingCandidate(REQUEST_ID); + assertNotNull(outcome); + String transientJwt = fixture.transientJwt.get(); + AccountGameplayDelegationSigner.PendingCandidateVerificationProof proof = + outcome.verificationProof(); + + assertNotNull(proof); + assertEquals(ISSUANCE_OPERATION_ID, outcome.operationId()); + assertEquals(REQUEST_ID, outcome.requestId()); + assertEquals(fixture.boundRecord.get().tokenHash(), outcome.tokenSha256()); + assertEquals(ISSUANCE_OPERATION_ID.toString(), fixture.boundRecord.get().operationId()); + assertEquals(REQUEST_ID.toString(), fixture.boundRecord.get().requestId()); + assertEquals(TOKEN_JTI.toString(), fixture.boundRecord.get().jti()); + assertEquals(ACCOUNT_ID.toString(), fixture.boundRecord.get().accountId()); + assertEquals("pending", fixture.boundRecord.get().state()); + assertEquals(GENERATION, outcome.signerGeneration()); + assertEquals(KID, outcome.signerKid()); + assertEquals(ISSUANCE_OPERATION_ID, proof.operationId()); + assertEquals(REQUEST_ID, proof.requestId()); + assertEquals(ACCOUNT_ID, proof.accountId()); + assertEquals(TOKEN_JTI, proof.tokenJti()); + assertEquals( + fixture.evidenceBundle.canonicalSha256(), + proof.evidenceBundleReference().canonicalSha256()); + assertEquals(outcome.tokenSha256(), proof.tokenSha256()); + assertEquals(fixture.evidenceReference, proof.evidenceBundleReference()); + assertEquals(fixture.authoritySnapshot, proof.authoritySnapshot()); + assertEquals(fixture.pendingIdentity.issuedAtEpochSecond(), proof.issuedAtEpochSecond()); + assertEquals(fixture.pendingIdentity.notBeforeEpochSecond(), proof.notBeforeEpochSecond()); + assertEquals(fixture.pendingIdentity.expiresAtEpochSecond(), proof.expiresAtEpochSecond()); + assertEquals(REQUEST_DIGEST, proof.identity().requestDigest()); + assertEquals(WORKLOAD, proof.identity().callerWorkload()); + assertEquals(CALLER_CONTEXT_ID, proof.identity().callerContextId()); + assertEquals(fixture.authoritySnapshot.issuanceFence(), proof.issuanceFence()); + assertEquals(GENERATION_OPERATION_ID, proof.signerOperationId()); + assertEquals(GENERATION, proof.signerGeneration()); + assertEquals(KID, proof.signerKid()); + assertEquals("COMMITTED", proof.signerCorrespondence().promotionStatus()); + assertEquals(PROMOTION_OPERATION_ID, proof.signerCorrespondence().promotionOperationId()); + assertEquals(GENERATION_OPERATION_ID, proof.signerCorrespondence().generationOperationId()); + assertEquals(fixture.sourceIdentity, proof.signerCorrespondence().publicJwksSourceIdentity()); + assertEquals("13", proof.signerCorrespondence().privatePromotionObservedResourceVersion()); + assertEquals("b".repeat(64), proof.signerCorrespondence().privatePromotionReceiptDigest()); + assertEquals("20", proof.signerCorrespondence().priorPublicResourceVersion()); + assertEquals("21", proof.signerCorrespondence().observedPublicResourceVersion()); + assertEquals("c".repeat(64), proof.signerCorrespondence().publicDataDigest()); + assertEquals("d".repeat(64), proof.signerCorrespondence().publicReceiptDigest()); + assertEquals(outcome.sealedCandidate(), proof.sealedCandidate()); + assertTrue(proof.canonicalRegistryRecordSha256().matches("[0-9a-f]{64}")); + assertEquals( + fixture.evidenceBundle.canonicalSha256(), + outcome.sealedCandidate().authorityEvidenceBundleSha256()); + assertFalse(outcome.toString().contains(transientJwt)); + assertFalse(proof.toString().contains(transientJwt)); + assertFalse(proof.signerCorrespondence().toString().contains(transientJwt)); + assertProofHasNoPublicConstructionOrMutableAggregateFields(); + assertEquals(3, fixture.publicSourceLoadCount.get()); + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + verify(fixture.issuance, times(2)).readPendingSigningIdentity(REQUEST_ID); + verify(fixture.issuance).bindSignedCandidate(REQUEST_ID, transientJwt, GENERATION); + verify(fixture.issuance, times(2)).readPendingRegistryCandidate(REQUEST_ID); + verify(fixture.envelopeService) + .sealPendingCandidate(eq(REQUEST_ID), any(CallerIdentity.class), eq(transientJwt)); + verify(fixture.desiredState, times(3)) + .readCurrentCommittedSigner( + eq(fixture.accountBinding), eq(fixture.trustFence), eq(API_DIGEST), eq(API_REVISION)); + + var order = inOrder(fixture.issuance, fixture.envelopeService); + order.verify(fixture.issuance, times(2)).readPendingSigningIdentity(REQUEST_ID); + order.verify(fixture.issuance).bindSignedCandidate(REQUEST_ID, transientJwt, GENERATION); + order.verify(fixture.issuance).readPendingRegistryCandidate(REQUEST_ID); + order + .verify(fixture.envelopeService) + .sealPendingCandidate(eq(REQUEST_ID), any(CallerIdentity.class), eq(transientJwt)); + order.verify(fixture.issuance).readPendingRegistryCandidate(REQUEST_ID); + } + + @Test + void revalidatesPrivateProofOnlyInsideWritableTransactionAgainstCurrentOwner() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + AccountGameplayDelegationSigner.PendingCandidateVerificationProof proof = + fixture.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.requireCurrentCommittedSigner(proof)); + + TransactionTemplate writable = new TransactionTemplate(fixture.transactionManager); + int loadsBeforeOwnerCheck = fixture.publicSourceLoadCount.get(); + writable.execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + }); + assertEquals(loadsBeforeOwnerCheck, fixture.publicSourceLoadCount.get()); + + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + readOnly.execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + })); + } + + @Test + void revalidatesRepositoryIssuedCommittedSnapshotOnlyInsideWritableTransaction() + throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + var proof = fixture.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData committed = committedData(proof); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.requireCurrentCommittedSigner(committed)); + + int loadsBeforeOwnerCheck = fixture.publicSourceLoadCount.get(); + new TransactionTemplate(fixture.transactionManager) + .execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + }); + assertEquals(loadsBeforeOwnerCheck, fixture.publicSourceLoadCount.get()); + + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + readOnly.execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + })); + } + + @Test + void committedSnapshotRecheckDeniesChangedSignerOrWithdrawnProtectedTrust() throws Exception { + Fixture changedOwner = new Fixture(temporaryDirectory, false); + var changedProof = changedOwner.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData changedSnapshot = committedData(changedProof); + changedOwner.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(changedOwner.transactionManager) + .execute( + status -> { + changedOwner.signer.requireCurrentCommittedSigner(changedSnapshot); + return null; + })); + + Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); + var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData trustSnapshot = committedData(trustProof); + withdrawnTrust.withdrawMaterializerTrust(); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(withdrawnTrust.transactionManager) + .execute( + status -> { + withdrawnTrust.signer.requireCurrentCommittedSigner(trustSnapshot); + return null; + })); + } + + private static CommittedCandidateVerificationData committedData( + AccountGameplayDelegationSigner.PendingCandidateVerificationProof proof) { + var verifiedIdentity = proof.identity(); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + verifiedIdentity.operationId(), + verifiedIdentity.requestId(), + verifiedIdentity.accountId(), + verifiedIdentity.callerWorkload(), + verifiedIdentity.callerContextId(), + AccountGameplayCredentialRequestBindingFixture.binding(), + verifiedIdentity.requestDigest(), + verifiedIdentity.tokenJti(), + verifiedIdentity.issuedAtEpochSecond(), + verifiedIdentity.notBeforeEpochSecond(), + verifiedIdentity.expiresAtEpochSecond()); + CommittedCandidateVerificationData committed = mock(CommittedCandidateVerificationData.class); + when(committed.identity()).thenReturn(identity); + when(committed.authoritySnapshot()).thenReturn(proof.authoritySnapshot()); + when(committed.evidenceBundleReference()).thenReturn(proof.evidenceBundleReference()); + when(committed.tokenSha256()).thenReturn(proof.tokenSha256()); + when(committed.signerKid()).thenReturn(proof.signerKid()); + when(committed.signerGeneration()).thenReturn(proof.signerGeneration()); + when(committed.canonicalRegistryRecordSha256()) + .thenReturn(proof.canonicalRegistryRecordSha256()); + when(committed.commitProofSha256()).thenReturn("e".repeat(64)); + when(committed.signerCorrespondence()).thenReturn(proof.signerCorrespondence()); + when(committed.envelopeKeyId()).thenReturn("response-key-1"); + when(committed.envelopeSha256()).thenReturn("f".repeat(64)); + when(committed.envelopeBytesLength()).thenReturn(64); + when(committed.responseRecoveryExpiryEpochMillis()) + .thenReturn(proof.sealedCandidate().responseRecoveryExpiryEpochMillis()); + return committed; + } + + @Test + void refusesVerificationProofAfterCurrentCommittedSignerChangesOrTrustIsWithdrawn() + throws Exception { + Fixture changedOwner = new Fixture(temporaryDirectory, false); + var proof = changedOwner.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + changedOwner.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + TransactionTemplate writable = new TransactionTemplate(changedOwner.transactionManager); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + writable.execute( + status -> { + changedOwner.signer.requireCurrentCommittedSigner(proof); + return null; + })); + + Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); + var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + withdrawnTrust.withdrawMaterializerTrust(); + TransactionTemplate trustTransaction = + new TransactionTemplate(withdrawnTrust.transactionManager); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + trustTransaction.execute( + status -> { + withdrawnTrust.signer.requireCurrentCommittedSigner(trustProof); + return null; + })); + } + + @Test + void responseRecoveryAcceptsACommittedSignerAfterRotationOnlyWhileItsExactKeyIsRetained() + throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + var originalProof = fixture.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData committed = committedData(originalProof); + fixture.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + fixture.sourceJwks.set( + jwksJson(signerPair, KID, mismatchedPair, "account-key-43") + .getBytes(StandardCharsets.UTF_8)); + Files.writeString(fixture.privateRoot.resolve("current.key"), "unavailable private material"); + + new TransactionTemplate(fixture.transactionManager) + .execute( + status -> { + fixture.signer.requireCurrentCommittedRecoverySigner(committed); + return null; + }); + fixture.signer.requireRetainedCommittedPublicKey(committed); + + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + verify(fixture.trustedJwksSource, times(4)).load(); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(fixture.transactionManager) + .execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + })); + } + + @Test + void responseRecoveryRejectsMissingSubstitutedExpiredOrUntrustedHistoricalKey() throws Exception { + Fixture missingKey = new Fixture(temporaryDirectory, false); + var missingProof = missingKey.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData missingCommitted = committedData(missingProof); + missingKey.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + missingKey.sourceJwks.set( + jwksJson(mismatchedPair, "account-key-43").getBytes(StandardCharsets.UTF_8)); + new TransactionTemplate(missingKey.transactionManager) + .execute( + status -> { + missingKey.signer.requireCurrentCommittedRecoverySigner(missingCommitted); + return null; + }); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> missingKey.signer.requireRetainedCommittedPublicKey(missingCommitted)); + + Fixture substitutedKey = new Fixture(temporaryDirectory, false); + var substitutedProof = + substitutedKey.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData substitutedCommitted = committedData(substitutedProof); + substitutedKey.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + substitutedKey.sourceJwks.set( + jwksJson(mismatchedPair, KID, mismatchedPair, "account-key-43") + .getBytes(StandardCharsets.UTF_8)); + new TransactionTemplate(substitutedKey.transactionManager) + .execute( + status -> { + substitutedKey.signer.requireCurrentCommittedRecoverySigner(substitutedCommitted); + return null; + }); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> substitutedKey.signer.requireRetainedCommittedPublicKey(substitutedCommitted)); + + Fixture expired = new Fixture(temporaryDirectory, false); + var expiredProof = expired.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData expiredCommitted = committedData(expiredProof); + var oldIdentity = expiredProof.identity(); + when(expiredCommitted.identity()) + .thenReturn( + new AccountGameplayDelegationPendingIdentity( + oldIdentity.operationId(), + oldIdentity.requestId(), + oldIdentity.accountId(), + oldIdentity.callerWorkload(), + oldIdentity.callerContextId(), + AccountGameplayCredentialRequestBindingFixture.binding(), + oldIdentity.requestDigest(), + oldIdentity.tokenJti(), + oldIdentity.issuedAtEpochSecond(), + oldIdentity.notBeforeEpochSecond(), + NOW.getEpochSecond() - 1L)); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(expired.transactionManager) + .execute( + status -> { + expired.signer.requireCurrentCommittedRecoverySigner(expiredCommitted); + return null; + })); + + Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); + var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + CommittedCandidateVerificationData trustCommitted = committedData(trustProof); + withdrawnTrust.withdrawMaterializerTrust(); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + new TransactionTemplate(withdrawnTrust.transactionManager) + .execute( + status -> { + withdrawnTrust.signer.requireCurrentCommittedRecoverySigner(trustCommitted); + return null; + })); + } + + @Test + void refusesVerificationProofWhenPromotionReceiptFenceNoLongerMatches() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + var proof = fixture.signer.signPendingCandidate(REQUEST_ID).verificationProof(); + fixture.mismatchPrivatePromotionObservation(); + + TransactionTemplate writable = new TransactionTemplate(fixture.transactionManager); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + writable.execute( + status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + })); + } + + @Test + void deniesWhenCommittedSignerEvidenceIsMissingBeforeReadingIssuanceOrJwks() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.returnMissingCommittedEvidence(); + + AccountGameplayDelegationSigner.SigningUnavailableException failure = + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + assertEquals( + "Account gameplay delegation candidate is unavailable or ambiguous", failure.getMessage()); + assertNull(failure.getCause()); + verifyNoInteractions(fixture.issuance, fixture.trustedJwksSource, fixture.envelopeService); + } + + @Test + void rejectsMismatchedLiveJwksBeforeBindingTheSignedCandidate() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.useSourceJwks(mismatchedPair); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(fixture.issuance).readPendingSigningIdentity(REQUEST_ID); + // The initial pin read is followed by the cache's independent source parse/refresh. + assertEquals(2, fixture.publicSourceLoadCount.get()); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + verifyNoInteractions(fixture.envelopeService); + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + } + + @Test + void rejectsPublicProjectionDriftAfterSigningAndBeforeCandidatePersistence() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.changeSourceJwksOnLoad(3, jwksJson(mismatchedPair).getBytes(StandardCharsets.UTF_8)); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + assertEquals(3, fixture.publicSourceLoadCount.get()); + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + verifyNoInteractions(fixture.envelopeService); + } + + private static void assertProofHasNoPublicConstructionOrMutableAggregateFields() { + Class proofType = AccountGameplayDelegationSigner.PendingCandidateVerificationProof.class; + var constructors = proofType.getDeclaredConstructors(); + assertEquals(1, constructors.length); + assertTrue(java.lang.reflect.Modifier.isPrivate(constructors[0].getModifiers())); + assertNoMutableAggregateFields(proofType); + assertNoMutableAggregateFields(AccountGameplayDelegationSigner.VerifiedPendingIdentity.class); + assertNoMutableAggregateFields( + AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence.class); + } + + private static void assertNoMutableAggregateFields(Class type) { + for (java.lang.reflect.Field field : type.getDeclaredFields()) { + if (field.isSynthetic()) continue; + assertFalse(field.getType().isArray(), type.getSimpleName() + " exposes array storage"); + assertFalse( + Map.class.isAssignableFrom(field.getType()), + type.getSimpleName() + " exposes mutable map storage"); + } + } + + @Test + void rejectsCommittedSignerChangeAcrossTheSigningGapBeforeBinding() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.changeCommittedSignerAfterFirstRead(mismatchedPair); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(fixture.issuance, times(2)).readPendingSigningIdentity(REQUEST_ID); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + verifyNoInteractions(fixture.envelopeService); + assertEquals(3, fixture.publicSourceLoadCount.get()); + assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); + } + + @Test + void rejectsPendingIdentityDriftAcrossTheSigningGapBeforeBinding() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.changePendingIdentityAfterFirstRead(); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(fixture.issuance, times(2)).readPendingSigningIdentity(REQUEST_ID); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + verifyNoInteractions(fixture.envelopeService); + } + + @Test + void rejectsExpiredPendingIdentityBeforePublicSourceReadOrSigning() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, true); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(fixture.issuance).readPendingSigningIdentity(REQUEST_ID); + verifyNoInteractions(fixture.trustedJwksSource, fixture.envelopeService); + verify(fixture.issuance, never()).bindSignedCandidate(any(), anyString(), anyString()); + } + + @Test + void closesOpenedPendingCredentialWhenAcquisitionTransactionCommitFails() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + PendingRegistryCandidate persisted = + new PendingRegistryCandidate( + fixture.pendingIdentity, + "d".repeat(64), + KID, + GENERATION, + fixture.pendingIdentity.expiresAtEpochSecond(), + new byte[0], + fixture.authoritySnapshot, + fixture.evidenceReference); + when(fixture.pendingSigningIdentity.persistedCandidate()).thenReturn(Optional.of(persisted)); + PendingCandidateCredential opened = mock(PendingCandidateCredential.class); + when(opened.sealedCandidate()) + .thenReturn( + sealedObservation( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + fixture.evidenceBundle, + Math.multiplyExact(fixture.pendingIdentity.expiresAtEpochSecond(), 1_000L))); + when(fixture.envelopeService.openPendingCandidate(eq(REQUEST_ID), any(CallerIdentity.class))) + .thenReturn(opened); + ((InertTransactionManager) fixture.transactionManager).failNextCommit(); + + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + verify(opened).close(); + verifyNoInteractions(fixture.trustedJwksSource); + } + + @Test + void quarantinesCandidateAndEnvelopeReadbackMismatchesWithoutLeakingTransientJwt() + throws Exception { + Fixture candidateMismatch = new Fixture(temporaryDirectory, false); + candidateMismatch.returnMismatchedBoundCandidate(); + AccountGameplayDelegationSigner.SigningUnavailableException candidateFailure = + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> candidateMismatch.signer.signPendingCandidate(REQUEST_ID)); + assertNotNull(candidateMismatch.transientJwt.get()); + assertFalse(candidateFailure.toString().contains(candidateMismatch.transientJwt.get())); + assertNull(candidateFailure.getCause()); + verifyNoInteractions(candidateMismatch.envelopeService); + + Fixture envelopeMismatch = new Fixture(temporaryDirectory, false); + envelopeMismatch.returnMismatchedEnvelopeReadback(); + AccountGameplayDelegationSigner.SigningUnavailableException envelopeFailure = + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> envelopeMismatch.signer.signPendingCandidate(REQUEST_ID)); + assertNotNull(envelopeMismatch.transientJwt.get()); + assertFalse(envelopeFailure.toString().contains(envelopeMismatch.transientJwt.get())); + assertNull(envelopeFailure.getCause()); + verify(envelopeMismatch.envelopeService) + .sealPendingCandidate( + eq(REQUEST_ID), any(CallerIdentity.class), eq(envelopeMismatch.transientJwt.get())); + } + + @Test + void rejectsSealedEnvelopeExpiryThatDiffersFromImmutablePendingIdentity() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + fixture.returnMismatchedSealedExpiry(); + + AccountGameplayDelegationSigner.SigningUnavailableException failure = + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> fixture.signer.signPendingCandidate(REQUEST_ID)); + + assertNull(failure.getCause()); + assertNotNull(fixture.transientJwt.get()); + assertFalse(failure.toString().contains(fixture.transientJwt.get())); + verify(fixture.issuance) + .bindSignedCandidate(REQUEST_ID, fixture.transientJwt.get(), GENERATION); + verify(fixture.envelopeService) + .sealPendingCandidate( + eq(REQUEST_ID), any(CallerIdentity.class), eq(fixture.transientJwt.get())); + verify(fixture.issuance, times(1)).readPendingRegistryCandidate(REQUEST_ID); + } + + static final class Fixture { + private final AccountGameplayDelegationIssuanceRepository issuance; + private final AccountJwtSignerDesiredStateRepository desiredState; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtJwksApiBinding apiBinding; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final AccountGameplayDelegationResponseEnvelopeService envelopeService; + private CommittedSignerEvidence committedEvidence; + private final AtomicReference transientJwt = new AtomicReference<>(); + private final AtomicReference boundRecord = + new AtomicReference<>(); + private final AtomicReference sourceJwks = new AtomicReference<>(); + private final AtomicInteger publicSourceLoadCount = new AtomicInteger(); + private final AtomicBoolean sourceLoadsWereOutsideTransactions = new AtomicBoolean(true); + private final AccountAuthoritySnapshot authoritySnapshot; + private final AccountGameplayDelegationPendingIdentity pendingIdentity; + private final PendingSigningIdentity pendingSigningIdentity; + private final AccountAuthEvidenceBundle evidenceBundle; + private final EvidenceBundleReference evidenceReference; + private final SourceIdentity sourceIdentity; + private final AccountJwtSignerDesiredStateRepository.Binding accountBinding; + private final TrustFence trustFence; + private final AccountMountedJwtSignerBundle.ExpectedIdentity mountedIdentity; + private final Path privateRoot; + private final Path publicRoot; + private final PlatformTransactionManager transactionManager; + private final AccountGameplayDelegationSigner signer; + private int mutateSourceOnLoad = Integer.MAX_VALUE; + private byte[] changedSourceBytes; + private long sealedExpiryDeltaMillis; + + Fixture(Path temporaryDirectory, boolean expired) throws Exception { + this(temporaryDirectory, null, null, null, null, CLOCK, expired); + } + + Fixture( + Path temporaryDirectory, + PendingSigningIdentity suppliedPending, + AccountGameplayDelegationIssuanceRepository suppliedIssuance, + AccountGameplayDelegationResponseEnvelopeService suppliedEnvelopeService, + PlatformTransactionManager suppliedTransactionManager, + Clock suppliedClock) + throws Exception { + this( + temporaryDirectory, + suppliedPending, + suppliedIssuance, + suppliedEnvelopeService, + suppliedTransactionManager, + suppliedClock, + false); + } + + private Fixture( + Path temporaryDirectory, + PendingSigningIdentity suppliedPending, + AccountGameplayDelegationIssuanceRepository suppliedIssuance, + AccountGameplayDelegationResponseEnvelopeService suppliedEnvelopeService, + PlatformTransactionManager suppliedTransactionManager, + Clock suppliedClock, + boolean expired) + throws Exception { + ensureEphemeralRsaPairs(); + issuance = + suppliedIssuance == null + ? mock(AccountGameplayDelegationIssuanceRepository.class) + : suppliedIssuance; + desiredState = mock(AccountJwtSignerDesiredStateRepository.class); + materializerTrust = mock(AccountJwtSignerMaterializerTrustBinding.class); + apiBinding = mock(AccountJwtJwksApiBinding.class); + trustedJwksSource = mock(AccountJwtJwksTrustedSource.class); + envelopeService = + suppliedEnvelopeService == null + ? mock(AccountGameplayDelegationResponseEnvelopeService.class) + : suppliedEnvelopeService; + transactionManager = + suppliedTransactionManager == null + ? new InertTransactionManager() + : suppliedTransactionManager; + Clock signingClock = suppliedClock == null ? CLOCK : suppliedClock; + + if (suppliedPending == null) { + long issuedAt = expired ? NOW.getEpochSecond() - 300L : NOW.getEpochSecond(); + long expiresAt = expired ? NOW.getEpochSecond() - 1L : NOW.getEpochSecond() + 120L; + pendingIdentity = + new AccountGameplayDelegationPendingIdentity( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CALLER_CONTEXT_ID, + AccountGameplayCredentialRequestBindingFixture.binding(), + REQUEST_DIGEST, + TOKEN_JTI, + issuedAt, + issuedAt, + expiresAt); + evidenceBundle = evidenceBundle(pendingIdentity); + evidenceReference = evidenceReference(evidenceBundle); + pendingSigningIdentity = pendingSigningIdentity(pendingIdentity, evidenceBundle); + authoritySnapshot = + new AccountAuthoritySnapshot(ACCOUNT_ID, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty()); + } else { + pendingSigningIdentity = suppliedPending; + pendingIdentity = suppliedPending.identity(); + evidenceBundle = suppliedPending.evidenceBundle(); + authoritySnapshot = suppliedPending.authoritySnapshot(); + evidenceReference = evidenceReference(evidenceBundle); + } + sourceJwks.set(jwksJson(signerPair).getBytes(StandardCharsets.UTF_8)); + sourceIdentity = sourceIdentity(); + accountBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + trustFence = + new TrustFence(CLUSTER_UID, NAMESPACE_UID, MATERIALIZER_DIGEST, MATERIALIZER_REVISION); + mountedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + GENERATION_OPERATION_ID.toString(), + GENERATION, + KID, + fingerprint(signerPair)); + privateRoot = + Files.createDirectory(temporaryDirectory.resolve("private-" + UUID.randomUUID())); + publicRoot = Files.createDirectory(temporaryDirectory.resolve("public-" + UUID.randomUUID())); + Files.writeString( + privateRoot.resolve("current.key"), privateBundleJson(mountedIdentity, signerPair)); + Files.writeString(publicRoot.resolve("jwks.json"), jwksJson(signerPair)); + + configureProtectedBindings(); + configureTrustedJwksSource(); + configureCommittedSigner(ownerEvidence(signerPair, GENERATION, KID)); + if (suppliedIssuance == null) configureIssuanceRepository(); + if (suppliedEnvelopeService == null) configureEnvelopeService(); + signer = + new AccountGameplayDelegationSigner( + issuance, + desiredState, + materializerTrust, + apiBinding, + trustedJwksSource, + envelopeService, + transactionManager, + signingClock, + privateRoot, + Path.of("current.key"), + publicRoot, + Path.of("jwks.json")); + } + + AccountGameplayDelegationSigner signer() { + return signer; + } + + AccountGameplayDelegationIssuanceRepository issuanceRepository() { + return issuance; + } + + AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService() { + return envelopeService; + } + + PlatformTransactionManager transactionManager() { + return transactionManager; + } + + UUID requestId() { + return pendingIdentity.requestId(); + } + + UUID accountId() { + return pendingIdentity.accountId(); + } + + AccountJwtSignerDesiredStateRepository desiredStateRepository() { + return desiredState; + } + + void withdrawTrust() { + withdrawMaterializerTrust(); + } + + private void configureProtectedBindings() { + AccountJwtSignerMaterializerTrustBinding.Binding materializer = + mock(AccountJwtSignerMaterializerTrustBinding.Binding.class); + when(materializer.environmentId()).thenReturn(ENVIRONMENT); + when(materializer.clusterId()).thenReturn(CLUSTER); + when(materializer.namespace()).thenReturn(NAMESPACE); + when(materializer.expectedClusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(materializer.expectedNamespaceUid()).thenReturn(NAMESPACE_UID); + when(materializer.bindingDigest()).thenReturn(MATERIALIZER_DIGEST); + when(materializer.configRevision()).thenReturn(MATERIALIZER_REVISION); + when(materializerTrust.current()).thenReturn(Optional.of(materializer)); + + AccountJwtJwksApiBinding.ParsedBinding api = + mock(AccountJwtJwksApiBinding.ParsedBinding.class); + when(api.environmentId()).thenReturn(ENVIRONMENT); + when(api.clusterId()).thenReturn(CLUSTER); + when(api.namespace()).thenReturn(NAMESPACE); + when(api.expectedClusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(api.expectedNamespaceUid()).thenReturn(NAMESPACE_UID); + when(api.bindingDigest()).thenReturn(API_DIGEST); + when(api.configRevision()).thenReturn(API_REVISION); + when(api.apiServer()).thenReturn(java.net.URI.create(API_ORIGIN)); + when(api.servingCaSha256()).thenReturn(SERVING_CA_DIGEST); + when(apiBinding.current()).thenReturn(api); + } + + private void configureTrustedJwksSource() { + when(trustedJwksSource.sourceIdentity()) + .thenAnswer( + invocation -> { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + sourceLoadsWereOutsideTransactions.set(false); + } + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + return sourceIdentity; + }); + when(trustedJwksSource.load()) + .thenAnswer( + invocation -> { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + sourceLoadsWereOutsideTransactions.set(false); + } + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + int load = publicSourceLoadCount.incrementAndGet(); + byte[] bytes = + load >= mutateSourceOnLoad && changedSourceBytes != null + ? changedSourceBytes + : sourceJwks.get(); + return new PublicJwksSnapshot(sourceIdentity, bytes); + }); + } + + private void configureCommittedSigner(CommittedSignerEvidence evidence) { + committedEvidence = evidence; + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.of(evidence)); + } + + private void replaceCommittedEvidence(CommittedSignerEvidence evidence) { + committedEvidence = evidence; + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.of(evidence)); + } + + private void mismatchPrivatePromotionObservation() { + when(committedEvidence.promotion().privatePromotionObservedResourceVersion()) + .thenReturn(Optional.of("14")); + } + + private void withdrawMaterializerTrust() { + when(materializerTrust.current()).thenReturn(Optional.empty()); + } + + private void configureIssuanceRepository() { + when(issuance.readPendingSigningIdentity(REQUEST_ID)) + .thenReturn(pendingSigningIdentity, pendingSigningIdentity); + when(issuance.bindSignedCandidate(eq(REQUEST_ID), anyString(), eq(GENERATION))) + .thenAnswer( + invocation -> { + String jwt = invocation.getArgument(1); + transientJwt.set(jwt); + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + jwt, + GENERATION, + new IssuanceBinding( + ISSUANCE_OPERATION_ID.toString(), + REQUEST_ID.toString(), + REQUEST_DIGEST, + ACCOUNT_ID.toString()), + authoritySnapshot, + evidenceReference, + NOW.getEpochSecond(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + boundRecord.set(record); + return new BoundTokenCandidate( + REQUEST_ID, record.tokenHash(), record.kid(), record.signerGeneration()); + }); + when(issuance.readPendingRegistryCandidate(REQUEST_ID)) + .thenAnswer( + invocation -> { + GameSessionAccountDelegationRegistryRecord record = boundRecord.get(); + assertNotNull(record); + return new PendingRegistryCandidate( + pendingIdentity, + record.tokenHash(), + record.kid(), + record.signerGeneration(), + record.expiresAtEpochSecond(), + record.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES), + authoritySnapshot, + evidenceReference); + }); + } + + private void configureEnvelopeService() { + when(envelopeService.sealPendingCandidate( + eq(REQUEST_ID), any(CallerIdentity.class), anyString())) + .thenAnswer( + invocation -> { + assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + CallerIdentity caller = invocation.getArgument(1); + String jwt = invocation.getArgument(2); + assertEquals(WORKLOAD, caller.workload()); + assertEquals(CALLER_CONTEXT_ID, caller.contextId()); + assertEquals(transientJwt.get(), jwt); + return sealedObservation( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + evidenceBundle, + Math.multiplyExact(pendingIdentity.expiresAtEpochSecond(), 1_000L) + + sealedExpiryDeltaMillis); + }); + } + + private void returnMissingCommittedEvidence() { + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.empty()); + } + + private void useSourceJwks(KeyPair pair) { + sourceJwks.set(jwksJson(pair).getBytes(StandardCharsets.UTF_8)); + } + + private void changeSourceJwksOnLoad(int loadNumber, byte[] bytes) { + mutateSourceOnLoad = loadNumber; + changedSourceBytes = bytes.clone(); + } + + private void changeCommittedSignerAfterFirstRead(KeyPair changedKey) { + CommittedSignerEvidence original = ownerEvidence(signerPair, GENERATION, KID); + CommittedSignerEvidence changed = ownerEvidence(changedKey, "43", "account-key-43"); + when(desiredState.readCurrentCommittedSigner( + any(AccountJwtSignerDesiredStateRepository.Binding.class), + any(TrustFence.class), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.of(original), Optional.of(changed)); + } + + private void changePendingIdentityAfterFirstRead() { + AccountGameplayDelegationPendingIdentity changedIdentity = + new AccountGameplayDelegationPendingIdentity( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CALLER_CONTEXT_ID, + pendingIdentity.credentialRequestBinding(), + REQUEST_DIGEST, + UUID.fromString("2a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), + pendingIdentity.issuedAtEpochSecond(), + pendingIdentity.notBeforeEpochSecond(), + pendingIdentity.expiresAtEpochSecond()); + PendingSigningIdentity changed = pendingSigningIdentity(changedIdentity, evidenceBundle); + when(issuance.readPendingSigningIdentity(REQUEST_ID)) + .thenReturn(pendingSigningIdentity, changed); + } + + private void returnMismatchedBoundCandidate() { + when(issuance.bindSignedCandidate(eq(REQUEST_ID), anyString(), eq(GENERATION))) + .thenAnswer( + invocation -> { + transientJwt.set(invocation.getArgument(1)); + return new BoundTokenCandidate(REQUEST_ID, "f".repeat(64), KID, GENERATION); + }); + } + + private void returnMismatchedEnvelopeReadback() { + when(envelopeService.sealPendingCandidate( + eq(REQUEST_ID), any(CallerIdentity.class), anyString())) + .thenAnswer( + invocation -> { + assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + transientJwt.set(invocation.getArgument(2)); + return sealedObservation( + UUID.fromString("3a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), + REQUEST_ID, + evidenceBundle, + Math.multiplyExact(pendingIdentity.expiresAtEpochSecond(), 1_000L)); + }); + } + + private void returnMismatchedSealedExpiry() { + sealedExpiryDeltaMillis = 1L; + } + } + + private static PendingSigningIdentity pendingSigningIdentity( + AccountGameplayDelegationPendingIdentity identity, AccountAuthEvidenceBundle bundle) { + PendingSigningIdentity pending = mock(PendingSigningIdentity.class); + when(pending.identity()).thenReturn(identity); + when(pending.authoritySnapshot()) + .thenReturn( + new AccountAuthoritySnapshot(ACCOUNT_ID, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty())); + when(pending.evidenceBundle()).thenReturn(bundle); + return pending; + } + + private static AccountAuthEvidenceBundle evidenceBundle( + AccountGameplayDelegationPendingIdentity identity) { + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new OwnerEvaluation( + new BundleReference("1", "11", "9", "3"), + "b".repeat(64), + "c".repeat(64), + ACCOUNT_ID, + new OperationIdentity( + identity.operationId(), + identity.requestId(), + identity.requestDigest(), + identity.callerWorkload(), + identity.callerContextId(), + identity.accountId()), + new TokenIdentity( + identity.tokenJti(), + 1L, + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond()), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 1L, + new AuthoritySourceVersions(1L, 1L, 1L), + new AccountIdentitySource( + 42L, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L), + List.of( + new OutboxCheckpoint(accountStream, 0L, null, null), + new OutboxCheckpoint(issuerStream, 0L, null, null)))); + } + + private static EvidenceBundleReference evidenceReference(AccountAuthEvidenceBundle bundle) { + Map reference = (Map) bundle.fields().get("bundleRef"); + return new EvidenceBundleReference( + (String) reference.get("bundleVersion"), + (String) reference.get("sourceVersion"), + (String) reference.get("sourceFence"), + (String) reference.get("linearization"), + bundle.canonicalSha256()); + } + + private static CommittedSignerEvidence ownerEvidence( + KeyPair pair, String generation, String kid) { + String publicFingerprint = fingerprint(pair); + AccountJwtSignerDesiredStateRepository.Binding binding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + TrustFence trust = + new TrustFence(CLUSTER_UID, NAMESPACE_UID, MATERIALIZER_DIGEST, MATERIALIZER_REVISION); + UUID generationOperation = + generation.equals(GENERATION) + ? GENERATION_OPERATION_ID + : UUID.fromString("9af097ea-b1d1-42ea-9f24-46aeb211a779"); + UUID promotionOperation = + generation.equals(GENERATION) + ? PROMOTION_OPERATION_ID + : UUID.fromString("aaf097ea-b1d1-42ea-9f24-46aeb211a779"); + ActiveSigner active = new ActiveSigner(generation, kid); + DesiredState desired = + new DesiredState( + binding, + generation.equals(GENERATION) ? 7L : 8L, + Optional.of(active), + Optional.of(active), + Optional.of(generationOperation), + Optional.empty(), + Optional.empty()); + + GenerationResult generationResult = mock(GenerationResult.class); + when(generationResult.operationId()).thenReturn(generationOperation); + when(generationResult.binding()).thenReturn(binding); + when(generationResult.trustFence()).thenReturn(trust); + when(generationResult.operationDigest()).thenReturn("2".repeat(64)); + when(generationResult.generationRequestDigest()).thenReturn("3".repeat(64)); + when(generationResult.desiredStateVersion()).thenReturn(6L); + when(generationResult.privateSecretName()) + .thenReturn(AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + when(generationResult.secretUid()).thenReturn("66666666-6666-4666-8666-666666666666"); + when(generationResult.expectedPriorResourceVersion()).thenReturn("12"); + when(generationResult.observedResourceVersion()).thenReturn("13"); + when(generationResult.targetGeneration()).thenReturn(generation); + when(generationResult.targetKid()).thenReturn(kid); + when(generationResult.targetAlgorithm()).thenReturn("RS256"); + when(generationResult.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(generationResult.receiptDigest()).thenReturn("4".repeat(64)); + + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + when(promotion.operationId()).thenReturn(promotionOperation); + when(promotion.generationOperationId()).thenReturn(generationOperation); + when(promotion.binding()).thenReturn(binding); + when(promotion.trustFence()).thenReturn(trust); + when(promotion.targetGeneration()).thenReturn(generation); + when(promotion.targetKid()).thenReturn(kid); + when(promotion.targetAlgorithm()).thenReturn("RS256"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(publicFingerprint); + when(promotion.requestDigest()).thenReturn("5".repeat(64)); + when(promotion.expectedRecordVersion()).thenReturn(6L); + when(promotion.expectedPreviousActive()).thenReturn(Optional.empty()); + when(promotion.expectedPreviousPublicKeyFingerprint()).thenReturn(Optional.empty()); + when(promotion.expectedPublishedActive()).thenReturn(Optional.of(active)); + when(promotion.generationOperationDigest()).thenReturn("2".repeat(64)); + when(promotion.generationReceiptDigest()).thenReturn("4".repeat(64)); + when(promotion.secretUid()).thenReturn("66666666-6666-4666-8666-666666666666"); + when(promotion.expectedPrivateResourceVersion()).thenReturn("12"); + when(promotion.apiBindingDigest()).thenReturn(API_DIGEST); + when(promotion.apiConfigRevision()).thenReturn(API_REVISION); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicResourceVersion()).thenReturn("20"); + when(promotion.prepublicationIntentDigest()).thenReturn("6".repeat(64)); + when(promotion.prepublicationReceiptDigest()).thenReturn("7".repeat(64)); + when(promotion.mountedObservationDigest()).thenReturn("8".repeat(64)); + when(promotion.readinessPlanDigest()).thenReturn("9".repeat(64)); + when(promotion.readinessEvidenceDigest()).thenReturn("a".repeat(64)); + when(promotion.status()).thenReturn("COMMITTED"); + when(promotion.privatePromotionDispatched()).thenReturn(true); + when(promotion.privatePromotionObservedResourceVersion()).thenReturn(Optional.of("13")); + when(promotion.privatePromotionReceiptDigest()).thenReturn(Optional.of("b".repeat(64))); + when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.of("21")); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of("c".repeat(64))); + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.of("d".repeat(64))); + + PrivatePromotionReceipt privateReceipt = + new PrivatePromotionReceipt(promotionOperation, generationOperation, "13", "b".repeat(64)); + ActiveJwksPromotionReceipt publicReceipt = + new ActiveJwksPromotionReceipt( + promotionOperation, CONFIG_MAP_UID, "20", "21", "c".repeat(64), "d".repeat(64)); + return new CommittedSignerEvidence( + promotion, generationResult, desired, privateReceipt, publicReceipt); + } + + private static SealedCandidateObservation sealedObservation( + UUID operationId, + UUID requestId, + AccountAuthEvidenceBundle bundle, + long responseRecoveryExpiryEpochMillis) { + return new SealedCandidateObservation( + operationId, + requestId, + bundle.canonicalSha256(), + 1L, + responseRecoveryExpiryEpochMillis, + "9".repeat(64), + 512); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + API_REVISION, + API_ORIGIN, + SERVING_CA_DIGEST); + } + + private static String privateBundleJson( + AccountMountedJwtSignerBundle.ExpectedIdentity identity, KeyPair pair) { + return "{" + + "\"version\":1," + + "\"environmentId\":\"" + + identity.environmentId() + + "\"," + + "\"clusterId\":\"" + + identity.clusterId() + + "\"," + + "\"namespace\":\"" + + identity.namespace() + + "\"," + + "\"operationId\":\"" + + identity.operationId() + + "\"," + + "\"generation\":\"" + + identity.generation() + + "\"," + + "\"kid\":\"" + + identity.kid() + + "\"," + + "\"algorithm\":\"RS256\"," + + "\"privateKeyPkcs8\":\"" + + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(((RSAPrivateCrtKey) pair.getPrivate()).getEncoded()) + + "\",\"publicKeyFingerprint\":\"" + + identity.publicKeyFingerprint() + + "\"}"; + } + + private static String jwksJson(KeyPair pair) { + return jwksJson(pair, KID); + } + + private static String jwksJson( + KeyPair firstPair, String firstKid, KeyPair secondPair, String secondKid) { + return "{\"keys\":[" + + jwkJson(firstPair, firstKid) + + "," + + jwkJson(secondPair, secondKid) + + "]}"; + } + + private static String jwksJson(KeyPair pair, String kid) { + return "{\"keys\":[" + jwkJson(pair, kid) + "]}"; + } + + private static String jwkJson(KeyPair pair, String kid) { + RSAPublicKey key = (RSAPublicKey) pair.getPublic(); + return "{" + + "\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\"," + + "\"kid\":\"" + + kid + + "\",\"key_ops\":[\"verify\"]," + + "\"n\":\"" + + base64Url(unsigned(key.getModulus())) + + "\"," + + "\"e\":\"" + + base64Url(unsigned(key.getPublicExponent())) + + "\"}"; + } + + private static String fingerprint(KeyPair pair) { + RSAPublicKey key = (RSAPublicKey) pair.getPublic(); + String material = + "{\"e\":\"" + + base64Url(unsigned(key.getPublicExponent())) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsigned(key.getModulus())) + + "\"}"; + try { + return HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(material.getBytes(StandardCharsets.US_ASCII))); + } catch (java.security.GeneralSecurityException failure) { + throw new IllegalStateException(failure); + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] encoded = value.toByteArray(); + return encoded.length > 1 && encoded[0] == 0 + ? Arrays.copyOfRange(encoded, 1, encoded.length) + : encoded; + } + + private static String base64Url(byte[] value) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } finally { + Arrays.fill(value, (byte) 0); + } + } + + private static final class InertTransactionManager extends AbstractPlatformTransactionManager { + private final AtomicBoolean failNextCommit = new AtomicBoolean(); + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) { + if (failNextCommit.getAndSet(false)) + throw new IllegalStateException("Injected commit failure"); + } + + private void failNextCommit() { + failNextCommit.set(true); + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTestFixtureFactory.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTestFixtureFactory.java new file mode 100644 index 0000000000..7d7751e8c1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTestFixtureFactory.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import org.springframework.transaction.PlatformTransactionManager; + +/** Narrow test-only access to the existing RSA-backed signer fixture for composition tests. */ +public final class AccountGameplayDelegationSignerTestFixtureFactory { + private AccountGameplayDelegationSignerTestFixtureFactory() {} + + public static Fixture create(Path temporaryDirectory) throws Exception { + return new Fixture(new AccountGameplayDelegationSignerTest.Fixture(temporaryDirectory, false)); + } + + public static final class Fixture { + private final AccountGameplayDelegationSignerTest.Fixture delegate; + + private Fixture(AccountGameplayDelegationSignerTest.Fixture delegate) { + this.delegate = delegate; + } + + public AccountGameplayDelegationSigner signer() { + return delegate.signer(); + } + + public AccountGameplayDelegationIssuanceRepository issuanceRepository() { + return delegate.issuanceRepository(); + } + + public AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService() { + return delegate.responseEnvelopeService(); + } + + public PlatformTransactionManager transactionManager() { + return delegate.transactionManager(); + } + + public UUID requestId() { + return delegate.requestId(); + } + + public UUID accountId() { + return delegate.accountId(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java new file mode 100644 index 0000000000..a3336bb2d7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java @@ -0,0 +1,545 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.output.CommandOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayDelegationTokenRegistryTest { + private static final String ACCOUNT_ID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String JTI = "2921ba03-bf74-49ac-b24b-a9255f5de308"; + private static final String OPERATION_ID = "5414e55d-0393-4561-ac3d-cb916a08d3f0"; + private static final String REQUEST_ID = "1ee95a1e-83f2-4a63-a7ba-6288e246ac76"; + private static final long NOW = 1_800_000_000L; + private static final long EXPIRY_MILLIS = (NOW + 120L) * 1000L + 30_000L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private AccountGameplayDelegationIssuanceRepository repository; + private final TestTransactionManager transactionManager = new TestTransactionManager(); + private StatefulRedisConnection connection; + private RedisCommands commands; + private AccountGameplayDelegationTokenRegistry registry; + private PendingRegistryCandidate candidate; + private byte[] encodedRecord; + private byte[] redisKey; + + @BeforeEach + void setUp() throws Exception { + repository = mock(AccountGameplayDelegationIssuanceRepository.class); + connection = mock(StatefulRedisConnection.class); + commands = mock(RedisCommands.class); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + AccountCoordinationPinnedConnectionProvider provider = + () -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return connection; + }; + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + token(claims()), "5", binding(), snapshot(), evidenceBundleReference(), NOW, 16_384L); + encodedRecord = record.toCanonicalJsonBytes(16_384L); + redisKey = ascii("session:auth:token:" + record.tokenHash()); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + UUID.fromString(OPERATION_ID), + UUID.fromString(REQUEST_ID), + UUID.fromString(ACCOUNT_ID), + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"), + AccountGameplayCredentialRequestBindingFixture.binding(), + "a".repeat(64), + UUID.fromString(JTI), + NOW, + NOW, + NOW + 120L); + candidate = + new PendingRegistryCandidate( + identity, + record.tokenHash(), + record.kid(), + "5", + NOW + 120L, + encodedRecord, + snapshot(), + evidenceBundleReference()); + when(repository.readPendingRegistryCandidate(UUID.fromString(REQUEST_ID))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return candidate; + }); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(1L); + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(commands.get(redisKey)).thenReturn(encodedRecord.clone()); + when(commands.pexpiretime(redisKey)).thenReturn(EXPIRY_MILLIS); + AccountGameplayDelegationRedisClient redisClient = + new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled(getClass().getClassLoader()), + new AcknowledgementRequirements(1, 1, 1_000), + Clock.fixed(Instant.ofEpochSecond(NOW).plusMillis(500L), ZoneOffset.UTC), + 16_384, + getClass().getClassLoader()); + registry = + new AccountGameplayDelegationTokenRegistry( + repository, + transactionManager, + redisClient, + Clock.fixed(Instant.ofEpochSecond(NOW).plusMillis(500L), ZoneOffset.UTC), + 16_384L, + 30_000L); + } + + @Test + void rejectsAmbientAccountTransactionBeforeReadingCandidateOrOpeningRedis() { + TransactionTemplate ambientTransaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + ambientTransaction.execute( + status -> registry.registerPending(UUID.fromString(REQUEST_ID)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient Account transaction"); + + verify(repository, org.mockito.Mockito.never()) + .readPendingRegistryCandidate(UUID.fromString(REQUEST_ID)); + verify(connection, org.mockito.Mockito.never()).isOpen(); + } + + @Test + void rejectsMissingCandidateBeforeOpeningRedis() { + doReturn(null).when(repository).readPendingRegistryCandidate(UUID.fromString(REQUEST_ID)); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("candidate is unavailable"); + + verify(connection, org.mockito.Mockito.never()).isOpen(); + } + + @Test + void usesOnePinnedRoleCheckedConnectionForScriptLoadEvalshaWaitaofAndExactReadback() + throws Exception { + var receipt = registry.registerPending(UUID.fromString(REQUEST_ID)); + assertThat(receipt.outcome()).isEqualTo(PendingRegistrationOutcome.CREATED); + assertThat(receipt.operationId()).isEqualTo(OPERATION_ID); + assertThat(receipt.requestId()).isEqualTo(REQUEST_ID); + assertThat(receipt.requestDigest()).isEqualTo(candidate.identity().requestDigest()); + assertThat(receipt.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(receipt.tokenJti()).isEqualTo(JTI); + assertThat(receipt.tokenHash()).isEqualTo(candidate.tokenHash()); + assertThat(receipt.kid()).isEqualTo(candidate.kid()); + assertThat(receipt.signerGeneration()).isEqualTo(candidate.signerGeneration()); + assertThat(receipt.issuanceFence()).isEqualTo(candidate.authoritySnapshot().issuanceFence()); + assertThat(receipt.registryVersion()).isEqualTo(1L); + assertThat(receipt.canonicalRecordSha256()).isEqualTo(sha256(encodedRecord)); + assertThat(receipt.aclIdentity()) + .isEqualTo(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + assertThat(receipt.evidenceBundleReference()).isEqualTo(candidate.evidenceBundleReference()); + assertThat(receipt.absoluteExpiryMillis()).isEqualTo(EXPIRY_MILLIS); + assertThat(receipt.localAofCount()).isEqualTo(1L); + assertThat(receipt.replicaAofCount()).isEqualTo(1L); + assertThat(receipt.toString()).doesNotContain("compact", "eyJ"); + + InOrder order = inOrder(connection, commands); + order.verify(connection).isOpen(); + order.verify(connection).getOptions(); + order.verify(connection).sync(); + order.verify(commands).aclWhoami(); + org.mockito.ArgumentCaptor scriptBytes = + org.mockito.ArgumentCaptor.forClass(byte[].class); + org.mockito.ArgumentCaptor loadedSha = + org.mockito.ArgumentCaptor.forClass(String.class); + order.verify(commands).scriptLoad(scriptBytes.capture()); + ArgumentCaptor keys = ArgumentCaptor.forClass(byte[][].class); + ArgumentCaptor arguments = ArgumentCaptor.forClass(byte[][].class); + order + .verify(commands) + .evalsha( + loadedSha.capture(), eq(ScriptOutputType.INTEGER), keys.capture(), arguments.capture()); + assertThat(keys.getValue().length).isEqualTo(1); + assertThat(keys.getValue()[0]).containsExactly(redisKey); + assertThat(arguments.getValue().length).isEqualTo(2); + assertThat(arguments.getValue()[0]).containsExactly(encodedRecord); + assertThat(arguments.getValue()[1]).containsExactly(ascii(Long.toString(EXPIRY_MILLIS))); + ArgumentCaptor waitAofCommand = ArgumentCaptor.forClass(ProtocolKeyword.class); + ArgumentCaptor waitAofOutput = ArgumentCaptor.forClass(CommandOutput.class); + ArgumentCaptor waitAofArguments = ArgumentCaptor.forClass(CommandArgs.class); + order + .verify(commands) + .dispatch(waitAofCommand.capture(), waitAofOutput.capture(), waitAofArguments.capture()); + assertThat(waitAofCommand.getValue().toString()).isEqualTo("WAITAOF"); + assertThat(waitAofCommand.getValue().getBytes()).containsExactly(ascii("WAITAOF")); + assertThat(waitAofOutput.getValue()).isInstanceOf(ArrayOutput.class); + assertThat(waitAofArguments.getValue().toCommandString()).isEqualTo("1 1 1000"); + order.verify(commands).get(redisKey); + order.verify(commands).pexpiretime(redisKey); + order.verify(connection).close(); + verifyNoMoreInteractions(connection, commands); + String script = new String(scriptBytes.getValue(), StandardCharsets.UTF_8); + assertThat(script) + .contains("redis.call('PEXPIRETIME', key)") + .contains("'PXAT', ARGV[2]") + .contains("return 0") + .contains("return 1") + .doesNotContain("PTTL", "redis.call('TIME'"); + assertThat(loadedSha.getValue()).isEqualTo(sha1(scriptBytes.getValue())); + } + + @Test + void matchesAuthorityGenerationsFromTheCanonicalDecodedRecordDecimalStringDomain() { + Map tuple = (Map) recordFields(encodedRecord).get("authorityTuple"); + assertThat(tuple.get("issuerAuthGeneration")).isEqualTo("7"); + assertThat(tuple.get("accountAuthorityGeneration")).isEqualTo("11"); + assertThat(tuple.get("accountSecurityCutoff")) + .isEqualTo( + GameSessionAccountDelegationProfile.authorityTuple(7L, 11L, Optional.of(cutoff())) + .get("accountSecurityCutoff")); + + assertThat(registry.registerPending(UUID.fromString(REQUEST_ID)).outcome()) + .isEqualTo(PendingRegistrationOutcome.CREATED); + } + + @Test + void exactRetryReassertsSameAbsoluteExpiryAndDoesNotExtendThePendingRecord() { + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenReturn(0L); + + assertThat(registry.registerPending(UUID.fromString(REQUEST_ID)).outcome()) + .isEqualTo(PendingRegistrationOutcome.EXACT_RETRY); + + org.mockito.ArgumentCaptor evalArguments = + org.mockito.ArgumentCaptor.forClass(byte[][].class); + verify(commands) + .evalsha( + anyString(), + eq(ScriptOutputType.INTEGER), + any(byte[][].class), + evalArguments.capture()); + assertThat(evalArguments.getValue().length).isEqualTo(2); + assertThat(evalArguments.getValue()[0]).containsExactly(encodedRecord); + assertThat(evalArguments.getValue()[1]).containsExactly(ascii(Long.toString(EXPIRY_MILLIS))); + verify(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(commands).pexpiretime(redisKey); + } + + @Test + void rejectsAnyLiveRedisAclIdentityOtherThanAccountCoordAppBeforeLoadingScript() { + when(commands.aclWhoami()).thenReturn("default"); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(commands).aclWhoami(); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(anyString(), any(), any(byte[][].class), any(byte[][].class)); + verify(commands, org.mockito.Mockito.never()) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + verify(connection).close(); + } + + @Test + void rejectsAutoReconnectingConnectionBeforeRedisCommands() { + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(true).build()); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(connection).getOptions(); + verify(connection).isOpen(); + verify(connection).close(); + verify(commands, org.mockito.Mockito.never()).aclWhoami(); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + } + + @Test + void rejectsClosedConnectionBeforeRedisCommands() { + when(connection.isOpen()).thenReturn(false); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + + verify(connection).isOpen(); + verify(connection).close(); + verify(commands, org.mockito.Mockito.never()).aclWhoami(); + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + } + + @Test + void rejectsScriptBytesThatDoNotMatchTheImmutableOwnerDescriptorDigest() { + RedisScriptDescriptor descriptor = + new AccountGameplayDelegationRedisScriptContribution() + .descriptors().stream() + .filter( + item -> AccountGameplayDelegationRedisClient.SCRIPT_ID.equals(item.scriptId())) + .findFirst() + .orElseThrow( + () -> new AssertionError("Pending registry script descriptor is missing")); + RedisScriptDescriptor alteredDigest = + new RedisScriptDescriptor( + descriptor.scriptId(), + descriptor.resourcePath(), + "0".repeat(64), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + descriptor.keys(), + descriptor.arguments(), + descriptor.category(), + descriptor.outcomes(), + descriptor.resetSensitivity(), + descriptor.lossClass(), + descriptor.tailLossBehavior(), + descriptor.compatibilityLevel(), + descriptor.supportedCoexistence(), + descriptor.legacyPayloadShape()); + AccountGameplayDelegationRedisClient alteredClient = + new AccountGameplayDelegationRedisClient( + () -> connection, + RedisScriptCatalog.fromContributions(List.of(contribution(alteredDigest))), + new AcknowledgementRequirements(1, 1, 1_000), + Clock.fixed(Instant.ofEpochSecond(NOW).plusMillis(500L), ZoneOffset.UTC), + 16_384, + getClass().getClassLoader()); + + assertThatThrownBy( + () -> + alteredClient.registerPending(candidate.tokenHash(), encodedRecord, EXPIRY_MILLIS)) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verifyNoMoreInteractions(connection); + } + + @Test + void belowThresholdOrMismatchedReadbackNeverReturnsRegistrationSuccess() { + doReturn(List.of(1L, 0L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(commands, org.mockito.Mockito.never()).get(redisKey); + + doReturn(List.of("1", 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + verify(commands, org.mockito.Mockito.never()).get(redisKey); + + doReturn(List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + when(commands.get(redisKey)).thenReturn(ascii("different-record")); + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } + + @Test + void connectionCloseFailureNeverReturnsRegistrationSuccess() { + doThrow(new IllegalStateException("close failed")).when(connection).close(); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + } + + @Test + void pendingRegistryWriterRejectsRecordOmittingApplicableCutoffBeforeRedis() throws Exception { + Map mismatchedFields = new LinkedHashMap<>(recordFields(encodedRecord)); + Map tupleWithoutCutoff = new LinkedHashMap<>(); + ((Map) mismatchedFields.get("authorityTuple")) + .forEach((key, value) -> tupleWithoutCutoff.put((String) key, value)); + tupleWithoutCutoff.remove("accountSecurityCutoff"); + mismatchedFields.put("authorityTuple", tupleWithoutCutoff); + byte[] mismatchedBytes = canonicalJson(mismatchedFields); + PendingRegistryCandidate mismatched = + new PendingRegistryCandidate( + candidate.identity(), + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + candidate.expiresAtEpochSecond(), + mismatchedBytes, + snapshot(), + evidenceBundleReference()); + doReturn(mismatched).when(repository).readPendingRegistryCandidate(UUID.fromString(REQUEST_ID)); + + assertThatThrownBy(() -> registry.registerPending(UUID.fromString(REQUEST_ID))) + .isInstanceOf(IllegalArgumentException.class); + + verify(commands, org.mockito.Mockito.never()).scriptLoad(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(anyString(), any(), any(byte[][].class), any(byte[][].class)); + } + + private static Map claims() { + return Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", ACCOUNT_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("jti", JTI), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", NOW), + Map.entry("nbf", NOW), + Map.entry("exp", NOW + 120L), + Map.entry("tokenGeneration", "1"), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple(7L, 11L, Optional.of(cutoff()))), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", "11")); + } + + private static String token(Map claims) throws Exception { + String header = + JSON.writeValueAsString(Map.of("alg", "RS256", "kid", "test-key", "typ", "JWT")); + String payload = JSON.writeValueAsString(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString(header.getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString("signature-bytes".getBytes(StandardCharsets.UTF_8)); + } + + private static IssuanceBinding binding() { + return new IssuanceBinding(OPERATION_ID, REQUEST_ID, "a".repeat(64), ACCOUNT_ID); + } + + private static AccountAuthoritySnapshot snapshot() { + return new AccountAuthoritySnapshot( + UUID.fromString(ACCOUNT_ID), 7L, 7L, 11L, 11L, 11L, 11L, Optional.of(cutoff())); + } + + private static EvidenceBundleReference evidenceBundleReference() { + return new EvidenceBundleReference("1", "11", "9", "3", "d".repeat(64)); + } + + private static AccountSecurityCutoff cutoff() { + return new AccountSecurityCutoff("11", "account:auth-authority:v1:account/" + ACCOUNT_ID, "10"); + } + + private static Map recordFields(byte[] bytes) { + return GameSessionAccountDelegationRegistryRecord.decode(bytes, 16_384L).fields(); + } + + private static byte[] canonicalJson(Map value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static net.firedevops.firemud.common.redis.contracts.RedisScriptContribution contribution( + RedisScriptDescriptor descriptor) { + return new net.firedevops.firemud.common.redis.contracts.RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public List descriptors() { + return List.of(descriptor); + } + }; + } + + private static String sha1(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(bytes)); + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static final class TestTransactionManager extends AbstractPlatformTransactionManager { + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySourceTest.java new file mode 100644 index 0000000000..8b7565dee6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedGameplayCredentialDigestKeySourceTest.java @@ -0,0 +1,256 @@ +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.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountMountedGameplayCredentialDigestKeySourceTest { + private static final Instant NOW = Instant.parse("2026-10-07T00:00:00Z"); + private static final Instant HORIZON = Instant.parse("2027-01-16T12:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + + @TempDir Path tempDirectory; + + @Test + void resolvesDistinctActiveAndRetainedHmacKeysWithTheirExplicitHorizon() throws Exception { + Path mount = tempDirectory.resolve("mount"); + byte[] activeMaterial = keyMaterial(0x11); + byte[] retainedMaterial = keyMaterial(0x22); + writeManifest( + mount, + active("active-2", HORIZON, activeMaterial), + retained("prior-1", HORIZON.plusSeconds(60), retainedMaterial)); + AccountMountedGameplayCredentialDigestKeySource source = source(mount); + + var active = source.currentKey(); + var retained = source.requireKey("prior-1"); + + assertThat(active.keyId()).isEqualTo("active-2"); + assertThat(active.key().getAlgorithm()).isEqualTo("HmacSHA256"); + assertThat(active.key().getEncoded()).containsExactly(activeMaterial); + assertThat(active.retainedUntil()).isEqualTo(HORIZON); + assertThat(retained.keyId()).isEqualTo("prior-1"); + assertThat(retained.key().getAlgorithm()).isEqualTo("HmacSHA256"); + assertThat(retained.key().getEncoded()).containsExactly(retainedMaterial); + assertThat(retained.retainedUntil()).isEqualTo(HORIZON.plusSeconds(60)); + assertThat(active.toString()).isEqualTo("CredentialDigestKey[redacted]"); + assertThat(source.toString()).contains("redacted").doesNotContain(encoded(activeMaterial)); + assertThat(active.key().toString()).doesNotContain(encoded(activeMaterial)); + } + + @Test + void rejectsAnExpiredActiveOrRetainedKeyAtItsExactHorizon() throws Exception { + Path mount = tempDirectory.resolve("expired"); + writeManifest( + mount, + active("active-1", NOW, keyMaterial(0x31)), + retained("prior-1", HORIZON, keyMaterial(0x32))); + AccountMountedGameplayCredentialDigestKeySource source = source(mount); + + assertUnavailable(source::currentKey); + assertThat(source.requireKey("prior-1").keyId()).isEqualTo("prior-1"); + + writeManifest( + mount, + active("active-2", HORIZON, keyMaterial(0x33)), + retained("prior-1", NOW, keyMaterial(0x34))); + assertUnavailable(() -> source.requireKey("prior-1")); + } + + @Test + void reloadsRotationAndDoesNotRetainWithdrawnIds() throws Exception { + Path mount = tempDirectory.resolve("rotating"); + writeManifest(mount, active("key-v1", HORIZON, keyMaterial(0x41))); + AccountMountedGameplayCredentialDigestKeySource source = source(mount); + assertThat(source.currentKey().keyId()).isEqualTo("key-v1"); + + writeManifest( + mount, + active("key-v2", HORIZON.plusSeconds(600), keyMaterial(0x42)), + retained("key-v1", HORIZON, keyMaterial(0x41))); + assertThat(source.currentKey().keyId()).isEqualTo("key-v2"); + assertThat(source.requireKey("key-v1").keyId()).isEqualTo("key-v1"); + + writeManifest(mount, active("key-v3", HORIZON.plusSeconds(1200), keyMaterial(0x43))); + assertThat(source.currentKey().keyId()).isEqualTo("key-v3"); + assertUnavailable(() -> source.requireKey("key-v1")); + } + + @Test + void rejectsUnknownIdsAndMalformedOrAmbiguousManifestEntries() throws Exception { + Path mount = tempDirectory.resolve("malformed"); + String validActive = active("key-1", HORIZON, keyMaterial(0x51)); + String validRetained = retained("key-2", HORIZON, keyMaterial(0x52)); + writeManifest(mount, validActive); + AccountMountedGameplayCredentialDigestKeySource source = source(mount); + assertUnavailable(() -> source.requireKey("unknown")); + + String[] malformedManifests = { + validRetained, + validActive.replace("active key-1", "unknown key-1"), + validActive.replace(" ", " "), + validActive + " extra", + "future " + validRetained.substring("retained ".length()), + validActive + "\n" + retained("key-1", HORIZON, keyMaterial(0x53)), + validActive + "\n" + active("key-3", HORIZON, keyMaterial(0x54)), + active("key-3", HORIZON, new byte[31]), + active("bad.id", HORIZON, keyMaterial(0x55)) + }; + for (int index = 0; index < malformedManifests.length; index++) { + Path caseMount = tempDirectory.resolve("malformed-" + index); + writeRawManifest(caseMount, malformedManifests[index]); + assertUnavailable(() -> source(caseMount).currentKey()); + } + + Path tooMany = tempDirectory.resolve("too-many-retained"); + String[] entries = + new String[AccountMountedGameplayCredentialDigestKeySource.MAX_RETAINED_KEYS + 2]; + entries[0] = active("active", HORIZON, keyMaterial(0x61)); + for (int index = 1; index < entries.length; index++) { + entries[index] = retained("retired-" + index, HORIZON, keyMaterial(index)); + } + writeManifest(tooMany, entries); + assertUnavailable(() -> source(tooMany).currentKey()); + } + + @Test + void rejectsNonCanonicalEpochsEncodingOversizeAndInvalidUtf8() throws Exception { + String encoded = encoded(keyMaterial(0x71)); + String[] invalidEpochs = { + "0", "+" + HORIZON.toEpochMilli(), "0" + HORIZON.toEpochMilli(), "9223372036854775808" + }; + for (int index = 0; index < invalidEpochs.length; index++) { + Path mount = tempDirectory.resolve("epoch-" + index); + writeRawManifest(mount, "active key-1 " + invalidEpochs[index] + " " + encoded); + assertUnavailable(() -> source(mount).currentKey()); + } + + Path noncanonicalKey = tempDirectory.resolve("noncanonical-key"); + writeRawManifest( + noncanonicalKey, "active key-1 " + HORIZON.toEpochMilli() + " " + encoded + "="); + assertUnavailable(() -> source(noncanonicalKey).currentKey()); + + Path oversized = tempDirectory.resolve("oversized"); + Files.createDirectories(oversized); + Files.write( + oversized.resolve("keyring"), + new byte[AccountMountedGameplayCredentialDigestKeySource.MAX_MANIFEST_BYTES + 1]); + assertUnavailable(() -> source(oversized).currentKey()); + + Path invalidUtf8 = tempDirectory.resolve("invalid-utf8"); + Files.createDirectories(invalidUtf8); + Files.write(invalidUtf8.resolve("keyring"), new byte[] {(byte) 0xc3, (byte) 0x28}); + assertUnavailable(() -> source(invalidUtf8).currentKey()); + + Path nonregular = tempDirectory.resolve("nonregular"); + Files.createDirectories(nonregular.resolve("keyring")); + assertUnavailable(() -> source(nonregular).currentKey()); + } + + @Test + void acceptsOnlyProjectedManifestFilesWhoseResolvedPathStaysInsideTheMount() throws Exception { + Path mount = tempDirectory.resolve("projected"); + Path version = mount.resolve("..2026_10_07_00_00_00.0000000000"); + writeManifest(version, active("projected-key", HORIZON, keyMaterial(0x81))); + try { + Files.createSymbolicLink(mount.resolve("..data"), version.getFileName()); + Files.createSymbolicLink(mount.resolve("keyring"), Path.of("..data", "keyring")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support projected-secret symlinks"); + } + assertThat(source(mount).currentKey().keyId()).isEqualTo("projected-key"); + + Path outside = tempDirectory.resolve("outside"); + writeManifest(outside, active("outside-key", HORIZON, keyMaterial(0x82))); + Path escaping = tempDirectory.resolve("escaping"); + Files.createDirectories(escaping); + try { + Files.createSymbolicLink(escaping.resolve("keyring"), outside.resolve("keyring")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support symlink validation"); + } + AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException failure = + unavailable(() -> source(escaping).currentKey()); + assertThat(failure.getMessage()) + .doesNotContain(escaping.toString(), encoded(keyMaterial(0x82))); + assertThat(failure).hasNoCause(); + } + + @Test + void requiresAnAbsoluteMountPathAndDoesNotExposeKeyMaterialOnFailures() throws Exception { + assertThatThrownBy( + () -> new AccountMountedGameplayCredentialDigestKeySource(Path.of("relative"), CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account digest-key mount path must be absolute"); + + Path missing = tempDirectory.resolve("missing"); + AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException failure = + unavailable(() -> source(missing).currentKey()); + assertThat(failure.errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(failure.getMessage()) + .isEqualTo("Account credential-request digest keyring is unavailable") + .doesNotContain( + missing.toString(), + "active-2", + "prior-1", + encoded(keyMaterial(0x11)), + encoded(keyMaterial(0x22))); + assertThat(failure).hasNoCause(); + } + + private static AccountMountedGameplayCredentialDigestKeySource source(Path mount) { + return new AccountMountedGameplayCredentialDigestKeySource(mount, CLOCK); + } + + private static void writeManifest(Path mount, String... entries) throws Exception { + writeRawManifest(mount, String.join("\n", entries)); + } + + private static void writeRawManifest(Path mount, String entries) throws Exception { + Files.createDirectories(mount); + Files.writeString( + mount.resolve("keyring"), + "firemud-account-credential-request-digest-keyring-v1\n" + entries + "\n"); + } + + private static String active(String keyId, Instant horizon, byte[] key) { + return "active " + keyId + " " + horizon.toEpochMilli() + " " + encoded(key); + } + + private static String retained(String keyId, Instant horizon, byte[] key) { + return "retained " + keyId + " " + horizon.toEpochMilli() + " " + encoded(key); + } + + private static byte[] keyMaterial(int fill) { + byte[] bytes = new byte[AccountMountedGameplayCredentialDigestKeySource.KEY_BYTES]; + Arrays.fill(bytes, (byte) fill); + return bytes; + } + + private static String encoded(byte[] key) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } + + private static void assertUnavailable(Runnable operation) { + assertThat(unavailable(operation)).isNotNull(); + } + + private static AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException + unavailable(Runnable operation) { + Throwable failure = org.assertj.core.api.Assertions.catchThrowable(operation::run); + assertThat(failure) + .isInstanceOf( + AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException.class); + return (AccountMountedGameplayCredentialDigestKeySource.KeyUnavailableException) failure; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java index e112b28752..07b5a9c8f5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java @@ -2,6 +2,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -13,9 +19,13 @@ import java.time.ZoneOffset; import java.util.Arrays; import java.util.Base64; +import java.util.Map; import java.util.Optional; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; class AccountResponseEnvelopeCryptographyTest { private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); @@ -285,4 +295,360 @@ private static byte[] filledBytes(byte value) { private static byte[] bytes(String value) { return value.getBytes(StandardCharsets.UTF_8); } + + @Nested + class DonorCryptographyRegressions { + private static final Instant NOW = Instant.parse("2030-01-01T00:00:00Z"); + private static final byte[] RESPONSE_BYTES = {0, 1, (byte) 0xff, 0, 42}; + + @TempDir Path tempDirectory; + + @Test + void springConstructsCryptoBeansWhenDedicatedKeyringIsDisabled() { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "test", Map.of("firemud.account.response-envelope.keyring-path", ""))); + context.register( + AccountResponseEnvelopeKeyring.class, AccountResponseEnvelopeCryptography.class); + context.refresh(); + + assertNotNull(context.getBean(AccountResponseEnvelopeKeyring.class)); + assertNotNull(context.getBean(AccountResponseEnvelopeCryptography.class)); + } + } + + @Test + void roundTripsByteExactResponseUnderActiveKeyAndCompleteTypedBinding() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + AccountResponseEnvelopeCryptography crypto = crypto(mount, NOW); + Instant expiry = NOW.plusSeconds(60); + + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto.encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + + assertArrayEquals( + RESPONSE_BYTES, crypto(mount, NOW).decrypt(encrypted, binding("request-1"), expiry)); + assertTrue(encrypted.toString().contains("redacted")); + byte[] encoded = encrypted.bytes(); + int keyIdLength = Byte.toUnsignedInt(encoded[5]); + int nonceOffset = 6 + keyIdLength + Long.BYTES; + assertTrue(nonceOffset + AccountResponseEnvelopeCryptography.NONCE_BYTES < encoded.length); + } + + @Test + void rotationEncryptsWithNewActiveKeyAndRetainsOldKeyOnlyForItsDeclaredHorizon() + throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active prior-1 " + encodedKey(1)); + Instant expiry = NOW.plusSeconds(180); + Instant retiringUntil = NOW.plusSeconds(120); + AccountResponseEnvelopeCryptography oldCrypto = crypto(mount, NOW); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope prior = + oldCrypto.encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + + writeManifest( + mount, + "active active-2 " + encodedKey(2), + "retiring prior-1 " + retiringUntil.toEpochMilli() + " " + encodedKey(1)); + AccountResponseEnvelopeCryptography rotatedCrypto = crypto(mount, NOW.plusSeconds(30)); + assertArrayEquals(RESPONSE_BYTES, rotatedCrypto.decrypt(prior, binding("request-1"), expiry)); + + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope fresh = + rotatedCrypto.encrypt(binding("request-2"), RESPONSE_BYTES, expiry); + assertEquals("active-2", envelopeKeyId(fresh.bytes())); + + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> crypto(mount, retiringUntil).decrypt(prior, binding("request-1"), expiry)); + } + + @Test + void missingRetainedKeyIsRetryableUnavailableBeforeTheOwnerRecordedExpiry() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + Instant expiry = NOW.plusSeconds(60); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto(mount, NOW).encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + Files.delete(mount.resolve("keyring")); + + AccountResponseEnvelopeKeyring.KeyUnavailableException failure = + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> + crypto(mount, NOW.plusSeconds(10)) + .decrypt(encrypted, binding("request-1"), expiry)); + assertFalse(failure.getMessage().contains(mount.toString())); + assertEquals("AUTH_UNAVAILABLE", failure.errorCode()); + } + + @Test + void expiredOwnerRecordedHorizonIsTerminalEvenWhenKeyringIsUnavailable() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + Instant expiry = NOW.plusMillis(10); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto(mount, NOW).encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + Files.delete(mount.resolve("keyring")); + + AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired = + assertThrows( + AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException.class, + () -> crypto(mount, expiry).decrypt(encrypted, binding("request-1"), expiry)); + assertEquals("RESPONSE_RECOVERY_EXPIRED", expired.errorCode()); + } + + @Test + void changedOperationBindingExpiryOrCiphertextFailsIntegrity() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + AccountResponseEnvelopeCryptography crypto = crypto(mount, NOW); + Instant expiry = NOW.plusSeconds(60); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto.encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + + for (BindingVariant variant : BindingVariant.values()) { + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> crypto.decrypt(encrypted, variant.binding(), expiry)); + } + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> crypto.decrypt(encrypted, binding("request-1"), expiry.plusMillis(1))); + + byte[] tampered = encrypted.bytes(); + tampered[tampered.length - 1] ^= 1; + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> + crypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(tampered), + binding("request-1"), + expiry)); + + byte[] nonceTampered = encrypted.bytes(); + int nonceOffset = 6 + Byte.toUnsignedInt(nonceTampered[5]) + Long.BYTES; + nonceTampered[nonceOffset] ^= 1; + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> + crypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(nonceTampered), + binding("request-1"), + expiry)); + + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> + crypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + Arrays.copyOf(encrypted.bytes(), encrypted.bytes().length - 1)), + binding("request-1"), + expiry)); + } + + @Test + void wrongMaterialForAKeyIdFailsAuthentication() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active same-id " + encodedKey(1)); + Instant expiry = NOW.plusSeconds(60); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope encrypted = + crypto(mount, NOW).encrypt(binding("request-1"), RESPONSE_BYTES, expiry); + writeManifest(mount, "active same-id " + encodedKey(2)); + + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> crypto(mount, NOW.plusSeconds(1)).decrypt(encrypted, binding("request-1"), expiry)); + } + + @Test + void enforcesResponseAndBindingBoundsBeforeCryptography() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + AccountResponseEnvelopeCryptography crypto = crypto(mount, NOW); + byte[] oversizedResponse = + new byte[AccountResponseEnvelopeCryptography.MAX_RESPONSE_BYTES + 1]; + + assertThrows( + IllegalArgumentException.class, + () -> crypto.encrypt(binding("request-1"), oversizedResponse, NOW.plusSeconds(60))); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountResponseEnvelopeCryptography.Binding( + "issue", + "request-1", + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + new byte[8 * 1024 + 1], + new byte[] {'{', '}'}, + new byte[] {2})); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountResponseEnvelopeCryptography.Binding( + "issue", + "request-1", + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + new byte[] {1}, + new byte[0], + new byte[] {2})); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountResponseEnvelopeCryptography.Binding( + "issue", + "request-1", + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + new byte[] {1}, + new byte[] {'{', '}'}, + new byte[128 * 1024 + 1])); + AccountResponseEnvelopeCryptography.Binding maximumComponentBinding = + new AccountResponseEnvelopeCryptography.Binding( + "issue", + "request-1", + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + new byte[8 * 1024], + new byte[4 * 1024], + new byte[128 * 1024]); + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope maximumBindingEnvelope = + crypto.encrypt(maximumComponentBinding, RESPONSE_BYTES, NOW.plusSeconds(60)); + assertArrayEquals( + RESPONSE_BYTES, + crypto.decrypt(maximumBindingEnvelope, maximumComponentBinding, NOW.plusSeconds(60))); + assertThrows( + AccountResponseEnvelopeCryptography.IntegrityException.class, + () -> + crypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[AccountResponseEnvelopeCryptography.MAX_ENVELOPE_BYTES + 1]), + binding("request-1"), + NOW.plusSeconds(60))); + } + + private AccountResponseEnvelopeCryptography crypto(Path mount, Instant now) { + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(mount.toString()), + Clock.fixed(now, ZoneOffset.UTC), + new SecureRandom()); + } + + private AccountResponseEnvelopeCryptography.Binding binding(String requestId) { + return new AccountResponseEnvelopeCryptography.Binding( + "issue", + requestId, + new byte[32], + "spiffe://firemud/ns/test/sa/game-session-service", + "binding-1", + Optional.of("lineage-1"), + Optional.empty(), + Optional.of("lease-1"), + 17, + new byte[] {1, 2, 3}, + new byte[] {'{', '}'}, + new byte[] {4, 5, 6}); + } + + private enum BindingVariant { + OPERATION, + REQUEST_ID, + REQUEST_DIGEST, + CALLER, + BINDING, + LINEAGE, + REPLACEMENT, + LEASE, + ISSUANCE_FENCE, + AUTHORITY_TUPLE, + MEMBERSHIP_VERSION_MAP, + AUTHORITY_EVIDENCE_BUNDLE; + + private AccountResponseEnvelopeCryptography.Binding binding() { + String operation = this == OPERATION ? "refresh" : "issue"; + String requestId = this == REQUEST_ID ? "request-2" : "request-1"; + byte[] requestDigest = new byte[32]; + if (this == REQUEST_DIGEST) { + requestDigest[0] = 1; + } + String caller = + this == CALLER + ? "spiffe://firemud/ns/other/sa/game-session-service" + : "spiffe://firemud/ns/test/sa/game-session-service"; + String bindingId = this == BINDING ? "binding-2" : "binding-1"; + Optional lineage = Optional.of(this == LINEAGE ? "lineage-2" : "lineage-1"); + Optional replacement = + this == REPLACEMENT ? Optional.of("replacement-1") : Optional.empty(); + Optional lease = Optional.of(this == LEASE ? "lease-2" : "lease-1"); + long fence = this == ISSUANCE_FENCE ? 18 : 17; + byte[] authorityTuple = + this == AUTHORITY_TUPLE ? new byte[] {1, 2, 4} : new byte[] {1, 2, 3}; + byte[] membershipVersionMap = + this == MEMBERSHIP_VERSION_MAP + ? new byte[] {'{', '"', 't', '"', ':', '1', '}'} + : new byte[] {'{', '}'}; + byte[] authorityEvidence = + this == AUTHORITY_EVIDENCE_BUNDLE ? new byte[] {4, 5, 7} : new byte[] {4, 5, 6}; + return new AccountResponseEnvelopeCryptography.Binding( + operation, + requestId, + requestDigest, + caller, + bindingId, + lineage, + replacement, + lease, + fence, + authorityTuple, + membershipVersionMap, + authorityEvidence); + } + } + + private static String envelopeKeyId(byte[] encoded) { + int keyIdLength = Byte.toUnsignedInt(encoded[5]); + return new String(encoded, 6, keyIdLength, java.nio.charset.StandardCharsets.US_ASCII); + } + + private static void writeManifest(Path mount, String... entries) throws Exception { + Files.createDirectories(mount); + StringBuilder content = new StringBuilder("firemud-account-response-envelope-keyring-v1\n"); + for (String entry : entries) { + content.append(entry).append('\n'); + } + Files.writeString(mount.resolve("keyring"), content.toString()); + } + + private static String encodedKey(int fill) { + byte[] bytes = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + Arrays.fill(bytes, (byte) fill); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java index 2f0b799eaa..25704ccad1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java @@ -2,6 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -14,6 +18,7 @@ import java.util.Base64; import java.util.Set; import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -133,4 +138,152 @@ private static String encodedKey(int value) { Arrays.fill(key, (byte) value); return Base64.getUrlEncoder().withoutPadding().encodeToString(key); } + + @Nested + class DonorKeyringRegressions { + @TempDir Path tempDirectory; + + @Test + void loadsOneActiveAndRetiringDecryptOnlyKeysWithAnExactRetirementHorizon() throws Exception { + Path mount = tempDirectory.resolve("mount"); + Instant retirement = Instant.parse("2030-01-01T00:00:00Z"); + writeManifest( + mount, + "active active-2 " + encodedKey(2), + "retiring prior-1 " + retirement.toEpochMilli() + " " + encodedKey(1)); + + AccountResponseEnvelopeKeyring.Snapshot snapshot = + new AccountResponseEnvelopeKeyring(mount.toString()).readCurrent(); + + assertEquals("active-2", snapshot.activeKeyId()); + assertTrue( + snapshot + .decryptionKey("prior-1", retirement.minusMillis(1)) + .toString() + .contains("material=redacted")); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> snapshot.decryptionKey("prior-1", retirement)); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> snapshot.decryptionKey("withdrawn", retirement.minusMillis(1))); + } + + @Test + void reloadsMountedManifestSoWithdrawnKeysAreNotKeptInMemory() throws Exception { + Path mount = tempDirectory.resolve("mount"); + writeManifest(mount, "active active-1 " + encodedKey(1)); + AccountResponseEnvelopeKeyring keyring = new AccountResponseEnvelopeKeyring(mount.toString()); + + assertEquals("active-1", keyring.readCurrent().activeKeyId()); + writeManifest(mount, "active active-2 " + encodedKey(2)); + + AccountResponseEnvelopeKeyring.Snapshot updated = keyring.readCurrent(); + assertEquals("active-2", updated.activeKeyId()); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> updated.decryptionKey("active-1", Instant.parse("2030-01-01T00:00:00Z"))); + } + + @Test + void missingOrMalformedMountedManifestFailsRetryablyWithoutEchoingItsPath() throws Exception { + Path missing = tempDirectory.resolve("not-mounted"); + AccountResponseEnvelopeKeyring.KeyUnavailableException missingFailure = + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(missing.toString()).readCurrent()); + assertFalse(missingFailure.getMessage().contains(missing.toString())); + + Path malformed = tempDirectory.resolve("malformed"); + writeManifest( + malformed, + "active repeated " + encodedKey(1), + "retiring repeated 1893456000000 " + encodedKey(2)); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(malformed.toString()).readCurrent()); + } + + @Test + void rejectsBadKeyEncodingAndManifestSize() throws Exception { + Path malformed = tempDirectory.resolve("bad-key"); + writeManifest(malformed, "active active-1 not-base64url"); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(malformed.toString()).readCurrent()); + + Path oversized = tempDirectory.resolve("oversized"); + Files.createDirectories(oversized); + Files.write( + oversized.resolve("keyring"), + new byte[AccountResponseEnvelopeKeyring.MAX_MANIFEST_BYTES + 1]); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(oversized.toString()).readCurrent()); + } + + @Test + void readsKubernetesProjectedKeySymlinksOnlyWhenResolvedFileStaysInsideMountRoot() + throws Exception { + Path projectedMount = tempDirectory.resolve("projected"); + Path version = projectedMount.resolve("..2030_10_05_00_00_00.0000000000"); + Files.createDirectories(version); + writeManifest(version, "active projected-1 " + encodedKey(3)); + try { + Files.createSymbolicLink(projectedMount.resolve("..data"), version.getFileName()); + Files.createSymbolicLink(projectedMount.resolve("keyring"), Path.of("..data", "keyring")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support projected-secret symlinks"); + } + assertEquals( + "projected-1", + new AccountResponseEnvelopeKeyring(projectedMount.toString()) + .readCurrent() + .activeKeyId()); + + Path outside = tempDirectory.resolve("outside"); + writeManifest(outside, "active outside-1 " + encodedKey(4)); + Path escapingMount = tempDirectory.resolve("escaping"); + Files.createDirectories(escapingMount); + try { + Files.createSymbolicLink(escapingMount.resolve("keyring"), outside.resolve("keyring")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support symlink validation"); + } + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(escapingMount.toString()).readCurrent()); + } + + @Test + void rejectsNonCanonicalRetirementEpochs() throws Exception { + String[] invalidEpochs = {"+1893456000000", "01893456000000", "١٨٩٣٤٥٦٠٠٠٠٠٠"}; + for (int index = 0; index < invalidEpochs.length; index++) { + String epoch = invalidEpochs[index]; + Path mount = tempDirectory.resolve("epoch-" + index); + writeManifest( + mount, + "active active-1 " + encodedKey(1), + "retiring prior-1 " + epoch + " " + encodedKey(2)); + assertThrows( + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + () -> new AccountResponseEnvelopeKeyring(mount.toString()).readCurrent()); + } + } + + private static void writeManifest(Path mount, String... entries) throws Exception { + Files.createDirectories(mount); + StringBuilder content = new StringBuilder("firemud-account-response-envelope-keyring-v1\n"); + for (String entry : entries) { + content.append(entry).append('\n'); + } + Files.writeString(mount.resolve("keyring"), content.toString()); + } + + private static String encodedKey(int fill) { + byte[] bytes = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + java.util.Arrays.fill(bytes, (byte) fill); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java new file mode 100644 index 0000000000..0741693326 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java @@ -0,0 +1,222 @@ +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.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +/** Pure encoding fixtures are not owner/currentness or installation proof. */ +public class AccountSelectedGameplayAuthorityProjectionTest { + public static final UUID TENANT = UUID.fromString("6271a559-6f2d-4f82-bb1e-9d4c13884e51"); + public static final UUID ACCOUNT = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + + @Test + void independentMembershipVersionAndGenerationSurviveExactEventRoundTrip() { + var value = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "7", "2")); + assertThat(value.generation()).isEqualTo(new BigInteger("2")); + assertThat(value.membershipVersion()).isEqualTo(new BigInteger("7")); + assertThat(value.sourceVersion()).isEqualTo(new BigInteger("2")); + assertThat( + AccountSelectedGameplayAuthorityProjection.decode( + value.canonicalBytes(), ACCOUNT, TENANT) + .canonicalBytes()) + .containsExactly(value.canonicalBytes()); + assertThatThrownBy( + () -> + AccountSelectedGameplayAuthorityProjection.decode( + value.canonicalBytes(), UUID.randomUUID(), TENANT)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "7", "2"), 9L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void noSequenceGapEqualCheckpointConflictOrRegressionIsAdopted() { + var first = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "7", "2")); + first.requireSuccessorOf(null); + first.requireSuccessorOf(first); + var second = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "2", "8", "2")); + second.requireSuccessorOf(first); // Non-revoking version advancement is independent. + var gap = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "3", "9", "2")); + assertThatThrownBy(() -> gap.requireSuccessorOf(first)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> second.requireSuccessorOf(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> first.requireSuccessorOf(second)) + .isInstanceOf(IllegalArgumentException.class); + var conflict = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "8", "2")); + assertThatThrownBy(() -> conflict.requireSuccessorOf(first)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void duplicateExtraAliasAndMissingEventFailClosed() { + var value = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "7", "2")); + String json = new String(value.canonicalBytes(), StandardCharsets.UTF_8); + for (String malformed : + List.of( + json.replace( + "\"sourceVersion\":\"2\"", "\"sourceVersion\":\"2\",\"sourceVersion\":\"2\""), + json.replace("\"sourceVersion\":\"2\"", "\"generation\":\"2\""), + json.replace("\"sourceVersion\":\"2\"", "\"sourceVersion\":\"2\",\"extra\":true"), + json.replace("\"sourceVersion\":\"2\"", "\"sourceVersion\":2"))) { + assertThatThrownBy( + () -> + AccountSelectedGameplayAuthorityProjection.decode( + malformed.getBytes(StandardCharsets.UTF_8), ACCOUNT, TENANT)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void tenantProjectionUsesAuthorityStreamNotLinkedBillingStream() { + var event = tenant(TENANT); + var value = AccountSelectedGameplayAuthorityProjection.tenant(event); + assertThat(new String(value.canonicalBytes(), StandardCharsets.UTF_8)) + .contains("account:auth-authority:v1:tenant/" + TENANT) + .contains("account:tenant-entitlement:v1:tenant/" + TENANT); + assertThat(value.key()).isEqualTo("session:auth:generation:tenant:" + TENANT); + assertThat( + AccountSelectedGameplayAuthorityProjection.decode(value.canonicalBytes(), null, TENANT) + .canonicalBytes()) + .containsExactly(value.canonicalBytes()); + } + + public static byte[][] selected(byte[][] initial, UUID account, UUID tenant) { + return new byte[][] { + initial[0], + initial[1], + AccountSelectedGameplayAuthorityProjection.tenant(tenant(tenant)).canonicalBytes(), + AccountSelectedGameplayAuthorityProjection.membership( + member(account, tenant, "1", "2", "1"), 1L) + .canonicalBytes() + }; + } + + public static byte[][] selected( + byte[][] initial, + TenantAuthorityEventV1Codec.Event tenant, + MembershipAuthorityEventV1Codec.MembershipEvent member, + long memberSourceVersion) { + return new byte[][] { + initial[0], + initial[1], + AccountSelectedGameplayAuthorityProjection.tenant(tenant).canonicalBytes(), + AccountSelectedGameplayAuthorityProjection.membership(member, memberSourceVersion) + .canonicalBytes() + }; + } + + public static byte[] membershipBytes( + UUID account, UUID tenant, String sequence, String version, String generation) { + return AccountSelectedGameplayAuthorityProjection.membership( + member(account, tenant, sequence, version, generation), 1L) + .canonicalBytes(); + } + + public static MembershipAuthorityEventV1Codec.MembershipEvent member( + UUID account, UUID tenant, String sequence, String version, String generation) { + return MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "member-event-" + sequence), + Map.entry("requestId", "member-request-" + sequence), + Map.entry( + "outboxStreamKey", + "account:auth-authority:v1:membership/" + account + "/" + tenant), + Map.entry("outboxSequence", sequence), + Map.entry("sourceScope", "membership/" + account + "/" + tenant), + Map.entry("accountId", account.toString()), + Map.entry("tenantId", tenant.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(tenant.toString(), version)), + Map.entry("membershipAuthorityGeneration", generation), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), generation), + "privateRealmGrantVersions", + List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", List.of("player")), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + } + + public static TenantAuthorityEventV1Codec.Event tenant(UUID tenant) { + UUID creation = UUID.fromString("72a18e29-57c0-48be-a9e7-bd7b681d7720"); + UUID operation = UUID.fromString("a750fb1f-3e5d-40e6-b51e-160ef64d24ec"); + String digest = "sha256:" + "a".repeat(64); + var source = + new FreshTenantCreationEvidence( + 1, + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW")); + var request = + new DemoTenantEntitlementRequest( + UUID.fromString("15aad6f4-3c5b-4cd9-b1b9-654e6d9bc51a"), + tenant, + creation, + digest, + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(1L, 1L, 1L)); + var billing = DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + return TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billing); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java index bfbf78ae4b..6e0ab064ba 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java @@ -25,6 +25,9 @@ public final class GameSessionAccountDelegationProfile { public static final int MAX_COMPACT_JWT_BYTES = 16 * 1024; public static final int MAX_AUTHORITY_TUPLE_BYTES = 4 * 1024; public static final int MAX_REGISTRY_RECORD_BYTES = 16 * 1024; + public static final Pattern GAME_SESSION_CALLER_WORKLOAD = + Pattern.compile( + "^spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$"); private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); private GameSessionAccountDelegationProfile() {}