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