From a65495ace6c2b1c211c21e0c51b5bbf8e822c568 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Tue, 6 Oct 2026 13:49:06 +1300
Subject: [PATCH 1/3] Preserve creator-bound bootstrap and explicit Game Logic
owner manifest
---
.../account-service/runtime-and-data.md | 12 +
.../game-design-service/api-contracts.md | 10 +
.../game-logic-service/api-contracts.md | 2 +-
.../game-logic-service/runtime-and-data.md | 18 +-
...em-architecture-jwt-and-token-contracts.md | 36 +-
...ame-authoring-publishing-and-activation.md | 2 +
.../player-access-and-session.md | 2 +
.../v1/tenant_identity_service.proto | 30 +
.../GameDesignFreshTenantIdentityClient.java | 121 +++
.../AccountTenantCreationBootstrapResult.java | 49 ++
...countControlUiCurrentSourceRepository.java | 188 +++++
.../AccountTenantCreationBootstrapDigest.java | 251 ++++++
...tCreationBootstrapOperationRepository.java | 585 ++++++++++++++
.../security/AccountTokenProfileCatalog.java | 9 +-
...tCreationBootstrapAuthorizationSource.java | 20 +
...AccountTenantCreationBootstrapService.java | 755 ++++++++++++++++++
.../AccountControlUiTokenChecks.java | 319 ++++++++
...enant_creation_control_only_provenance.sql | 15 +
...V64__account_tenant_creation_bootstrap.sql | 189 +++++
...otstrapServicePostgresIntegrationTest.java | 645 +++++++++++++++
...tionProvenancePostgresIntegrationTest.java | 324 ++++++++
...iCurrentSourcePostgresIntegrationTest.java | 255 ++++++
.../AccountControlUiTokenFixture.java | 254 ++++++
...tionRepositoryPostgresIntegrationTest.java | 470 +++++++++++
...meDesignFreshTenantIdentityClientTest.java | 201 +++++
...ountTenantCreationBootstrapDigestTest.java | 188 +++++
.../AccountTokenProfileCatalogTest.java | 32 +-
...untTenantCreationBootstrapServiceTest.java | 138 ++++
.../AccountControlUiTokenChecksTest.java | 384 +++++++++
.../AccountControlUiTokenFixture.java | 250 ++++++
.../tenant/FreshTenantCreatorDigest.java | 103 +++
.../tenant/FreshTenantCreatorEvidence.java | 54 ++
.../tenant/FreshTenantCreatorDigestTest.java | 82 ++
.../FreshTenantCreatorEvidenceTest.java | 153 ++++
.../AccountAsymmetricJwtVerifier.java | 370 +++++++++
.../security/AccountJwtExactValues.java | 113 +++
.../AccountJwtProfileClaimSupport.java | 287 +++++++
.../security/AccountPublicJwksCache.java | 442 ++++++++++
.../ControlUiJwtProfileValidator.java | 104 +++
.../AccountAsymmetricJwtVerifierTest.java | 566 +++++++++++++
.../security/AccountJwtExactValuesTest.java | 121 +++
.../security/AccountPublicJwksCacheTest.java | 287 +++++++
.../ControlUiJwtProfileValidatorTest.java | 357 +++++++++
.../GameTenantCreationRepository.java | 308 +++++++
.../impl/TenantIdentityGrpcService.java | 148 ++++
.../src/main/resources/application-prod.yml | 1 +
.../src/main/resources/application.yml | 1 +
...ame_tenant_creation_initiator_evidence.sql | 165 ++++
...nantCreationRepositoryIntegrationTest.java | 359 +++++++++
.../TenantIdentityAuthConfigurationTest.java | 3 +
.../GameTenantCreationRepositoryTest.java | 53 ++
.../impl/AuthoredWorldSourceMtlsTest.java | 262 +++++-
.../impl/TenantIdentityGrpcServiceTest.java | 236 ++++++
services/game-logic-service/build.gradle.kts | 5 +
...ameLogicEmptyRuleInputManifestService.java | 87 ++
.../authoring/GameLogicRuleInputManifest.java | 243 ++++++
.../GameLogicRuleInputManifestRepository.java | 217 +++++
...game_logic_version_rule_input_manifest.sql | 98 +++
...eInputManifestPostgresIntegrationTest.java | 470 +++++++++++
.../GameLogicRuleInputManifestFixtures.java | 95 +++
.../GameLogicRuleInputManifestTest.java | 392 +++++++++
61 files changed, 11903 insertions(+), 33 deletions(-)
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecks.java
create mode 100644 services/account-service/src/main/resources/db/migration/V62__account_tenant_creation_control_only_provenance.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V64__account_tenant_creation_bootstrap.sql
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationProvenancePostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiTokenFixture.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigestTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapServiceTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecksTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenFixture.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java
create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifier.java
create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtExactValues.java
create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java
create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java
create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java
create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifierTest.java
create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountJwtExactValuesTest.java
create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java
create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java
create mode 100644 services/game-design-service/src/main/resources/db/migration/V46__game_tenant_creation_initiator_evidence.sql
create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicEmptyRuleInputManifestService.java
create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifest.java
create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestRepository.java
create mode 100644 services/game-logic-service/src/main/resources/db/migration/V2__game_logic_version_rule_input_manifest.sql
create mode 100644 services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestPostgresIntegrationTest.java
create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestFixtures.java
create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestTest.java
diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md
index 2078076aa7..fe20fe506d 100644
--- a/design/architecture/microservices/account-service/runtime-and-data.md
+++ b/design/architecture/microservices/account-service/runtime-and-data.md
@@ -237,6 +237,18 @@ Token refresh, replacement, generation, revocation, fencing, and logout are cano
Game Session orchestrates binding-refresh installation and reconciliation through Account-owned operations; it never writes Account-owned registry or authority state. Current runtime still uses the legacy Account session keys rather than the target issued-token registry, so the target refresh, replacement, fencing, and logout proof remains unavailable.
+### Exact Control-UI Issuance Recovery
+
+Ordinary `POST /auth/login` uses the crash-safe registry-backed issuance protocol in [ADR 0014](../../decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md#crash-safe-issuance-and-registry-projection). Its ingress and callers retain a stable high-entropy `requestId` for that issuance operation. This identifier belongs to durable operation identity, not an additional JWT claim, and the existing login response shape is unchanged. The semantic request digest identifies issuance semantics, not the supplied credential: Account must not retain a plaintext password, OTP, or fast credential digest to identify an exact retry.
+
+The existing Account response-envelope ring uses a distinct `control-ui-response` AEAD key and versioned targetless operation binding. It binds the exact Account subject, operation and request identities, token profile and audience, semantic request digest, original committed token and response hashes, complete applicable authority/fence/generation evidence, and original expiry. It contains no invented tenant, connect scope, Gateway context, or private-delegation binding. A key for another envelope purpose cannot decrypt this response. Provisioning, rotation, authenticated materialization/readback, and evidence-based decrypt-only key retirement remain owned by [Environment and Secrets](../../infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding); local encryption does not satisfy those delivery gates.
+
+Every recovery authenticates a currently valid credential for the same Account at the required authentication strength, then proves the exact durable operation is `COMMITTED`, its original issued-token registry record is active and exact, current authority and issuance fences still match, and the original result remains unexpired. A valid password or newly valid eligible OTP may establish fresh authentication; a consumed or expired original OTP cannot. Historical authentication evidence alone is insufficient. Changed issuance semantics conflict under the retained request identity rather than causing a new issuance.
+
+Only after those checks may Account return the original encrypted response bytes. It never remints a token, extends expiry, resets issuance time, relabels a delegation token, or treats recovery as tenant/gameplay admission. Missing custody or currentness, wrong key/purpose/binding, conflicting operation evidence, and revoked or expired registry state fail closed. Confidential response retention is bounded by its documented recovery horizon, no later than original token expiry; immutable non-secret operation evidence and the existing safe key-retirement proof remain separate.
+
+The unmerged creator-route components do not yet implement this producer or recovery path. Lost-response/restart, fresh-credential exact recovery, consumed-OTP denial, cross-Account and conflicting-request denial, expiry/revocation/currentness, and wrong-key/purpose/binding proof remain required before activation; detailed implementation status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status).
+
## Membership and Entitlement Authority
Billing-safe mutation authority contract:
diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md
index edebee4da1..5a74e440d4 100644
--- a/design/architecture/microservices/game-design-service/api-contracts.md
+++ b/design/architecture/microservices/game-design-service/api-contracts.md
@@ -122,6 +122,16 @@ The candidate read-only method is `TenantIdentityService.ResolveFreshTenantCreat
The focused proof boundary is an owner database producer/readback test that verifies atomic row+operation commit, exact retry, changed-input/source conflict with no second row or mutation, persisted digest recomputation, immutable operation/source/receipt readback, plus RPC positive exact-Account-peer and negative wrong/missing-peer tests. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) owns exact-head execution evidence and incident history. Account must separately persist its UUID-keyed identity association before membership work, as required by [Multi-Tenancy](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge); this owner proof creates no numeric alias. Neither unit tests nor database component execution substitutes for live workload authentication, a protected product creator, or a complete runtime admission handoff.
+### Fresh tenant creation initiator qualification
+
+The original `FreshTenantCreationEvidence/v1` and both creation digests above establish tenant identity, not creator authority. Preserve their exact bytes and digests. A fresh creator-qualified operation additionally records a distinct `FreshTenantCreatorEvidence/v1`: the complete original creation evidence, canonical initiating Account UUID, exact Account-owned creation-authorization operation UUID and digest, and its own qualification digest. Game Design stores both evidence classes atomically with the newly issued tenant; an unqualified existing operation cannot acquire a creator qualification afterward. Changed creator, authorization identity/digest or original creation input conflicts before mutation. Exact retries independently read back the original source and qualification. Private source keys remain provenance, never Account identity or permission.
+
+The qualification digest uses the same strict UTF-8 decimal-byte-length framing as the original creation digests. Its fixed-order segments are `game-design-tenant-creator-qualification/v1`, qualification schema version `1`, original creation schema version, namespace, creation-request UUID, original operation UUID, original request digest, canonical tenant UUID, positive decimal source game row ID, exact source tenant key, provenance kind, original evidence digest, initiating Account UUID, Account authorization operation UUID and Account authorization digest. All fields are mandatory; a valid digest binds evidence but does not authenticate its producer or authorize a creator.
+
+`TenantIdentityService.ResolveFreshTenantCreatorQualification` is a separate Account-only, same-namespace verified-mTLS read. Its closed request binds a distinct canonical `read_request_id`, the original creation request and expected request/evidence digests, the initiating Account, authorization operation/digest and expected qualification digest. Its closed response echoes the read identity and returns the complete unchanged creation evidence and distinct qualification. The receiver rejects unknown fields and authenticated forwarded caller context before owner access, compares every requested binding and both recomputed digests, and denies missing or contradictory qualification. The Account consumer authenticates Game Design and repeats those complete checks. Only this exact method is exempted from JWT interception; the workload guard remains mandatory. Existing source-only creation and authored-world source reads retain their contracts.
+
+The [Account tenant-role owner contract](../account-service/api-contracts.md#account-owned-tenant-role-administration) governs the resulting control-only first-administrator transition. Qualification storage or successful readback is not the protected Account creation-authorization producer, role bootstrap, hosted-terms acceptance or gameplay admission. These implementation and proof gaps remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md); public creation and creator authorization remain unavailable until their owner prerequisites are proved.
+
## Official Hosted Creator Mutation Gate
For official hosted deployments, every creator-intent content-bearing mutation enters the Game Design boundary only after the Account-owned currentness/evidence authority in [Account Service API Contracts](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party) has been evaluated for the tenant's Creator Party, identified operator, and hosted-terms scope under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). This applies before the first persisted Draft and before later authoring/revision, asset, template, plugin, and publication writes. The acting account's current tenant authorization is a separate conjunct; Gateway/UI checks are advisory.
diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md
index 6472c03d8e..489f0bb96f 100644
--- a/design/architecture/microservices/game-logic-service/api-contracts.md
+++ b/design/architecture/microservices/game-logic-service/api-contracts.md
@@ -6,7 +6,7 @@ This document defines the Game Logic Service REST and gRPC surfaces, exposure cl
- The current Game Logic adapters still return `shared.v1.ErrorDetail` for many failures and record `grpc.app_error`; that is implementation drift and a migration/proof gap, not a second contract.
- Causal-read status is target-only: the complete `CausalReadFence` and participant-proof enforcement described below are not current behavior. The live `ResolveLook` request/proto and World/Entity adapters remain floor-free, so protobuf propagation, adapter evidence, and focused causal-floor proof are implementation gaps.
-- The publish-gate digest handler enforces the distinct workload/method authorization and exact Game Design publication binding implemented by `PublicationReadGuard` and `PublicationDigestRequestBinding` (tenant, version scope, stable publish request, derived workflow identity, and request digest), with focused denial and response-scope checks. For a full-version request, the owner digest fails closed because Game Logic has no owner-local manifest and provenance sufficient to attest the version's rule inputs; it does not attest those inputs as an empty manifest. End-to-end full-version publication therefore remains blocked. The target workload, tenant/scope/request/workflow/digest context, exact response identity comparison, and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity).
+- The publish-gate digest handler enforces the distinct workload/method authorization and exact Game Design publication binding implemented by `PublicationReadGuard` and `PublicationDigestRequestBinding` (tenant, version scope, stable publish request, derived workflow identity, and request digest), with focused denial and response-scope checks. Game Logic now stores one explicit fresh-Version empty rule manifest, but the apply service is unregistered and default-denied without an authenticated current-source and Account commit-authority verifier. The protected `GetDraftDesignDigest` method remains fail-closed and does not read test-created or owner-internal rows as publication authority. Full-version publication therefore remains blocked. The target workload, tenant/scope/request/workflow/digest context, exact response identity comparison, and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); the owner manifest and digest semantics are defined in [Runtime and Data](runtime-and-data.md#fresh-version-explicit-empty-rule-input-manifest).
### Player execution context
diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md
index eef0de1ac1..abf009098e 100644
--- a/design/architecture/microservices/game-logic-service/runtime-and-data.md
+++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md
@@ -6,7 +6,7 @@ This document defines the Game Logic Service runtime model, dependency ownership
The sections below define the target-state runtime contract. Current implementation and proof status is:
-- The current full-version digest producer fails closed because Game Logic lacks the owner-local rule-input manifest and provenance needed to attest the selected version. It does not turn missing rule inputs into an empty manifest or synthetic commit identity. The publication binding and participant consequence are recorded in [API Contracts](api-contracts.md); the normal owner manifest and dedicated ability-schema producer remain required implementation work.
+- Game Logic now has insert-only owner storage for an explicit `EMPTY_RULE_INPUT_MANIFEST/v1` revision on a fresh Version, including the complete shared Draft binding, exact Game Design source proof, epoch-zero claim, immutable local result, and separate content/ability-schema digests. The apply service is unregistered and denies by default because no authenticated current-source plus Account commit-authority verifier is supplied. The existing `GetDraftDesignDigest` handler remains denied and does not infer empty input from missing rows or a test-created manifest; authenticated source, coordinator, and synchronized-visibility integration remain required. The scoped PostgreSQL test definitions use explicitly synthetic owner participants and test authority; no Docker execution is claimed. The publication boundary is recorded in [API Contracts](api-contracts.md).
- Same-type Game Logic takeover behind an existing edge connection is target behavior, but suppression of a client-visible reconnect after an ordinary qualifying Game Logic restart remains implementation or proof debt under ADR 0013.
- Target: `SendCommunication` and every other player-delegated gameplay RPC propagate one complete, validated typed `PlayerExecutionContext` from Game Session through Game Logic and onward. Game Logic validates the context against request and owner evidence, never treats caller-supplied identifiers as authority, remains stateless, and owns semantic gameplay outcomes; Game Session owns session, reconnect, and presentation state. This is the ADR 0024 target contract.
- Current implementation gap: the live `SendCommunicationRequest` is still a flat schema with tenant/session/character/account, communication/text and target metadata, room, game-instance, speaker, and effect fields plus legacy `session_attestation`; its current proto does not carry typed `playableStateNamespaceId`, `playableStateScope`, region/epoch, pointer, or admitted-bundle fields. Complete typed-context propagation is therefore not current behavior or proof.
@@ -25,7 +25,7 @@ The sections below define the target-state runtime contract. Current implementat
- The target runtime contract is that every player-delegated gameplay RPC carries the complete validated typed `PlayerExecutionContext`, including `tenantId`, `playableStateNamespaceId`, server-derived `playableStateScope`, active `gameInstanceId`, and applicable region/epoch or executor fences. The live per-RPC schemas, including `SendCommunication` and its legacy `session_attestation`, remain an implementation gap; see the [PlayerExecutionContext contract](../../system-architecture-authentication.md#gameplay-player-execution-context-contract-normative).
- Gameplay gRPC requests do not include JWTs. Game Session provides player identity from Redis via `SessionContext`, may refresh a JWT from Account Service if roles change, and does not validate tokens for gameplay. Service-to-service traffic still uses mutual TLS as described in the [Security Architecture](../../system-architecture-security.md).
- Utilizes the [Shared Libraries](../../system-architecture-shared-libraries.md) for DTO definitions, logging interceptors, and Micrometer metrics.
-- Flyway is enabled; the current initial migration is empty because the owner-local versioned rule/ability source is not implemented. This is implementation status, not permission to replace the target source with another service's aggregate or process-local state.
+- Flyway is enabled. The initial migration remains empty; V2 adds only the explicit immutable empty-manifest ledger. No versioned non-empty rule or ability source exists yet, so this ledger does not authorize a substitute source in another service or process-local state.
- NPC morale and aggression-state evaluation remain part of this service's runtime behavior. When gameplay rules consume faction or reputation signals sourced from Social & Groups, the local morale logic is still owned here, including transitions such as `FLEEING` and `SURRENDERED`; cross-service reputation data informs the decision, but Game Logic owns the gameplay-state consequence.
## Workflow Participation
@@ -47,7 +47,19 @@ For full-version publish gating, this service is still a required digest partici
Publish gating must fail closed if this service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`.
-The typed digest response distinguishes the complete rule-input `contentDigest` from the dedicated `abilitySchemaDigest`. Both belong to the same exact tenant/version, `appliedCommitId`, and supported `digestSchemaVersion`; a value from Automation, another participant, another commit or an unsupported source schema cannot substitute for Game Logic's ability evidence. The optional carrier represents absent evidence, not a proved empty schema. A successful full-version publish requires the dedicated Game Logic value, preserves it in the immutable release participant evidence and compares it exactly for plugin compatibility. Defining the normal persisted input manifest, its ability-schema subset and canonicalization remains producer work; the current unavailable producer must continue rejecting the request rather than manufacture either digest.
+The typed digest response distinguishes the complete rule-input `contentDigest` from the dedicated `abilitySchemaDigest`. Both belong to the same exact tenant/version, `appliedCommitId`, and supported `digestSchemaVersion`; a value from Automation, another participant, another commit or an unsupported source schema cannot substitute for Game Logic's ability evidence. The optional carrier represents absent evidence, not a proved empty schema. A successful full-version publish requires the dedicated Game Logic value, preserves it in the immutable release participant evidence and compares it exactly for plugin compatibility. The non-empty versioned rule/ability source and its complete producer remain future implementation work; the current public digest handler must continue rejecting requests rather than manufacture either digest.
+
+### Fresh-version explicit empty rule-input manifest
+
+The only owner apply shape currently supported is one explicit `EMPTY_RULE_INPUT_MANIFEST/v1` revision for a genuinely fresh Version. Its canonical Game Logic revision payload is `{"intentKind":"EMPTY_RULE_INPUT_MANIFEST/v1","manifest":{"abilitySchemas":[],"ruleInputs":[],"schemaVersion":1}}`. Both arrays are present and empty by creator intent; query absence, an absent row, or a fabricated version marker is not proof of an empty source. Any non-empty or configured rule/ability input is rejected until a future owner source and contract are defined.
+
+The owner operation consumes the complete existing `common.authoring.DraftCommitBinding` unchanged. Its target retains the exact canonical tenant and Version UUID plus Game Design Version/source row, private tenant-key, and provenance evidence. The full five-owner declaration remains mandatory. Game Logic derives exactly one affected tuple: owner `GAME_LOGIC`, aggregate `VERSION_RULE_MANIFEST`, aggregate ID equal to the canonical Version UUID, scope type `VERSION`, scope ID equal to that UUID, and expected epoch `0`. It rejects an omitted or additional Game Logic revision or affected unit and any nonzero expected epoch. The current-source and Account commit-authority verifier must validate that exact binding and keep authority effective through the Game Logic transaction; no production verifier is currently supplied, and the apply service remains unregistered and default-denied.
+
+The owner transaction inserts one immutable row keyed by canonical tenant and Version. That insert is the storage-level epoch-zero compare-and-swap: it retains the exact source proof, complete canonical binding and digest, explicit owner revision, request ID, actual commit ID, base commit, semantic digest preimages, aggregate/scope epoch advances from `0` to `1`, and exact `GAME_LOGIC` owner result together. A duplicate request returns the original row only when every retained binding and input byte matches. Any changed field, including source, request, commit, base, revision, or binding, conflicts; concurrent first claims retain one original result. The database rejects update and delete of the row. This local owner result is not proof that the other four owners applied or that the synchronized Game Design read fence advanced.
+
+Digest schema `1` hashes only the canonical RFC 8785 JSON semantic input `{"abilitySchemas":[],"digestSchemaVersion":1,"ruleInputs":[]}` as SHA-256 lowercase hexadecimal without a prefix. Its golden vector is `71b4da6a96f68a6f85d48731f5b4e448d05d21241ca75016ef0c9a0000c14f74`. The separate ability-schema digest hashes its own canonical RFC 8785 JSON preimage `{"abilitySchemaDigestDomain":"firemud.game-logic.ability-schema/v1","abilitySchemaVersion":1,"abilitySchemas":[]}`; its golden vector is `a6c1b6d52654bce002ddb64de2d84853061aa87cb15407547038cc3d4e7cfbd4`. The digest preimages include the explicit semantic arrays and their schema/domain versions. Tenant/version scope, Game Design source proof, full binding, request/commit/base identity, owner epochs, owner result, and storage timestamps are retained as provenance but excluded from these content hashes. Any change to included inputs, exclusions, canonicalization, or digest schema requires an explicit schema bump and replay/re-record workflow.
+
+The storage readback is internal owner evidence for later composition. It does not enable `GetDraftDesignDigest`: the public protected method remains fail-closed until an authenticated current-source and Account verifier, exact applied binding, and coordinated synchronized-visibility read path are integrated. Missing or unsupported rule/ability evidence remains a hard publication gate failure.
## Redis Role and Prefixes
diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md
index f69e5a8641..2d2c066d39 100644
--- a/design/architecture/system-architecture-jwt-and-token-contracts.md
+++ b/design/architecture/system-architecture-jwt-and-token-contracts.md
@@ -37,6 +37,24 @@ authorityTuple: {
}
```
+### Canonical Authority Counter Representation
+
+Authority counters are JSON strings containing canonical unsigned base-10 integers, never JSON numbers. The positive grammar `[1-9][0-9]*` applies to `tokenGeneration`, `issuanceFence`, issuer/account generations, every tenant/membership generation-map value, `grantVersion`, and every generation or sequence inside an applicable account-security or tenant-billing cutoff. The separate `membershipVersion` map follows [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md#canonical-membershipversion-carrier): its values use `0|[1-9][0-9]*`. A structurally valid zero membership version does not prove that a membership exists or authorize a route. Required empty maps and lists retain their exact empty representations.
+
+Consumers validate the grammar and compare arbitrary-precision integer values without a signed-64-bit ceiling, IEEE-754 conversion, or lexicographic ordering. Signs, leading zeros, whitespace, fractions, exponents, alternate numeral forms and numeric/string aliases are invalid. Complete carrier equality still compares every identity, map key, list entry, counter and presence/absence value; canonical byte measurement is not an equality oracle. Counter values remain independent even when their current values happen to match.
+
+JWT `iat`, `nbf` and `exp` remain exact bounded numeric UTC epoch-second timestamps; numeric schema literals and opaque identifiers do not become authority counters. Separately owned source-version, checkpoint, bundle-capture and signer evidence retains its owning schema and is not retyped by this rule. Account's sole-writer SQL counters keep their documented storage range: source overflow fails the producer before mutation, without wrapping or widening storage. Historical signed JWTs and digests are never rewritten or interpreted through a compatibility alias; a noncanonical credential requires fresh canonical issuance.
+
+The exact RFC 8785 canonical UTF-8 vectors below retain all decimal digits, including beyond Java `long`; the differing strings must never compare equal:
+
+| Logical counter | Canonical JSON bytes (ASCII subset of UTF-8) |
+| --- | --- |
+| `9007199254740992` | `{"tokenGeneration":"9007199254740992"}` |
+| `9007199254740993` | `{"tokenGeneration":"9007199254740993"}` |
+| `9223372036854775808` | `{"tokenGeneration":"9223372036854775808"}` |
+| `9223372036854775809` | `{"tokenGeneration":"9223372036854775809"}` |
+| Zero membership version | `{"membershipVersion":{"018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f":"0"}}` |
+
In contract examples, a trailing `?` on an object field marks an **Optional object field**: the object may be omitted only when that object is inapplicable to the profile or operation. It is not a shorthand for an empty object, and `null` is not omission. A **Required** field must be present even when its value is empty. A required **Empty-map** or **Empty-list** field must serialize its declared empty representation (`{}` or `[]`); omission, `null`, a scalar sentinel, or another empty shape is not equivalent. These presence rules apply consistently to JWT claims, registry records, evidence bundles, and bindings.
`issuerAuthGeneration` and `accountAuthorityGeneration` are positive Account-owned generations. `tenantAuthorityGeneration` and `membershipAuthorityGeneration` are independent maps keyed by exact tenant IDs; each map's applicable keys are determined separately by the token profile and route classification. The closed `billing_safe_tenant` exception can omit the target-tenant generation from route comparison, but it must not omit the canonical generation claim or the target-tenant key when the token profile requires that scoped key. Explicitly unscoped artifacts use empty maps. `privateRealmGrantVersions` contains exact lifecycle-bound non-public grant entries `{tenantId, worldSlug, realmSlug, playtestLifecycleId, grantVersion}` for every ordinary-private and playtest grant, and is empty for public production. The corresponding grant stream for either kind uses the canonical grant authority-stream scope codec; its exact field forms and codec bounds are defined by the [identifier glossary](./system-architecture-identifier-glossary.md#non-public-grant-identity) and [grant authority-stream codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec), without redefining that codec here. There is no ordinary-private grant entry without `playtestLifecycleId`. `accountSecurityCutoff` is an optional object field, and `tenantBillingCutoff` is an optional object field omitted when no tenant billing cutoff applies; neither is a replacement authority and neither uses collection omission-as-empty semantics. `membershipVersion` is separate membership projection/version data and `billing_safe_tenant` requires it to be compared independently from `membershipAuthorityGeneration`; neither field substitutes for the other. A missing applicable field, extra scope, malformed value, or mismatch fails closed.
@@ -229,16 +247,16 @@ Workload-only methods explicitly declare token profile, type, issuer, and audien
- `iat`: `1735689600`
- `nbf`: `1735689600`
- `exp`: `1735693200`
-- `tokenGeneration`: `12`
+- `tokenGeneration`: `"12"`
- `authorityTuple`:
- - `issuerAuthGeneration`: `7`
- - `accountAuthorityGeneration`: `12`
- - `tenantAuthorityGeneration`: `{ "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": 4, "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a": 9 }`
- - `membershipAuthorityGeneration`: `{ "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": 18, "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a": 3 }`
+ - `issuerAuthGeneration`: `"7"`
+ - `accountAuthorityGeneration`: `"12"`
+ - `tenantAuthorityGeneration`: `{ "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "4", "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a": "9" }`
+ - `membershipAuthorityGeneration`: `{ "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "18", "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a": "3" }`
- `privateRealmGrantVersions`: `[]`
- - `accountSecurityCutoff`: `{ accountAuthorityGeneration: 12, outboxStreamKey: "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", outboxSequence: 44 }`
-- `issuanceFence`: `27`
-- `membershipVersion`: `{ "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": 42, "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a": 7 }`
+ - `accountSecurityCutoff`: `{ accountAuthorityGeneration: "12", outboxStreamKey: "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", outboxSequence: "44" }`
+- `issuanceFence`: `"27"`
+- `membershipVersion`: `{ "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "42", "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a": "7" }`
- `globalRoles`: `["billingAdmin"]`
- `scopedRoles`:
- `"018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f"` -> `["tenantAdmin", "designer"]`
@@ -348,7 +366,7 @@ This is a closed Account claim set: all listed claims are required except the tw
| `iat` | Required | Required | Required | Required | UTC epoch seconds; Gateway preserves the gameplay-connect value as context `issuedAt` |
| `nbf` | Required | Required | Absent | Required | Token not usable before this time when present |
| `exp` | Required | Required | Required | Required | Token unusable after this time; `gameplay-connect` lifetime is at most 30 seconds from `iat` |
-| `tokenGeneration` | Required | Required | Absent (ordinary registry-only lineage field) | Required | Positive integer for issued-token-registry lineage; gameplay-connect instead uses its dedicated single-use replay contract |
+| `tokenGeneration` | Required | Required | Absent (ordinary registry-only lineage field) | Required | Canonical positive decimal string for issued-token-registry lineage; gameplay-connect instead uses its dedicated single-use replay contract |
| `authorityTuple` | Required | Required | Required | Required | Complete applicable tuple. For `gameplay-connect`, the exact bounded selected-target tuple is immutable issuance evidence passed unchanged through Gateway context into the later admission lease/binding checks; it is not registry-backed or standalone gameplay authority |
| `authorityTuple.issuerAuthGeneration` | Required | Required | Required | Required | Positive monotonic Account-owned issuer generation captured at issuance |
| `authorityTuple.accountAuthorityGeneration` | Required | Required | Required | Required | Positive monotonic Account-owned account generation captured at issuance |
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index e2949fc508..cb304006e6 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a
## Current Status
+The creator/owner prerequisite retains Game Design's original fresh-tenant evidence and adds an immutable initiating-Account qualifier and exact Account-workload-only readback under V46. The protected method has physical peer-denial proof, but its persisted qualifier is not an Account authorization grant. Game Logic now has a V2 owner-local explicit empty rule/ability manifest: the full five-owner Draft binding, exact source/Version, epoch-zero claim, immutable owner result and semantic digest vectors are retained and read back atomically. The application and storage classes remain unregistered/default-denied, and the public digest still refuses unsupported publication; missing content is not interpreted as empty. The composed Common/Account/Game Design/Game Logic checks and three service boot JARs pass, including all 101 Game Logic unit methods. Five Game Logic service-context cases execute; its ten new PostgreSQL cases and all 137 Game Design PostgreSQL cases skip without local Docker. Corrected database execution, authenticated owner application, synchronized visibility, actual full-release assembly and World lifecycle transport remain required. This is neither publication nor Gameplay activation proof.
+
At exact published `968fa3bb98efa19f50e659f4769fc3b1537e0787`, [CI37344877274](https://github.com/benhook1013/FireMUD/actions/runs/37344877274) Game Design Build and Test succeeded. Independently parsed raw XML repeats all twenty required PostgreSQL cases cleanly without skips: coordinator11 and selected-Draft9, including the exact concurrent-claim correction. Verified runner merge `238ac09f75a25a2d742acf6d89a565e85af5d897` has the exact unchanged Account parent and candidate parents, with head-identical tree `2243bed55dbb95c618d7359eb88a00f49026bc50`. Account's required source selections and World29 also passed at this source; aggregate CI was still active at the scoped handoff. Missing authenticated actor/creator/terms, complete owner/release producers, synchronized normal reads and runtime activation remain independent obligations.
At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) Game Design Build and Test succeeded. Independently parsed raw XML proves all twenty required PostgreSQL cases executed once with zero skips, failures or errors: eleven coordinator and nine selection cases. This includes the repaired identical-concurrent claim and both conflicting concurrent-identity cases. The five publication transaction, eight descriptor PostgreSQL and fourteen physical mTLS cases also executed cleanly. Runner checkout `a4c1a66b3930de6825542b9b5a2e79410a067a65` has the exact unchanged Account parent and published candidate as parents and a head-identical tree. This closes the coordinator race and selected-Draft database fixture/proof gaps below; it does not supply the missing authenticated actor/owner/release producers or runtime activation. World passed its separate twenty-eight required cases; Account stopped at an inherited OTP transaction-observer fixture before its required source-proof cases executed. Aggregate green is not claimed.
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 f72c49523f..c0f4619f80 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca
## Current Status
+The creator/owner prerequisite adds V62's non-admitting tenant-creation provenance and V64's atomic Account creator-bootstrap receipt. A verified fresh source can commit the control-only `tenantAdmin` membership, role snapshot, first event, audit and exact immutable result together; it does not infer `PLAYER` or gameplay admission. New commits remain denied without a registered current Account authorization/source participant. Persisted result evidence uses the exact one-tenant `membershipVersion` map while normalized sole-writer counters remain BIGINT. The new unscoped control-ui verifier and existing-only source observations validate canonical decimal counters, profile/registry equality and declared source evidence, but do not authenticate credentials, mint a complete authority bundle, issue a token or write the active registry. Account's full check and boot JAR pass with 984 clean unit results; all 404 PostgreSQL methods compile and skip locally without Docker. The real ordinary control-ui issuance/exact encrypted recovery, authenticated creator participant, subsequent explicit JOIN and live key custody/readiness remain open; no credential, RPC or ring activation is enabled.
+
The exact `678ca7c2c18679242c25d708dcbea1ba45894000` [CI37391494393](https://github.com/benhook1013/FireMUD/actions/runs/37391494393) executed all seven pending-reset source-change and seventeen logout-all PostgreSQL methods without skips. All seven reset methods failed because overlong generated schema names were truncated and collided; sixteen logout methods passed, while the V59-to-V60 fixture attempted to read a V61-only column. The correction preserves the full random schema suffix, the exact original source-change binding and every applicable V59/V60 retained-row image, and keeps that migration proof explicitly targeted at V60. Focused compilation, integration SpotBugs and Checkstyle pass locally; corrected PostgreSQL execution remains required. Exact merge parents and a source-identical tree establish attribution. No credential, creator-authority, ring or runtime activation follows from these fixture corrections.
The prepared V61 preservation component adds an immutable pending-reset request/source journal and a separate encrypted verifier row, linked to V57 ordering. `SOURCE_ABORTED` is a distinct no-mutation terminal result, never a fabricated source commit. An expired verifier may be erased while unresolved owner participation remains `WAITING`; expiry alone cannot settle or release the fence. Seven new PostgreSQL definitions cover retained exact ciphertext, changed-binding/remint denial, deferred live-envelope enforcement, both-owner ordering, expiry, rollback and immutable cancellation. Their upstream owner results are synthetic fixture readbacks, not authenticated producer proof. The Account full check, boot JAR, analyzers, formatting, links and Markdown pass in 30s with 964 clean unit results; all 393 integration cases, including these seven, skip without Docker. The previously failing logout-all assertion now preserves the complete original framed readback, but corrected PostgreSQL execution remains required. Public reset recovery, completion and cleanup integration are not implemented by this preservation checkpoint; further reset expansion is parked while the fresh authored-world application/lifecycle dependency is prioritized.
diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto
index ac061b5864..ed26a34d78 100644
--- a/protos/game-design/v1/tenant_identity_service.proto
+++ b/protos/game-design/v1/tenant_identity_service.proto
@@ -15,6 +15,9 @@ service TenantIdentityService {
// Exact immutable readback of a newly created tenant operation for Account.
rpc ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest)
returns (ResolveFreshTenantCreationResponse);
+ // Same-namespace Account mTLS read only, without forwarded caller context.
+ rpc ResolveFreshTenantCreatorQualification(ResolveFreshTenantCreatorQualificationRequest)
+ returns (ResolveFreshTenantCreatorQualificationResponse);
// Exact owner-local read of one persisted runtime tenant identity for Game Session.
rpc ResolveRuntimeTenantIdentity(ResolveRuntimeTenantIdentityRequest)
returns (ResolveRuntimeTenantIdentityResponse);
@@ -108,6 +111,33 @@ message ResolveFreshTenantCreationResponse {
string evidence_digest = 10;
}
+message ResolveFreshTenantCreatorQualificationRequest {
+ // Distinct Account read identity; it does not replace the creation request identity.
+ string read_request_id = 1;
+ string creation_request_id = 2;
+ string expected_request_digest = 3;
+ string expected_evidence_digest = 4;
+ string initiating_account_id = 5;
+ string account_authorization_operation_id = 6;
+ string account_authorization_digest = 7;
+ string expected_creator_evidence_digest = 8;
+}
+
+message FreshTenantCreatorQualificationEvidence {
+ int32 schema_version = 1;
+ string initiating_account_id = 2;
+ string account_authorization_operation_id = 3;
+ string account_authorization_digest = 4;
+ string evidence_digest = 5;
+}
+
+message ResolveFreshTenantCreatorQualificationResponse {
+ string read_request_id = 1;
+ // Original source identity evidence remains byte-for-byte and digest-for-digest unchanged.
+ ResolveFreshTenantCreationResponse creation_evidence = 2;
+ FreshTenantCreatorQualificationEvidence creator_qualification = 3;
+}
+
message ResolveRuntimeTenantIdentityRequest {
string canonical_tenant_id = 1;
string request_id = 2;
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClient.java
index 9863b2b1a7..6727da1cfc 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClient.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClient.java
@@ -13,9 +13,13 @@
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor;
import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest;
import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse;
+import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreatorQualificationRequest;
+import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreatorQualificationResponse;
import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc;
/** Caller-owned Account candidate for exact fresh-creation readback from Game Design. */
@@ -123,6 +127,123 @@ public FreshTenantCreationEvidence resolveCreation(
return evidence;
}
+ /**
+ * Reads the immutable Account initiator qualification for one exact source receipt.
+ *
+ *
This candidate consumer validates transport evidence only. It does not capture or
+ * authenticate the initiating Account identity; the protected Account creation adapter remains
+ * responsible for supplying an authorized binding.
+ */
+ public FreshTenantCreatorEvidence resolveCreatorQualification(
+ UUID readRequestId,
+ FreshTenantCreationEvidence expectedCreationEvidence,
+ UUID initiatingAccountId,
+ UUID accountAuthorizationOperationId,
+ String accountAuthorizationDigest) {
+ if (readRequestId == null || NIL_UUID.equals(readRequestId)) {
+ throw new IllegalArgumentException("Canonical nonnil creator read request ID is required");
+ }
+ if (expectedCreationEvidence == null
+ || !workloadNamespace.equals(expectedCreationEvidence.targetNamespace())) {
+ throw new IllegalArgumentException(
+ "Exact fresh tenant source evidence for the configured namespace is required");
+ }
+ if (initiatingAccountId == null || NIL_UUID.equals(initiatingAccountId)) {
+ throw new IllegalArgumentException("Canonical nonnil initiating Account UUID is required");
+ }
+ if (accountAuthorizationOperationId == null
+ || NIL_UUID.equals(accountAuthorizationOperationId)) {
+ throw new IllegalArgumentException(
+ "Canonical nonnil Account authorization operation UUID is required");
+ }
+ if (!GameTenantCreationDigest.isDigest(accountAuthorizationDigest)) {
+ throw new IllegalArgumentException("Canonical Account authorization digest is required");
+ }
+ String expectedCreatorEvidenceDigest =
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1,
+ expectedCreationEvidence,
+ initiatingAccountId,
+ accountAuthorizationOperationId,
+ accountAuthorizationDigest);
+
+ ResolveFreshTenantCreatorQualificationResponse response =
+ stub()
+ .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS)
+ .resolveFreshTenantCreatorQualification(
+ ResolveFreshTenantCreatorQualificationRequest.newBuilder()
+ .setReadRequestId(readRequestId.toString())
+ .setCreationRequestId(expectedCreationEvidence.creationRequestId().toString())
+ .setExpectedRequestDigest(expectedCreationEvidence.requestDigest())
+ .setExpectedEvidenceDigest(expectedCreationEvidence.evidenceDigest())
+ .setInitiatingAccountId(initiatingAccountId.toString())
+ .setAccountAuthorizationOperationId(accountAuthorizationOperationId.toString())
+ .setAccountAuthorizationDigest(accountAuthorizationDigest)
+ .setExpectedCreatorEvidenceDigest(expectedCreatorEvidenceDigest)
+ .build());
+
+ if (!response.getUnknownFields().asMap().isEmpty()
+ || !response.hasCreationEvidence()
+ || !response.hasCreatorQualification()) {
+ throw new IllegalStateException(
+ "Game Design creator qualification response is not the exact closed schema");
+ }
+ if (!response.getCreationEvidence().getUnknownFields().asMap().isEmpty()
+ || !response.getCreatorQualification().getUnknownFields().asMap().isEmpty()) {
+ throw new IllegalStateException("Game Design creator qualification contains unknown fields");
+ }
+ if (!readRequestId.toString().equals(response.getReadRequestId())) {
+ throw new IllegalStateException("Game Design did not echo the exact creator read identity");
+ }
+
+ FreshTenantCreationEvidence actualCreationEvidence;
+ try {
+ ResolveFreshTenantCreationResponse source = response.getCreationEvidence();
+ actualCreationEvidence =
+ new FreshTenantCreationEvidence(
+ source.getSchemaVersion(),
+ source.getTargetNamespace(),
+ parseCanonicalNonNilUuid(source.getCreationRequestId()),
+ parseCanonicalNonNilUuid(source.getOperationId()),
+ source.getRequestDigest(),
+ parseCanonicalNonNilUuid(source.getCanonicalTenantId()),
+ source.getSourceGameRowId(),
+ source.getSourceGameTenantKey(),
+ source.getProvenanceKind(),
+ source.getEvidenceDigest());
+ } catch (IllegalArgumentException exception) {
+ throw new IllegalStateException("Game Design source creation evidence is invalid", exception);
+ }
+ if (!expectedCreationEvidence.equals(actualCreationEvidence)) {
+ throw new IllegalStateException(
+ "Game Design creator qualification changed the original source evidence");
+ }
+
+ FreshTenantCreatorEvidence qualification;
+ try {
+ var wireQualification = response.getCreatorQualification();
+ qualification =
+ new FreshTenantCreatorEvidence(
+ wireQualification.getSchemaVersion(),
+ actualCreationEvidence,
+ parseCanonicalNonNilUuid(wireQualification.getInitiatingAccountId()),
+ parseCanonicalNonNilUuid(wireQualification.getAccountAuthorizationOperationId()),
+ wireQualification.getAccountAuthorizationDigest(),
+ wireQualification.getEvidenceDigest());
+ } catch (IllegalArgumentException exception) {
+ throw new IllegalStateException(
+ "Game Design creator qualification evidence is invalid", exception);
+ }
+ if (!initiatingAccountId.equals(qualification.initiatingAccountId())
+ || !accountAuthorizationOperationId.equals(qualification.accountAuthorizationOperationId())
+ || !accountAuthorizationDigest.equals(qualification.accountAuthorizationDigest())
+ || !expectedCreatorEvidenceDigest.equals(qualification.evidenceDigest())) {
+ throw new IllegalStateException(
+ "Game Design creator qualification does not match the exact Account binding");
+ }
+ return qualification;
+ }
+
private static UUID parseCanonicalNonNilUuid(String value) {
if (value == null) {
throw new IllegalArgumentException("UUID evidence is required");
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java
new file mode 100644
index 0000000000..467461750d
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java
@@ -0,0 +1,49 @@
+package net.firedevops.firemud.accountservice.dto;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/** Immutable historical Account owner result for one source-bound creator membership bootstrap. */
+public record AccountTenantCreationBootstrapResult(
+ UUID operationId,
+ String requestDigest,
+ UUID initiatingAccountUuid,
+ UUID tenantUuid,
+ String creatorEvidenceDigest,
+ String sourceSnapshotDigest,
+ Map membershipVersion,
+ String membershipAuthorityGeneration,
+ List roles,
+ boolean gameplayAdmissionAllowed,
+ String eventStreamKey,
+ String eventRequestId,
+ long eventSequence,
+ String eventId,
+ String eventDigest,
+ UUID auditEventId,
+ String auditEventType,
+ String auditPayloadDigest,
+ String resultDigest) {
+ public AccountTenantCreationBootstrapResult {
+ if (operationId == null
+ || initiatingAccountUuid == null
+ || tenantUuid == null
+ || membershipVersion == null
+ || membershipAuthorityGeneration == null
+ || roles == null
+ || eventStreamKey == null
+ || eventRequestId == null
+ || eventSequence <= 0L
+ || eventId == null
+ || eventDigest == null
+ || auditEventId == null
+ || auditEventType == null
+ || auditPayloadDigest == null
+ || resultDigest == null) {
+ throw new IllegalArgumentException("Committed creator-bootstrap result is incomplete");
+ }
+ membershipVersion = Map.copyOf(membershipVersion);
+ roles = List.copyOf(roles);
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java
new file mode 100644
index 0000000000..8ce4da5e70
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java
@@ -0,0 +1,188 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountLifecycleState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot;
+import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository.FreshEmptySource;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot;
+import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiTokenChecks.InspectedToken;
+import net.firedevops.firemud.common.security.AccountJwtExactValues;
+import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator;
+import org.jooq.DSLContext;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Existing-only source observations for the genuinely unscoped fresh-creator control-ui cut.
+ *
+ * All observations use the same locked Account transaction. The result is not a complete
+ * account-auth-evidence-bundle/v1 and never authorizes creator registration: issuer event/source
+ * provenance, current Coordination projections, durable token issuance and signer-generation
+ * retention remain separate prerequisites. Reads cannot enroll missing authority or roles.
+ */
+public final class AccountControlUiCurrentSourceRepository {
+ private static final JsonMapper JSON = JsonMapper.builder().build();
+ private final DSLContext dsl;
+ private final AccountRepository accounts;
+ private final AccountGlobalRoleSourceRepository globalRoles;
+ private final AccountAuthorityGenerationRepository generations;
+ private final AccountAuthoritySourceEventReadback accountSource;
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "Injected Account persistence collaborators remain internal owners.")
+ public AccountControlUiCurrentSourceRepository(
+ DSLContext dsl,
+ AccountRepository accounts,
+ AccountGlobalRoleSourceRepository globalRoles,
+ AccountAuthorityGenerationRepository generations,
+ AccountAuthoritySourceEventReadback accountSource) {
+ this.dsl = Objects.requireNonNull(dsl);
+ this.accounts = Objects.requireNonNull(accounts);
+ this.globalRoles = Objects.requireNonNull(globalRoles);
+ this.generations = Objects.requireNonNull(generations);
+ this.accountSource = Objects.requireNonNull(accountSource);
+ }
+
+ /**
+ * Compares the independently signed/registered candidate with existing current source rows. No
+ * credential authentication or public caller principal is created by this method.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public CurrentSourceObservation inspectUnscopedCurrent(InspectedToken candidate) {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw invalid();
+ }
+ Objects.requireNonNull(candidate);
+ Map claims = candidate.claims();
+ if (!Map.of().equals(claims.get("scopedRoles"))
+ || !Map.of().equals(claims.get("membershipVersion"))
+ || (claims.containsKey("globalRoles") && !List.of().equals(claims.get("globalRoles")))) {
+ throw invalid();
+ }
+ FreshEmptySource roles = globalRoles.readFreshEmptySourceForUpdate(candidate.accountId());
+ Account account =
+ accounts
+ .findByAccountUuidForUpdate(candidate.accountId())
+ .orElseThrow(AccountControlUiCurrentSourceRepository::invalid);
+ if (account.getLifecycleState() != AccountLifecycleState.ACTIVE
+ || !roles.accountUuid().equals(account.getAccountUuid())
+ || account.getAccountUuidSourceNumericId() == null
+ || roles.accountUuidSourceNumericId() != account.getAccountUuidSourceNumericId()
+ || roles.accountUuidProvenance() != account.getAccountUuidProvenance()
+ || account.getId() == null
+ || roles.accountRowId() != account.getId()) throw invalid();
+ CompositeSnapshot current =
+ generations.readCompositeSnapshot(
+ ControlUiJwtProfileValidator.ISSUER, candidate.accountId(), List.of(), List.of());
+ var latest = accountSource.requireCurrentLatest(account, current.account());
+ String stream = "account:auth-authority:v1:account/" + candidate.accountId();
+ if (latest.outboxSequence() == 0L) {
+ Long events =
+ Objects.requireNonNull(
+ dsl.fetchOne(
+ "SELECT COUNT(*) AS event_count FROM account_authority_outbox_events "
+ + "WHERE outbox_stream_key = ?",
+ stream),
+ "Account source event count returned no row")
+ .get("event_count", Long.class);
+ if (events == null || events != 0L) throw invalid();
+ }
+ AccountSourceSnapshot source =
+ new AccountSourceSnapshot(
+ candidate.accountId(),
+ current.account(),
+ stream,
+ latest.outboxSequence(),
+ latest.latestEvent());
+ Map tuple = new java.util.LinkedHashMap<>();
+ tuple.put("issuerAuthGeneration", Long.toString(current.issuer().generation()));
+ tuple.put("accountAuthorityGeneration", Long.toString(current.account().generation()));
+ tuple.put("tenantAuthorityGeneration", Map.of());
+ tuple.put("membershipAuthorityGeneration", Map.of());
+ tuple.put("privateRealmGrantVersions", List.of());
+ latest
+ .latestEvent()
+ .ifPresent(
+ event -> {
+ try {
+ Map wire =
+ JSON.readValue(event.payload(), new TypeReference<>() {});
+ tuple.put("accountSecurityCutoff", wire.get("accountSecurityCutoff"));
+ } catch (IOException failure) {
+ throw invalid();
+ }
+ });
+ requireEqual(tuple, claims.get("authorityTuple"));
+ requireEqual(Long.toString(current.issuanceFence().value()), claims.get("issuanceFence"));
+ Map expectedVersions =
+ Map.of(
+ "issuerSourceVersion", current.issuer().sourceVersion(),
+ "accountSourceVersion", current.account().sourceVersion(),
+ "issuanceFenceSourceVersion", current.issuanceFence().sourceVersion());
+ requireEqual(expectedVersions, candidate.registryRecord().get("authoritySourceVersions"));
+ return new CurrentSourceObservation(
+ candidate.accountId(), current, source, roles.globalRoleSourceVersion());
+ }
+
+ private static void requireEqual(Object left, Object right) {
+ if (left == null || right == null || !AccountJwtExactValues.sameJsonValue(left, right)) {
+ throw invalid();
+ }
+ }
+
+ private static IllegalStateException invalid() {
+ return new IllegalStateException("Account control-ui current source observation failed");
+ }
+
+ /** Private-minted same-transaction source evidence; deliberately not an authority receipt. */
+ public static final class CurrentSourceObservation {
+ private final UUID accountId;
+ private final CompositeSnapshot authority;
+ private final AccountSourceSnapshot accountSource;
+ private final long globalRoleSourceVersion;
+
+ private CurrentSourceObservation(
+ UUID accountId,
+ CompositeSnapshot authority,
+ AccountSourceSnapshot accountSource,
+ long globalRoleSourceVersion) {
+ this.accountId = accountId;
+ this.authority = authority;
+ this.accountSource = accountSource;
+ this.globalRoleSourceVersion = globalRoleSourceVersion;
+ }
+
+ public UUID accountId() {
+ return accountId;
+ }
+
+ public CompositeSnapshot authority() {
+ return authority;
+ }
+
+ public AccountSourceSnapshot accountSource() {
+ return accountSource;
+ }
+
+ public long globalRoleSourceVersion() {
+ return globalRoleSourceVersion;
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiCurrentSourceObservation[non-authorizing]";
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java
new file mode 100644
index 0000000000..e17c784be8
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java
@@ -0,0 +1,251 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.PrivateRealmGrantVersion;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+
+/** Canonical complete-map encodings and digests for immutable creator-bootstrap owner evidence. */
+public final class AccountTenantCreationBootstrapDigest {
+ private static final String REQUEST_DOMAIN =
+ "firemud/account/tenant-creation-bootstrap/request/v1";
+ private static final String RESULT_DOMAIN = "firemud/account/tenant-creation-bootstrap/result/v1";
+
+ private AccountTenantCreationBootstrapDigest() {}
+
+ public static byte[] creatorEvidencePayload(FreshTenantCreatorEvidence evidence) {
+ Objects.requireNonNull(evidence, "creator evidence is required");
+ Map creator = new LinkedHashMap<>();
+ creator.put("schemaVersion", Integer.toString(evidence.schemaVersion()));
+ creator.put("creationEvidence", creationEvidenceMap(evidence.creationEvidence()));
+ creator.put("initiatingAccountId", evidence.initiatingAccountId().toString());
+ creator.put(
+ "accountAuthorizationOperationId", evidence.accountAuthorizationOperationId().toString());
+ creator.put("accountAuthorizationDigest", evidence.accountAuthorizationDigest());
+ creator.put("evidenceDigest", evidence.evidenceDigest());
+ return canonicalJson(creator);
+ }
+
+ public static byte[] sourceSnapshotPayload(NeverJoinedMembershipSnapshot snapshot) {
+ Objects.requireNonNull(snapshot, "Account baseline snapshot is required");
+ Map source = new LinkedHashMap<>();
+ source.put("accountId", snapshot.accountId());
+ source.put("tenantId", snapshot.tenantId());
+ source.put("membershipExists", snapshot.membershipExists());
+ source.put("membershipLifecycleState", snapshot.membershipLifecycleState());
+ source.put("gameplayAdmissionAllowed", snapshot.gameplayAdmissionAllowed());
+ source.put("roles", snapshot.roles());
+ source.put("membershipVersion", snapshot.membershipVersion());
+ source.put("membershipAuthorityGeneration", snapshot.membershipAuthorityGeneration());
+ source.put("authorityTuple", authorityTupleMap(snapshot.authorityTuple()));
+ source.put("issuanceFence", snapshot.issuanceFence());
+ source.put("evaluatedAt", snapshot.evaluatedAt().toString());
+ source.put("outboxStreamKey", snapshot.outboxStreamKey());
+ source.put(
+ "outboxCheckpoints",
+ snapshot.outboxCheckpoints().stream()
+ .map(
+ checkpoint ->
+ Map.of(
+ "outboxStreamKey", checkpoint.outboxStreamKey(),
+ "outboxSequence", checkpoint.outboxSequence()))
+ .toList());
+ source.put(
+ "outboxSourceEvidence",
+ snapshot.outboxSourceEvidence().stream()
+ .map(
+ evidence ->
+ Map.of(
+ "outboxStreamKey", evidence.outboxStreamKey(),
+ "outboxSequence", evidence.outboxSequence(),
+ "eventId", evidence.eventId(),
+ "eventDigest", evidence.eventDigest(),
+ "canonicalEventJson", evidence.canonicalEventJson()))
+ .toList());
+ return canonicalJson(source);
+ }
+
+ public static byte[] requestPayload(byte[] creatorEvidencePayload, byte[] sourceSnapshotPayload) {
+ return frameBytes(
+ REQUEST_DOMAIN.getBytes(StandardCharsets.UTF_8),
+ creatorEvidencePayload,
+ sourceSnapshotPayload);
+ }
+
+ public static byte[] resultPayload(
+ String requestId,
+ String requestDigest,
+ String sourceSnapshotDigest,
+ UUID tenantUuid,
+ Map membershipVersion,
+ String membershipAuthorityGeneration,
+ String eventStreamKey,
+ String eventRequestId,
+ long eventSequence,
+ String eventId,
+ String eventDigest,
+ byte[] eventPayload,
+ UUID auditEventId,
+ String auditEventType,
+ String auditOccurredAt,
+ String auditPayloadDigest,
+ byte[] auditPayload,
+ byte[] creatorEvidencePayload,
+ byte[] sourceSnapshotPayload) {
+ Objects.requireNonNull(tenantUuid, "result tenant UUID is required");
+ Objects.requireNonNull(membershipVersion, "result membership-version map is required");
+ String tenantKey = tenantUuid.toString();
+ if (membershipVersion.size() != 1 || !membershipVersion.containsKey(tenantKey)) {
+ throw new IllegalArgumentException(
+ "Creator-bootstrap result requires exactly its tenant membership-version entry");
+ }
+ String version = membershipVersion.get(tenantKey);
+ try {
+ if (version == null
+ || !Long.toString(Long.parseLong(version)).equals(version)
+ || Long.parseLong(version) <= 0L) {
+ throw new IllegalArgumentException("Creator-bootstrap membership version is invalid");
+ }
+ } catch (NumberFormatException failure) {
+ throw new IllegalArgumentException(
+ "Creator-bootstrap membership version is invalid", failure);
+ }
+ Map result = new LinkedHashMap<>();
+ result.put("schemaVersion", "account-tenant-creation-bootstrap-result/v1");
+ result.put("requestId", requestId);
+ result.put("requestDigest", requestDigest);
+ result.put("sourceSnapshotDigest", sourceSnapshotDigest);
+ result.put("membershipVersion", membershipVersion);
+ result.put("membershipAuthorityGeneration", membershipAuthorityGeneration);
+ result.put("eventStreamKey", eventStreamKey);
+ result.put("eventRequestId", eventRequestId);
+ result.put("eventSequence", Long.toString(eventSequence));
+ result.put("eventId", eventId);
+ result.put("eventDigest", eventDigest);
+ result.put("eventPayload", Base64.getEncoder().encodeToString(eventPayload));
+ result.put("auditEventId", auditEventId.toString());
+ result.put("auditEventType", auditEventType);
+ result.put("auditOccurredAt", auditOccurredAt);
+ result.put("auditPayloadDigest", auditPayloadDigest);
+ result.put("auditPayload", Base64.getEncoder().encodeToString(auditPayload));
+ result.put("creatorEvidence", Base64.getEncoder().encodeToString(creatorEvidencePayload));
+ result.put("sourceSnapshot", Base64.getEncoder().encodeToString(sourceSnapshotPayload));
+ return frameBytes(RESULT_DOMAIN.getBytes(StandardCharsets.UTF_8), canonicalJson(result));
+ }
+
+ public static String sha256(byte[] payload) {
+ Objects.requireNonNull(payload, "digest payload is required");
+ try {
+ return "sha256:"
+ + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("SHA-256 is unavailable", impossible);
+ }
+ }
+
+ public static byte[] authorityTuplePayload(AuthorityTuple tuple) {
+ return canonicalJson(authorityTupleMap(tuple));
+ }
+
+ public static Map authorityTupleMap(AuthorityTuple tuple) {
+ Objects.requireNonNull(tuple, "authority tuple is required");
+ Map result = new LinkedHashMap<>();
+ result.put("issuerAuthGeneration", tuple.issuerAuthGeneration());
+ result.put("accountAuthorityGeneration", tuple.accountAuthorityGeneration());
+ result.put("tenantAuthorityGeneration", tuple.tenantAuthorityGeneration());
+ result.put("membershipAuthorityGeneration", tuple.membershipAuthorityGeneration());
+ result.put(
+ "privateRealmGrantVersions",
+ tuple.privateRealmGrantVersions().stream()
+ .map(AccountTenantCreationBootstrapDigest::grantMap)
+ .toList());
+ tuple
+ .accountSecurityCutoff()
+ .ifPresent(cutoff -> result.put("accountSecurityCutoff", cutoffMap(cutoff)));
+ tuple
+ .tenantBillingCutoff()
+ .ifPresent(
+ cutoffs -> {
+ Map encodedCutoffs = new LinkedHashMap<>();
+ cutoffs.forEach(
+ (tenantId, cutoff) -> encodedCutoffs.put(tenantId, cutoffMap(cutoff)));
+ result.put("tenantBillingCutoff", encodedCutoffs);
+ });
+ return result;
+ }
+
+ private static Map creationEvidenceMap(FreshTenantCreationEvidence evidence) {
+ Map result = new LinkedHashMap<>();
+ result.put("schemaVersion", Integer.toString(evidence.schemaVersion()));
+ result.put("targetNamespace", evidence.targetNamespace());
+ result.put("creationRequestId", evidence.creationRequestId().toString());
+ result.put("operationId", evidence.operationId().toString());
+ result.put("requestDigest", evidence.requestDigest());
+ result.put("canonicalTenantId", evidence.canonicalTenantId().toString());
+ result.put("sourceGameRowId", Long.toString(evidence.sourceGameRowId()));
+ result.put("sourceGameTenantKey", evidence.sourceGameTenantKey());
+ result.put("provenanceKind", evidence.provenanceKind());
+ result.put("evidenceDigest", evidence.evidenceDigest());
+ return result;
+ }
+
+ private static Map grantMap(PrivateRealmGrantVersion grant) {
+ return Map.of(
+ "tenantId", grant.tenantId(),
+ "worldSlug", grant.worldSlug(),
+ "realmSlug", grant.realmSlug(),
+ "playtestLifecycleId", grant.playtestLifecycleId(),
+ "grantVersion", grant.grantVersion());
+ }
+
+ private static Map cutoffMap(AccountSecurityCutoff cutoff) {
+ return Map.of(
+ "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(),
+ "outboxStreamKey", cutoff.outboxStreamKey(),
+ "outboxSequence", cutoff.outboxSequence());
+ }
+
+ private static Map cutoffMap(TenantBillingCutoff cutoff) {
+ return Map.of(
+ "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(),
+ "tenantBillingSequence", cutoff.tenantBillingSequence(),
+ "outboxStreamKey", cutoff.outboxStreamKey(),
+ "outboxSequence", cutoff.outboxSequence());
+ }
+
+ private static byte[] canonicalJson(Object value) {
+ try {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(
+ tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value));
+ } catch (IOException | RuntimeException failure) {
+ throw new IllegalStateException(
+ "Creator-bootstrap canonical JSON serialization failed", failure);
+ }
+ }
+
+ private static byte[] frameBytes(byte[]... values) {
+ ByteArrayOutputStream framed = new ByteArrayOutputStream();
+ for (byte[] value : values) {
+ Objects.requireNonNull(value, "framed value is required");
+ framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array());
+ framed.writeBytes(value);
+ }
+ return framed.toByteArray();
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java
new file mode 100644
index 0000000000..5f04c59025
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java
@@ -0,0 +1,585 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Immutable Account owner request, source snapshot, and result receipt for creator bootstrap. */
+@Repository
+public class AccountTenantCreationBootstrapOperationRepository {
+ private static final String TABLE = "account_tenant_creation_bootstrap_operations";
+
+ private final DSLContext dsl;
+
+ @SuppressFBWarnings(
+ value = "CT_CONSTRUCTOR_THROW",
+ justification =
+ "Spring transaction proxy requires a non-final class; constructor only validates its internal collaborator and publishes no partial instance.")
+ public AccountTenantCreationBootstrapOperationRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl, "DSLContext is required");
+ }
+
+ /** Claims one source and baseline, or returns its exact immutable original result. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Claim claim(
+ FreshTenantCreatorEvidence evidence,
+ byte[] creatorEvidencePayload,
+ byte[] sourceSnapshotPayload,
+ String sourceSnapshotDigest,
+ byte[] requestPayload,
+ String requestDigest,
+ long baselineMembershipVersion,
+ long baselineMembershipAuthorityGeneration) {
+ requireWriteTransaction();
+ Objects.requireNonNull(evidence, "creator evidence is required");
+ requireBytes(creatorEvidencePayload, "creator evidence payload");
+ requireBytes(sourceSnapshotPayload, "Account source snapshot payload");
+ requireBytes(requestPayload, "creator-bootstrap request payload");
+ requireDigest(sourceSnapshotDigest, "source snapshot digest");
+ requireDigest(requestDigest, "request digest");
+ if (baselineMembershipVersion <= 0L || baselineMembershipAuthorityGeneration <= 0L) {
+ throw new IllegalArgumentException("Creator-bootstrap baseline counters must be positive");
+ }
+ var creation = evidence.creationEvidence();
+ UUID requestId = evidence.accountAuthorizationOperationId();
+ int inserted =
+ dsl.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (request_id, schema_version, initiating_account_uuid, tenant_uuid, "
+ + "creation_request_id, creation_operation_id, account_authorization_operation_id, "
+ + "account_authorization_digest, creator_evidence_digest, creator_evidence_payload, "
+ + "source_snapshot_payload, source_snapshot_digest, request_payload, request_digest, "
+ + "baseline_membership_version, baseline_membership_authority_generation, "
+ + "baseline_event_sequence, status) "
+ + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'IN_PROGRESS') "
+ + "ON CONFLICT DO NOTHING",
+ requestId,
+ evidence.initiatingAccountId(),
+ creation.canonicalTenantId(),
+ creation.creationRequestId(),
+ creation.operationId(),
+ evidence.accountAuthorizationOperationId(),
+ evidence.accountAuthorizationDigest(),
+ evidence.evidenceDigest(),
+ creatorEvidencePayload,
+ sourceSnapshotPayload,
+ sourceSnapshotDigest,
+ requestPayload,
+ requestDigest,
+ baselineMembershipVersion,
+ baselineMembershipAuthorityGeneration);
+ if (inserted == 1) {
+ StoredOperation stored =
+ findForUpdate(requestId)
+ .orElseThrow(
+ () -> new IllegalStateException("Claimed creator-bootstrap operation is absent"));
+ requireSameInput(
+ stored,
+ evidence,
+ creatorEvidencePayload,
+ sourceSnapshotPayload,
+ sourceSnapshotDigest,
+ requestPayload,
+ requestDigest,
+ baselineMembershipVersion,
+ baselineMembershipAuthorityGeneration);
+ if (!"IN_PROGRESS".equals(stored.status())) {
+ throw new IllegalStateException("New creator-bootstrap claim is not in progress");
+ }
+ return new Claim(true, stored);
+ }
+ if (inserted != 0) {
+ throw new IllegalStateException("Creator-bootstrap operation claim was ambiguous");
+ }
+
+ Optional sameRequest = findForUpdate(requestId);
+ if (sameRequest.isPresent()) {
+ StoredOperation stored = sameRequest.orElseThrow();
+ requireSameInput(
+ stored,
+ evidence,
+ creatorEvidencePayload,
+ sourceSnapshotPayload,
+ sourceSnapshotDigest,
+ requestPayload,
+ requestDigest,
+ baselineMembershipVersion,
+ baselineMembershipAuthorityGeneration);
+ if (!"COMMITTED".equals(stored.status())) {
+ throw new IllegalStateException(
+ "Incomplete creator-bootstrap operation cannot be replayed");
+ }
+ return new Claim(false, stored);
+ }
+
+ Optional tenantOperation = findRequestIdByTenantForUpdate(creation.canonicalTenantId());
+ if (tenantOperation.isPresent()) {
+ throw new OperationConflictException(
+ "Fresh tenant already has a different immutable creator-bootstrap operation");
+ }
+ throw new IllegalStateException("Conflicting creator-bootstrap operation claim disappeared");
+ }
+
+ /** Returns one request under its row lock for exact retry verification. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findForUpdate(UUID requestId) {
+ requireWriteTransaction();
+ Objects.requireNonNull(requestId, "creator-bootstrap request ID is required");
+ Record row =
+ dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", requestId);
+ return row == null ? Optional.empty() : Optional.of(toStoredOperation(row));
+ }
+
+ /** Locks the tenant's unique original creator operation when a request ID differs. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findRequestIdByTenantForUpdate(UUID tenantUuid) {
+ requireWriteTransaction();
+ Objects.requireNonNull(tenantUuid, "tenant UUID is required");
+ Record row =
+ dsl.fetchOne(
+ "SELECT request_id FROM " + TABLE + " WHERE tenant_uuid = ? FOR UPDATE", tenantUuid);
+ return row == null ? Optional.empty() : Optional.of(row.get("request_id", UUID.class));
+ }
+
+ /**
+ * Requires no older Account membership receipt or operation history for this exact UUID pair. The
+ * caller already holds the initiator Account row fence and the Account authority snapshot.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public void assertNoContradictoryMembershipHistory(UUID accountUuid, UUID tenantUuid) {
+ requireWriteTransaction();
+ boolean receiptHead =
+ exists(
+ "SELECT EXISTS (SELECT 1 FROM account_membership_transition_receipt_stream_heads "
+ + "WHERE account_uuid = ? AND tenant_uuid = ?)",
+ accountUuid,
+ tenantUuid);
+ boolean priorJoinOperation =
+ exists(
+ "SELECT EXISTS (SELECT 1 FROM account_join_operations "
+ + "WHERE account_uuid = ? AND tenant_uuid = ?)",
+ accountUuid,
+ tenantUuid);
+ boolean priorRoleOperation =
+ exists(
+ "SELECT EXISTS (SELECT 1 FROM account_tenant_role_operation_members "
+ + "WHERE account_uuid = ? AND tenant_uuid = ?)",
+ accountUuid,
+ tenantUuid);
+ if (receiptHead || priorJoinOperation || priorRoleOperation) {
+ throw new IllegalStateException(
+ "Fresh creator membership pair has contradictory retained Account history");
+ }
+ }
+
+ /** Completes the exact claim with the membership event, audit, and immutable result receipt. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public StoredOperation complete(UUID requestId, Completion completion) {
+ requireWriteTransaction();
+ Objects.requireNonNull(requestId, "creator-bootstrap request ID is required");
+ Objects.requireNonNull(completion, "creator-bootstrap completion is required");
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET membership_id = ?, membership_version = ?, "
+ + "membership_authority_generation = ?, membership_lifecycle_state = ?, "
+ + "gameplay_admission_allowed = ?, membership_roles_payload = ?, "
+ + "event_stream_key = ?, event_request_id = ?, event_sequence = ?, event_id = ?, "
+ + "event_digest = ?, caller_bound_authority_invalidated = ?, event_payload = ?, "
+ + "audit_event_id = ?, audit_event_type = ?, audit_occurred_at = CAST(? AS TIMESTAMPTZ), "
+ + "audit_payload_digest = ?, audit_payload = ?, result_payload = ?, result_digest = ?, "
+ + "status = 'COMMITTED' WHERE request_id = ? AND status = 'IN_PROGRESS'",
+ completion.membershipId(),
+ completion.membershipVersion(),
+ completion.membershipAuthorityGeneration(),
+ completion.membershipLifecycleState(),
+ completion.gameplayAdmissionAllowed(),
+ completion.membershipRolesPayload(),
+ completion.eventStreamKey(),
+ completion.eventRequestId(),
+ completion.eventSequence(),
+ completion.eventId(),
+ completion.eventDigest(),
+ completion.callerBoundAuthorityInvalidated(),
+ completion.eventPayload(),
+ completion.auditEventId(),
+ completion.auditEventType(),
+ OffsetDateTime.ofInstant(completion.auditOccurredAt(), ZoneOffset.UTC).toString(),
+ completion.auditPayloadDigest(),
+ completion.auditPayload(),
+ completion.resultPayload(),
+ completion.resultDigest(),
+ requestId);
+ if (updated != 1) {
+ throw new IllegalStateException("Creator-bootstrap operation was not completed exactly once");
+ }
+ StoredOperation stored =
+ findForUpdate(requestId)
+ .orElseThrow(
+ () -> new IllegalStateException("Completed creator-bootstrap receipt is absent"));
+ if (!"COMMITTED".equals(stored.status())
+ || stored.membershipId() != completion.membershipId()
+ || stored.membershipVersion() != completion.membershipVersion()
+ || stored.membershipAuthorityGeneration() != completion.membershipAuthorityGeneration()
+ || !completion.membershipLifecycleState().equals(stored.membershipLifecycleState())
+ || !Boolean.valueOf(completion.gameplayAdmissionAllowed())
+ .equals(stored.gameplayAdmissionAllowed())
+ || !Arrays.equals(stored.membershipRolesPayload(), completion.membershipRolesPayload())
+ || !stored.eventStreamKey().equals(completion.eventStreamKey())
+ || !stored.eventRequestId().equals(completion.eventRequestId())
+ || stored.eventSequence() != completion.eventSequence()
+ || !stored.eventId().equals(completion.eventId())
+ || !stored.eventDigest().equals(completion.eventDigest())
+ || !Arrays.equals(stored.eventPayload(), completion.eventPayload())
+ || !stored.auditEventId().equals(completion.auditEventId())
+ || !stored.auditEventType().equals(completion.auditEventType())
+ || !stored.auditOccurredAt().equals(completion.auditOccurredAt())
+ || !stored.auditPayloadDigest().equals(completion.auditPayloadDigest())
+ || !Arrays.equals(stored.auditPayload(), completion.auditPayload())
+ || !Arrays.equals(stored.resultPayload(), completion.resultPayload())
+ || !stored.resultDigest().equals(completion.resultDigest())) {
+ throw new IllegalStateException("Creator-bootstrap committed receipt readback differs");
+ }
+ return stored;
+ }
+
+ private boolean exists(String query, Object... bindings) {
+ Record result = dsl.fetchOne(query, bindings);
+ return result != null && Boolean.TRUE.equals(result.get(0, Boolean.class));
+ }
+
+ private static void requireSameInput(
+ StoredOperation stored,
+ FreshTenantCreatorEvidence evidence,
+ byte[] creatorEvidencePayload,
+ byte[] sourceSnapshotPayload,
+ String sourceSnapshotDigest,
+ byte[] requestPayload,
+ String requestDigest,
+ long baselineMembershipVersion,
+ long baselineMembershipAuthorityGeneration) {
+ var creation = evidence.creationEvidence();
+ if (!stored.requestId().equals(evidence.accountAuthorizationOperationId())
+ || !stored.initiatingAccountUuid().equals(evidence.initiatingAccountId())
+ || !stored.tenantUuid().equals(creation.canonicalTenantId())
+ || !stored.creationRequestId().equals(creation.creationRequestId())
+ || !stored.creationOperationId().equals(creation.operationId())
+ || !stored
+ .accountAuthorizationOperationId()
+ .equals(evidence.accountAuthorizationOperationId())
+ || !stored.accountAuthorizationDigest().equals(evidence.accountAuthorizationDigest())
+ || !stored.creatorEvidenceDigest().equals(evidence.evidenceDigest())
+ || !Arrays.equals(stored.creatorEvidencePayload(), creatorEvidencePayload)
+ || !Arrays.equals(stored.sourceSnapshotPayload(), sourceSnapshotPayload)
+ || !stored.sourceSnapshotDigest().equals(sourceSnapshotDigest)
+ || !Arrays.equals(stored.requestPayload(), requestPayload)
+ || !stored.requestDigest().equals(requestDigest)
+ || stored.baselineMembershipVersion() != baselineMembershipVersion
+ || stored.baselineMembershipAuthorityGeneration() != baselineMembershipAuthorityGeneration
+ || stored.baselineEventSequence() != 0L) {
+ throw new OperationConflictException(
+ "Creator-bootstrap operation ID was reused with changed source or Account snapshot");
+ }
+ }
+
+ private static StoredOperation toStoredOperation(Record row) {
+ return new StoredOperation(
+ required(row.get("request_id", UUID.class), "request ID"),
+ required(row.get("initiating_account_uuid", UUID.class), "initiating Account UUID"),
+ required(row.get("tenant_uuid", UUID.class), "tenant UUID"),
+ required(row.get("creation_request_id", UUID.class), "creation request ID"),
+ required(row.get("creation_operation_id", UUID.class), "creation operation ID"),
+ required(
+ row.get("account_authorization_operation_id", UUID.class),
+ "Account authorization operation ID"),
+ required(
+ row.get("account_authorization_digest", String.class), "Account authorization digest"),
+ required(row.get("creator_evidence_digest", String.class), "creator evidence digest"),
+ required(row.get("creator_evidence_payload", byte[].class), "creator evidence payload"),
+ required(row.get("source_snapshot_payload", byte[].class), "source snapshot payload"),
+ required(row.get("source_snapshot_digest", String.class), "source snapshot digest"),
+ required(row.get("request_payload", byte[].class), "request payload"),
+ required(row.get("request_digest", String.class), "request digest"),
+ required(row.get("baseline_membership_version", Long.class), "baseline membership version"),
+ required(
+ row.get("baseline_membership_authority_generation", Long.class),
+ "baseline membership authority generation"),
+ required(row.get("baseline_event_sequence", Long.class), "baseline event sequence"),
+ required(row.get("status", String.class), "operation status"),
+ row.get("membership_id", Long.class),
+ row.get("membership_version", Long.class),
+ row.get("membership_authority_generation", Long.class),
+ row.get("membership_lifecycle_state", String.class),
+ row.get("gameplay_admission_allowed", Boolean.class),
+ row.get("membership_roles_payload", byte[].class),
+ row.get("event_stream_key", String.class),
+ row.get("event_request_id", String.class),
+ row.get("event_sequence", Long.class),
+ row.get("event_id", String.class),
+ row.get("event_digest", String.class),
+ row.get("caller_bound_authority_invalidated", Boolean.class),
+ row.get("event_payload", byte[].class),
+ row.get("audit_event_id", UUID.class),
+ row.get("audit_event_type", String.class),
+ toInstant(row.get("audit_occurred_at", OffsetDateTime.class)),
+ row.get("audit_payload_digest", String.class),
+ row.get("audit_payload", byte[].class),
+ row.get("result_payload", byte[].class),
+ row.get("result_digest", String.class),
+ toInstant(row.get("committed_at", OffsetDateTime.class)));
+ }
+
+ private static T required(T value, String label) {
+ if (value == null) {
+ throw new IllegalStateException("Creator-bootstrap stored " + label + " is absent");
+ }
+ return value;
+ }
+
+ private static Instant toInstant(OffsetDateTime value) {
+ return value == null ? null : value.toInstant();
+ }
+
+ private static void requireBytes(byte[] value, String label) {
+ if (value == null || value.length == 0) {
+ throw new IllegalArgumentException("Creator-bootstrap " + label + " is required");
+ }
+ }
+
+ private static void requireDigest(String value, String label) {
+ if (value == null || !value.matches("sha256:[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Creator-bootstrap " + label + " is malformed");
+ }
+ }
+
+ private static void requireWriteTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException(
+ "Creator-bootstrap owner operation requires a write transaction");
+ }
+ }
+
+ public record Claim(boolean claimed, StoredOperation operation) {
+ public Claim {
+ Objects.requireNonNull(operation, "claimed creator-bootstrap operation is required");
+ }
+ }
+
+ public record Completion(
+ long membershipId,
+ long membershipVersion,
+ long membershipAuthorityGeneration,
+ String membershipLifecycleState,
+ boolean gameplayAdmissionAllowed,
+ byte[] membershipRolesPayload,
+ String eventStreamKey,
+ String eventRequestId,
+ long eventSequence,
+ String eventId,
+ String eventDigest,
+ boolean callerBoundAuthorityInvalidated,
+ byte[] eventPayload,
+ UUID auditEventId,
+ String auditEventType,
+ Instant auditOccurredAt,
+ String auditPayloadDigest,
+ byte[] auditPayload,
+ byte[] resultPayload,
+ String resultDigest) {
+ public Completion {
+ if (membershipId <= 0L
+ || membershipVersion <= 0L
+ || membershipAuthorityGeneration <= 0L
+ || membershipLifecycleState == null
+ || membershipRolesPayload == null
+ || eventStreamKey == null
+ || eventRequestId == null
+ || eventSequence <= 0L
+ || eventId == null
+ || eventDigest == null
+ || eventPayload == null
+ || auditEventId == null
+ || auditEventType == null
+ || auditOccurredAt == null
+ || auditPayloadDigest == null
+ || auditPayload == null
+ || resultPayload == null
+ || resultDigest == null) {
+ throw new IllegalArgumentException("Creator-bootstrap completion evidence is incomplete");
+ }
+ membershipRolesPayload = membershipRolesPayload.clone();
+ eventPayload = eventPayload.clone();
+ auditPayload = auditPayload.clone();
+ resultPayload = resultPayload.clone();
+ }
+
+ @Override
+ public byte[] membershipRolesPayload() {
+ return membershipRolesPayload.clone();
+ }
+
+ @Override
+ public byte[] eventPayload() {
+ return eventPayload.clone();
+ }
+
+ @Override
+ public byte[] auditPayload() {
+ return auditPayload.clone();
+ }
+
+ @Override
+ public byte[] resultPayload() {
+ return resultPayload.clone();
+ }
+ }
+
+ public record StoredOperation(
+ UUID requestId,
+ UUID initiatingAccountUuid,
+ UUID tenantUuid,
+ UUID creationRequestId,
+ UUID creationOperationId,
+ UUID accountAuthorizationOperationId,
+ String accountAuthorizationDigest,
+ String creatorEvidenceDigest,
+ byte[] creatorEvidencePayload,
+ byte[] sourceSnapshotPayload,
+ String sourceSnapshotDigest,
+ byte[] requestPayload,
+ String requestDigest,
+ long baselineMembershipVersion,
+ long baselineMembershipAuthorityGeneration,
+ long baselineEventSequence,
+ String status,
+ Long membershipId,
+ Long membershipVersion,
+ Long membershipAuthorityGeneration,
+ String membershipLifecycleState,
+ Boolean gameplayAdmissionAllowed,
+ byte[] membershipRolesPayload,
+ String eventStreamKey,
+ String eventRequestId,
+ Long eventSequence,
+ String eventId,
+ String eventDigest,
+ Boolean callerBoundAuthorityInvalidated,
+ byte[] eventPayload,
+ UUID auditEventId,
+ String auditEventType,
+ Instant auditOccurredAt,
+ String auditPayloadDigest,
+ byte[] auditPayload,
+ byte[] resultPayload,
+ String resultDigest,
+ Instant committedAt) {
+ public StoredOperation {
+ creatorEvidencePayload = cloneBytes(creatorEvidencePayload);
+ sourceSnapshotPayload = cloneBytes(sourceSnapshotPayload);
+ requestPayload = cloneBytes(requestPayload);
+ membershipRolesPayload = cloneBytes(membershipRolesPayload);
+ eventPayload = cloneBytes(eventPayload);
+ auditPayload = cloneBytes(auditPayload);
+ resultPayload = cloneBytes(resultPayload);
+ }
+
+ @Override
+ public byte[] creatorEvidencePayload() {
+ return cloneBytes(creatorEvidencePayload);
+ }
+
+ @Override
+ public byte[] sourceSnapshotPayload() {
+ return cloneBytes(sourceSnapshotPayload);
+ }
+
+ @Override
+ public byte[] requestPayload() {
+ return cloneBytes(requestPayload);
+ }
+
+ @Override
+ public byte[] membershipRolesPayload() {
+ return cloneBytes(membershipRolesPayload);
+ }
+
+ @Override
+ public byte[] eventPayload() {
+ return cloneBytes(eventPayload);
+ }
+
+ @Override
+ public byte[] auditPayload() {
+ return cloneBytes(auditPayload);
+ }
+
+ @Override
+ public byte[] resultPayload() {
+ return cloneBytes(resultPayload);
+ }
+
+ public AccountTenantCreationBootstrapResult result() {
+ if (!"COMMITTED".equals(status)
+ || membershipVersion == null
+ || membershipAuthorityGeneration == null
+ || eventSequence == null
+ || eventStreamKey == null
+ || eventRequestId == null
+ || eventId == null
+ || eventDigest == null
+ || auditEventId == null
+ || auditEventType == null
+ || auditPayloadDigest == null
+ || resultDigest == null) {
+ throw new IllegalStateException("Incomplete creator-bootstrap result is not replayable");
+ }
+ return new AccountTenantCreationBootstrapResult(
+ requestId,
+ requestDigest,
+ initiatingAccountUuid,
+ tenantUuid,
+ creatorEvidenceDigest,
+ sourceSnapshotDigest,
+ java.util.Map.of(tenantUuid.toString(), Long.toString(membershipVersion)),
+ Long.toString(membershipAuthorityGeneration),
+ List.of("tenantAdmin"),
+ false,
+ eventStreamKey,
+ eventRequestId,
+ eventSequence,
+ eventId,
+ eventDigest,
+ auditEventId,
+ auditEventType,
+ auditPayloadDigest,
+ resultDigest);
+ }
+
+ private static byte[] cloneBytes(byte[] bytes) {
+ return bytes == null ? null : bytes.clone();
+ }
+ }
+
+ public static final class OperationConflictException extends IllegalStateException {
+ public OperationConflictException(String message) {
+ super(message);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalog.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalog.java
index fdeb9b68a2..ea01bf1323 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalog.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalog.java
@@ -390,7 +390,7 @@ private static void validateActualClaimPresence(
private static void validateActualClaimMaps(ProfileShape shape, ActualClaimMaps actualClaims) {
Map membershipVersion =
actualClaims.membershipVersion().orElseThrow(AccountTokenProfileCatalog::invalidCandidate);
- Set membershipVersionKeys = requirePositiveTenantCounterMap(membershipVersion);
+ Set membershipVersionKeys = requireNonNegativeTenantCounterMap(membershipVersion);
if (!membershipVersionKeys.equals(
canonicalTenantKeys(shape.authority().membershipVersionKeys()))) {
throw invalidCandidate();
@@ -407,13 +407,13 @@ private static void validateActualClaimMaps(ProfileShape shape, ActualClaimMaps
}
}
- private static Set requirePositiveTenantCounterMap(Map values) {
+ private static Set requireNonNegativeTenantCounterMap(Map values) {
Set keys = new HashSet<>();
for (Map.Entry entry : values.entrySet()) {
String key = entry.getKey();
BigInteger value = entry.getValue();
requireCanonicalTenantKey(key);
- if (value == null || value.signum() <= 0) {
+ if (value == null || value.signum() < 0) {
throw invalidCandidate();
}
keys.add(key);
@@ -987,7 +987,8 @@ public record ClaimFieldPresence(
}
/**
- * Actual separate JWT map claims, preserving omission and arbitrary-precision counters.
+ * Actual separate JWT map claims, preserving omission and arbitrary-precision non-negative
+ * membership-version counters.
*
* The optionals preserve claim absence separately from an empty object. Maps and nested role
* lists are copied defensively.
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java
new file mode 100644
index 0000000000..43ad8d45e4
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java
@@ -0,0 +1,20 @@
+package net.firedevops.firemud.accountservice.service;
+
+import java.util.function.Supplier;
+import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+
+/**
+ * Account-owned authorization/source participant required for a new creator bootstrap commit.
+ *
+ *
The implementation must authenticate the initiating Account and exact source operation, verify
+ * the current Account authorization named by the creator evidence, and hold or participate in that
+ * source's commit fence until {@code mutationWhileCurrent} returns and the enclosing Account
+ * transaction commits. The immutable DTO alone is never authorization. No production implementation
+ * is registered by this storage slice, so new creator bootstrap attempts are default-denied.
+ */
+public interface AccountTenantCreationBootstrapAuthorizationSource {
+ AccountTenantCreationBootstrapResult withCurrentAuthorizationAndSourceParticipation(
+ FreshTenantCreatorEvidence evidence,
+ Supplier mutationWhileCurrent);
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java
new file mode 100644
index 0000000000..1fd4e7a3a9
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java
@@ -0,0 +1,755 @@
+package net.firedevops.firemud.accountservice.service;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope;
+import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity;
+import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountTenantMembership;
+import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Claim;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Account-owned atomic membership bootstrap for an exact fresh tenant creator operation.
+ *
+ * This service is intentionally not exposed by REST or gRPC. A new commit requires a separately
+ * registered current Account authorization/source participant; no such production participant is
+ * registered by this slice, so new bootstrap attempts remain default-denied.
+ */
+@Service
+@SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "Injected Account repositories and source participants are internal collaborators.")
+public class AccountTenantCreationBootstrapService {
+ public static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED";
+ private static final String ROLE_SNAPSHOT_JSON = "[\"tenantAdmin\"]";
+ private static final JsonMapper JSON = JsonMapper.builder().build();
+
+ private final AccountRepository accountRepository;
+ private final FreshTenantIdentityAssociationRepository tenantAssociationRepository;
+ private final AccountMembershipAuthorityEventProducer eventProducer;
+ private final AccountMembershipPairAuthorityRepository pairAuthorityRepository;
+ private final AccountTenantMembershipRepository membershipRepository;
+ private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository;
+ private final AccountAuthorityOutboxRepository authorityOutboxRepository;
+ private final AccountAuditOutboxRepository auditOutboxRepository;
+ private final AccountTenantCreationBootstrapOperationRepository operationRepository;
+ private final ObjectProvider
+ authorizationSourceProvider;
+
+ @SuppressFBWarnings(
+ value = "CT_CONSTRUCTOR_THROW",
+ justification =
+ "Spring transaction proxy requires a non-final class; constructor only validates its internal collaborators and publishes no partial instance.")
+ public AccountTenantCreationBootstrapService(
+ AccountRepository accountRepository,
+ FreshTenantIdentityAssociationRepository tenantAssociationRepository,
+ AccountMembershipAuthorityEventProducer eventProducer,
+ AccountMembershipPairAuthorityRepository pairAuthorityRepository,
+ AccountTenantMembershipRepository membershipRepository,
+ AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository,
+ AccountAuthorityOutboxRepository authorityOutboxRepository,
+ AccountAuditOutboxRepository auditOutboxRepository,
+ AccountTenantCreationBootstrapOperationRepository operationRepository,
+ ObjectProvider
+ authorizationSourceProvider) {
+ this.accountRepository = Objects.requireNonNull(accountRepository);
+ this.tenantAssociationRepository = Objects.requireNonNull(tenantAssociationRepository);
+ this.eventProducer = Objects.requireNonNull(eventProducer);
+ this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository);
+ this.membershipRepository = Objects.requireNonNull(membershipRepository);
+ this.roleSnapshotRepository = Objects.requireNonNull(roleSnapshotRepository);
+ this.authorityOutboxRepository = Objects.requireNonNull(authorityOutboxRepository);
+ this.auditOutboxRepository = Objects.requireNonNull(auditOutboxRepository);
+ this.operationRepository = Objects.requireNonNull(operationRepository);
+ this.authorizationSourceProvider = Objects.requireNonNull(authorizationSourceProvider);
+ }
+
+ /**
+ * Replays only an exact committed historical result, or runs a new commit under a current-source
+ * participant. The creator evidence value itself is data and does not authorize this method.
+ */
+ @Transactional
+ public AccountTenantCreationBootstrapResult bootstrap(FreshTenantCreatorEvidence evidence) {
+ requireWritableOwnerTransaction();
+ Objects.requireNonNull(evidence, "Authenticated creator evidence is required");
+ UUID creatorUuid = evidence.initiatingAccountId();
+ UUID tenantUuid = evidence.creationEvidence().canonicalTenantId();
+ Account creator =
+ accountRepository
+ .findByAccountUuidForUpdate(creatorUuid)
+ .orElseThrow(() -> new IllegalStateException("Creator Account row is absent"));
+ requireAccountIdentity(creator, creatorUuid);
+
+ UUID requestId = evidence.accountAuthorizationOperationId();
+ Optional original = operationRepository.findForUpdate(requestId);
+ if (original.isPresent()) {
+ return replayExactOriginal(evidence, original.orElseThrow());
+ }
+ Optional tenantOperation = operationRepository.findRequestIdByTenantForUpdate(tenantUuid);
+ if (tenantOperation.isPresent()) {
+ throw new AccountTenantCreationBootstrapOperationRepository.OperationConflictException(
+ "Fresh tenant already has a different immutable creator-bootstrap operation");
+ }
+
+ AccountTenantCreationBootstrapAuthorizationSource currentSource =
+ authorizationSourceProvider.getIfAvailable();
+ if (currentSource == null) {
+ throw new IllegalStateException(
+ "No current Account creator-authorization/source participant is registered");
+ }
+ AtomicBoolean callbackRan = new AtomicBoolean();
+ AtomicReference committed = new AtomicReference<>();
+ AccountTenantCreationBootstrapResult returned =
+ currentSource.withCurrentAuthorizationAndSourceParticipation(
+ evidence,
+ () -> {
+ if (!callbackRan.compareAndSet(false, true)) {
+ throw new IllegalStateException(
+ "Account creator authorization/source participant repeated its commit callback");
+ }
+ AccountTenantCreationBootstrapResult result = commitNew(evidence, creator);
+ committed.set(result);
+ return result;
+ });
+ if (!callbackRan.get() || returned == null || !returned.equals(committed.get())) {
+ throw new IllegalStateException(
+ "Account creator authorization/source participant did not preserve the owner result");
+ }
+ return returned;
+ }
+
+ private AccountTenantCreationBootstrapResult commitNew(
+ FreshTenantCreatorEvidence evidence, Account creator) {
+ requireWritableOwnerTransaction();
+ UUID creatorUuid = evidence.initiatingAccountId();
+ UUID tenantUuid = evidence.creationEvidence().canonicalTenantId();
+ FreshTenantCreationEvidence associated =
+ tenantAssociationRepository
+ .read(tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Fresh Game Design tenant source is absent"));
+ if (!associated.equals(evidence.creationEvidence())) {
+ throw new IllegalStateException(
+ "Fresh Game Design tenant source differs from creator qualification evidence");
+ }
+
+ AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline =
+ eventProducer.readFreshNeverJoinedMembershipSnapshot(creatorUuid, tenantUuid);
+ if (!creatorUuid.toString().equals(baseline.accountId())
+ || !tenantUuid.toString().equals(baseline.tenantId())
+ || baseline.membershipExists()
+ || !"MISSING".equals(baseline.membershipLifecycleState())
+ || baseline.gameplayAdmissionAllowed()
+ || !List.of(
+ new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry(
+ baseline.outboxStreamKey(), "0"))
+ .equals(
+ baseline.outboxCheckpoints().stream()
+ .filter(
+ checkpoint ->
+ checkpoint.outboxStreamKey().equals(baseline.outboxStreamKey()))
+ .toList())) {
+ throw new IllegalStateException(
+ "Creator bootstrap baseline is not exact sequence-zero absence");
+ }
+
+ operationRepository.assertNoContradictoryMembershipHistory(creatorUuid, tenantUuid);
+ VerifiedTenantProvenance provenance = freshProvenance(associated);
+ PairAuthority priorPair =
+ pairAuthorityRepository
+ .readForUpdate(creatorUuid, tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Positive creator membership baseline is absent"));
+ long baselineVersion =
+ positiveLong(baseline.membershipVersion().get(tenantUuid.toString()), "membership version");
+ long baselineGeneration =
+ positiveLong(baseline.membershipAuthorityGeneration(), "membership authority generation");
+ if (!priorPair.accountUuid().equals(creatorUuid)
+ || !priorPair.tenantUuid().equals(tenantUuid)
+ || !priorPair.provenance().equals(provenance)
+ || priorPair.membershipExists()
+ || priorPair.membershipVersion() != baselineVersion
+ || priorPair.membershipAuthorityGeneration() != baselineGeneration
+ || priorPair.lastEventSequence() != 0L
+ || priorPair.lastEventId() != null
+ || priorPair.lastEventDigest() != null
+ || priorPair.lastTransitionInvalidated()) {
+ throw new IllegalStateException("Creator pair differs from its same-fence positive baseline");
+ }
+
+ byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence);
+ byte[] sourcePayload = AccountTenantCreationBootstrapDigest.sourceSnapshotPayload(baseline);
+ String sourceDigest = AccountTenantCreationBootstrapDigest.sha256(sourcePayload);
+ byte[] requestPayload =
+ AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload);
+ String requestDigest = AccountTenantCreationBootstrapDigest.sha256(requestPayload);
+ Claim claim =
+ operationRepository.claim(
+ evidence,
+ creatorPayload,
+ sourcePayload,
+ sourceDigest,
+ requestPayload,
+ requestDigest,
+ baselineVersion,
+ baselineGeneration);
+ if (!claim.claimed()) {
+ return replayExactOriginal(evidence, claim.operation());
+ }
+
+ long newVersion = increment(baselineVersion, "membership version");
+ AccountTenantMembership membership = new AccountTenantMembership();
+ membership.setAccount(creator);
+ membership.setTenantId(null);
+ membership.setTenantUuid(tenantUuid);
+ membership.setTenantProvenanceKind(TenantProvenanceKind.FRESH_GAME_DESIGN.name());
+ membership.setTenantSourceOperationId(associated.operationId());
+ membership.setTenantProvenanceDigest(associated.evidenceDigest());
+ membership.setGameplayAdmissionAllowed(false);
+ membership.setLifecycleState("ACTIVE");
+ membership.setMembershipVersion(newVersion);
+ membership.setMembershipAuthorityGeneration(baselineGeneration);
+ membership.setAuthorityProvenance("TENANT_CREATION");
+ AccountTenantMembership persisted =
+ membershipRepository.saveCanonical(membership, creatorUuid, tenantUuid, provenance);
+ RoleSnapshot roles =
+ roleSnapshotRepository.replaceCanonical(
+ persisted, creatorUuid, tenantUuid, provenance, newVersion, List.of("tenantAdmin"));
+ if (!roles.roles().equals(List.of("tenantAdmin"))) {
+ throw new IllegalStateException("Creator membership role readback is not tenantAdmin-only");
+ }
+
+ String requestId = evidence.accountAuthorizationOperationId().toString();
+ String streamKey =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + creatorUuid
+ + "/"
+ + tenantUuid;
+ if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) {
+ throw new IllegalStateException(
+ "Creator membership stream acquired history before bootstrap");
+ }
+ String eventId =
+ UUID.nameUUIDFromBytes(
+ (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId)
+ .getBytes(StandardCharsets.UTF_8))
+ .toString();
+ MembershipEvent[] candidate = new MembershipEvent[1];
+ Event event =
+ authorityOutboxRepository.append(
+ streamKey,
+ requestId,
+ sequence -> {
+ if (sequence != 1L) {
+ throw new IllegalStateException(
+ "First creator membership event must use sequence one");
+ }
+ MembershipEvent sealed =
+ MembershipAuthorityEventV1Codec.seal(
+ eventPreimage(
+ baseline,
+ creatorUuid,
+ tenantUuid,
+ newVersion,
+ baselineGeneration,
+ streamKey,
+ requestId,
+ eventId));
+ candidate[0] = sealed;
+ return new EventEvidence(
+ sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8());
+ });
+ MembershipEvent expectedEvent = candidate[0];
+ Event eventReadback =
+ authorityOutboxRepository
+ .findEvent(streamKey, requestId)
+ .orElseThrow(
+ () -> new IllegalStateException("Creator membership event readback is absent"));
+ Checkpoint checkpoint =
+ authorityOutboxRepository
+ .readCheckpoint(streamKey)
+ .orElseThrow(
+ () -> new IllegalStateException("Creator membership checkpoint is absent"));
+ MembershipEvent verifiedEvent =
+ MembershipAuthorityEventV1Codec.verify(
+ new String(eventReadback.payload(), StandardCharsets.UTF_8));
+ if (expectedEvent == null
+ || !event.equals(eventReadback)
+ || !checkpoint.outboxStreamKey().equals(streamKey)
+ || checkpoint.outboxSequence() != 1L
+ || !checkpoint.sourceEventId().equals(event.eventId())
+ || !checkpoint.sourceEventDigest().equals(event.eventDigest())
+ || !verifiedEvent.equals(expectedEvent)
+ || !verifiedEvent.roles().equals(List.of("tenantAdmin"))
+ || verifiedEvent.gameplayAdmissionAllowed()
+ || verifiedEvent.callerBoundAuthorityInvalidated()
+ || !Long.toString(newVersion)
+ .equals(verifiedEvent.membershipVersion().get(tenantUuid.toString()))) {
+ throw new IllegalStateException("Creator membership event or checkpoint readback differs");
+ }
+
+ PairAuthority advanced =
+ pairAuthorityRepository.commitTransition(
+ priorPair, new PairTransition(true, 1L, event.eventId(), event.eventDigest(), false));
+ if (!advanced.membershipExists()
+ || advanced.membershipVersion() != newVersion
+ || advanced.membershipAuthorityGeneration() != baselineGeneration
+ || advanced.lastEventSequence() != 1L
+ || !event.eventId().equals(advanced.lastEventId())
+ || !event.eventDigest().equals(advanced.lastEventDigest())
+ || advanced.lastTransitionInvalidated()) {
+ throw new IllegalStateException("Creator membership pair transition readback differs");
+ }
+
+ byte[] rolesPayload = ROLE_SNAPSHOT_JSON.getBytes(StandardCharsets.UTF_8);
+ UUID auditEventId =
+ UUID.nameUUIDFromBytes(
+ ("account-tenant-creation-bootstrap-audit/v1:" + requestId)
+ .getBytes(StandardCharsets.UTF_8));
+ byte[] auditPayload =
+ auditPayload(
+ evidence,
+ requestDigest,
+ sourceDigest,
+ newVersion,
+ baselineGeneration,
+ event,
+ checkpoint);
+ String auditText = new String(auditPayload, StandardCharsets.UTF_8);
+ AccountAuditEnvelope audit =
+ auditOutboxRepository.appendCanonicalTenant(
+ auditEventId, tenantUuid.toString(), AUDIT_EVENT_TYPE, auditText);
+ byte[] resultPayload =
+ AccountTenantCreationBootstrapDigest.resultPayload(
+ requestId,
+ requestDigest,
+ sourceDigest,
+ tenantUuid,
+ verifiedEvent.membershipVersion(),
+ Long.toString(baselineGeneration),
+ streamKey,
+ requestId,
+ checkpoint.outboxSequence(),
+ event.eventId(),
+ event.eventDigest(),
+ event.payload(),
+ audit.auditEventId(),
+ audit.eventType(),
+ audit.occurredAt().toString(),
+ audit.payloadDigest(),
+ audit.payload().getBytes(StandardCharsets.UTF_8),
+ creatorPayload,
+ sourcePayload);
+ String resultDigest = AccountTenantCreationBootstrapDigest.sha256(resultPayload);
+ StoredOperation completed =
+ operationRepository.complete(
+ evidence.accountAuthorizationOperationId(),
+ new Completion(
+ persisted.getId(),
+ newVersion,
+ baselineGeneration,
+ "ACTIVE",
+ false,
+ rolesPayload,
+ streamKey,
+ requestId,
+ checkpoint.outboxSequence(),
+ event.eventId(),
+ event.eventDigest(),
+ false,
+ event.payload(),
+ audit.auditEventId(),
+ audit.eventType(),
+ audit.occurredAt(),
+ audit.payloadDigest(),
+ audit.payload().getBytes(StandardCharsets.UTF_8),
+ resultPayload,
+ resultDigest));
+
+ verifyCommittedReadback(completed, persisted, roles, advanced, event, audit);
+ return completed.result();
+ }
+
+ private AccountTenantCreationBootstrapResult replayExactOriginal(
+ FreshTenantCreatorEvidence evidence, StoredOperation operation) {
+ byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence);
+ if (!operation.requestId().equals(evidence.accountAuthorizationOperationId())
+ || !operation.initiatingAccountUuid().equals(evidence.initiatingAccountId())
+ || !operation.tenantUuid().equals(evidence.creationEvidence().canonicalTenantId())
+ || !Arrays.equals(operation.creatorEvidencePayload(), creatorPayload)
+ || !operation.creatorEvidenceDigest().equals(evidence.evidenceDigest())
+ || !operation.creationOperationId().equals(evidence.creationEvidence().operationId())
+ || !operation.creationRequestId().equals(evidence.creationEvidence().creationRequestId())
+ || !operation
+ .accountAuthorizationOperationId()
+ .equals(evidence.accountAuthorizationOperationId())
+ || !operation.accountAuthorizationDigest().equals(evidence.accountAuthorizationDigest())) {
+ throw new AccountTenantCreationBootstrapOperationRepository.OperationConflictException(
+ "Creator-bootstrap operation ID was reused with changed creator or authorization source");
+ }
+ requireCommittedOperation(operation);
+ byte[] sourcePayload = operation.sourceSnapshotPayload();
+ byte[] requestPayload =
+ AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload);
+ if (!AccountTenantCreationBootstrapDigest.sha256(sourcePayload)
+ .equals(operation.sourceSnapshotDigest())
+ || !Arrays.equals(requestPayload, operation.requestPayload())
+ || !AccountTenantCreationBootstrapDigest.sha256(requestPayload)
+ .equals(operation.requestDigest())
+ || !AccountTenantCreationBootstrapDigest.sha256(operation.resultPayload())
+ .equals(operation.resultDigest())) {
+ throw new IllegalStateException(
+ "Creator-bootstrap immutable source or result digest differs");
+ }
+
+ MembershipEvent event =
+ MembershipAuthorityEventV1Codec.verify(
+ new String(operation.eventPayload(), StandardCharsets.UTF_8));
+ String expectedStream =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + evidence.initiatingAccountId()
+ + "/"
+ + evidence.creationEvidence().canonicalTenantId();
+ if (!expectedStream.equals(operation.eventStreamKey())
+ || !operation.requestId().toString().equals(operation.eventRequestId())
+ || operation.eventSequence() != 1L
+ || !event.outboxStreamKey().equals(operation.eventStreamKey())
+ || !event.requestId().equals(operation.eventRequestId())
+ || !event.eventId().equals(operation.eventId())
+ || !event.eventDigest().equals(operation.eventDigest())
+ || !"ACTIVE".equals(event.membershipLifecycleState())
+ || event.gameplayAdmissionAllowed()
+ || event.callerBoundAuthorityInvalidated()
+ || !event.roles().equals(List.of("tenantAdmin"))
+ || !Map.of(operation.tenantUuid().toString(), Long.toString(operation.membershipVersion()))
+ .equals(event.membershipVersion())) {
+ throw new IllegalStateException("Creator-bootstrap historical event receipt is inconsistent");
+ }
+ Event originalEvent =
+ authorityOutboxRepository
+ .findEvent(operation.eventStreamKey(), operation.eventRequestId())
+ .orElseThrow(() -> new IllegalStateException("Original creator event is absent"));
+ if (originalEvent.outboxSequence() != operation.eventSequence()
+ || !originalEvent.eventId().equals(operation.eventId())
+ || !originalEvent.eventDigest().equals(operation.eventDigest())
+ || !Arrays.equals(originalEvent.payload(), operation.eventPayload())) {
+ throw new IllegalStateException("Original creator event readback differs from its receipt");
+ }
+
+ AccountAuditEnvelope expectedAudit = auditEnvelope(operation);
+ AccountAuditEnvelope actualAudit =
+ auditOutboxRepository
+ .findExactCanonicalTenantEnvelopeForUpdate(expectedAudit)
+ .orElseThrow(
+ () -> new IllegalStateException("Original creator audit envelope is absent"));
+ if (!actualAudit.equals(expectedAudit)) {
+ throw new IllegalStateException("Original creator audit envelope differs from its receipt");
+ }
+ byte[] expectedResultPayload =
+ AccountTenantCreationBootstrapDigest.resultPayload(
+ operation.requestId().toString(),
+ operation.requestDigest(),
+ operation.sourceSnapshotDigest(),
+ operation.tenantUuid(),
+ event.membershipVersion(),
+ Long.toString(operation.membershipAuthorityGeneration()),
+ operation.eventStreamKey(),
+ operation.eventRequestId(),
+ operation.eventSequence(),
+ operation.eventId(),
+ operation.eventDigest(),
+ operation.eventPayload(),
+ operation.auditEventId(),
+ operation.auditEventType(),
+ operation.auditOccurredAt().toString(),
+ operation.auditPayloadDigest(),
+ operation.auditPayload(),
+ operation.creatorEvidencePayload(),
+ operation.sourceSnapshotPayload());
+ if (!Arrays.equals(expectedResultPayload, operation.resultPayload())) {
+ throw new IllegalStateException("Creator-bootstrap historical result bytes differ");
+ }
+ // This is immutable historical recovery. It intentionally does not read or rewrite current
+ // membership, roles, pair authority, or later JOIN state.
+ return operation.result();
+ }
+
+ private void verifyCommittedReadback(
+ StoredOperation completed,
+ AccountTenantMembership expectedMembership,
+ RoleSnapshot expectedRoles,
+ PairAuthority expectedPair,
+ Event expectedEvent,
+ AccountAuditEnvelope expectedAudit) {
+ AccountTenantMembership membership =
+ membershipRepository
+ .findCanonicalMembershipForUpdate(expectedPair.accountUuid(), expectedPair.tenantUuid())
+ .orElseThrow(() -> new IllegalStateException("Creator membership readback is absent"));
+ RoleSnapshot roles =
+ roleSnapshotRepository
+ .findForCanonicalUpdate(
+ expectedPair.accountUuid(),
+ expectedPair.tenantUuid(),
+ expectedPair.provenance(),
+ expectedMembership.getId(),
+ expectedMembership.getMembershipVersion())
+ .orElseThrow(
+ () -> new IllegalStateException("Creator role snapshot readback is absent"));
+ PairAuthority pair =
+ pairAuthorityRepository
+ .readForUpdate(expectedPair.accountUuid(), expectedPair.tenantUuid())
+ .orElseThrow(
+ () -> new IllegalStateException("Creator pair authority readback is absent"));
+ Event event =
+ authorityOutboxRepository
+ .findEvent(expectedEvent.outboxStreamKey(), expectedEvent.requestId())
+ .orElseThrow(() -> new IllegalStateException("Creator event readback is absent"));
+ MembershipEvent eventSnapshot =
+ MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8));
+ AccountTenantCreationBootstrapResult result = completed.result();
+ AccountAuditEnvelope audit =
+ auditOutboxRepository
+ .findExactCanonicalTenantEnvelopeForUpdate(expectedAudit)
+ .orElseThrow(() -> new IllegalStateException("Creator audit readback is absent"));
+ StoredOperation receipt =
+ operationRepository
+ .findForUpdate(completed.requestId())
+ .orElseThrow(() -> new IllegalStateException("Creator operation receipt is absent"));
+ if (!sameMembership(expectedMembership, membership)
+ || !expectedRoles.equals(roles)
+ || !expectedPair.equals(pair)
+ || !expectedEvent.equals(event)
+ || !expectedAudit.equals(audit)
+ || !result.membershipVersion().equals(eventSnapshot.membershipVersion())
+ || !Map.of(
+ expectedPair.tenantUuid().toString(),
+ Long.toString(expectedMembership.getMembershipVersion()))
+ .equals(result.membershipVersion())
+ || !"COMMITTED".equals(receipt.status())
+ || !completed.resultDigest().equals(receipt.resultDigest())
+ || !Arrays.equals(completed.resultPayload(), receipt.resultPayload())
+ || !Arrays.equals(completed.eventPayload(), receipt.eventPayload())
+ || !Arrays.equals(completed.auditPayload(), receipt.auditPayload())) {
+ throw new IllegalStateException(
+ "Creator membership, roles, pair, event, audit, or receipt readback differs");
+ }
+ }
+
+ private Map eventPreimage(
+ AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline,
+ UUID creatorUuid,
+ UUID tenantUuid,
+ long membershipVersion,
+ long membershipGeneration,
+ String streamKey,
+ String requestId,
+ String eventId) {
+ Map event = new LinkedHashMap<>();
+ event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION);
+ event.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE);
+ event.put("eventId", eventId);
+ event.put("requestId", requestId);
+ event.put("outboxStreamKey", streamKey);
+ event.put("outboxSequence", "1");
+ event.put("sourceScope", "membership/" + creatorUuid + "/" + tenantUuid);
+ event.put("accountId", creatorUuid.toString());
+ event.put("tenantId", tenantUuid.toString());
+ event.put("membershipExists", true);
+ event.put("membershipLifecycleState", "ACTIVE");
+ event.put("membershipVersion", Map.of(tenantUuid.toString(), Long.toString(membershipVersion)));
+ event.put("membershipAuthorityGeneration", Long.toString(membershipGeneration));
+ event.put(
+ "authorityTuple",
+ AccountTenantCreationBootstrapDigest.authorityTupleMap(baseline.authorityTuple()));
+ event.put("issuanceFence", baseline.issuanceFence());
+ event.put("roles", List.of("tenantAdmin"));
+ event.put("gameplayAdmissionAllowed", false);
+ event.put("callerBoundAuthorityInvalidated", false);
+ return event;
+ }
+
+ private byte[] auditPayload(
+ FreshTenantCreatorEvidence evidence,
+ String requestDigest,
+ String sourceSnapshotDigest,
+ long membershipVersion,
+ long membershipGeneration,
+ Event event,
+ Checkpoint checkpoint) {
+ Map payload = new LinkedHashMap<>();
+ payload.put("schemaVersion", "account-tenant-creation-bootstrap-audit/v1");
+ payload.put("requestId", evidence.accountAuthorizationOperationId().toString());
+ payload.put("requestDigest", requestDigest);
+ payload.put("initiatingAccountUuid", evidence.initiatingAccountId().toString());
+ payload.put("tenantUuid", evidence.creationEvidence().canonicalTenantId().toString());
+ payload.put("creationRequestId", evidence.creationEvidence().creationRequestId().toString());
+ payload.put("creationOperationId", evidence.creationEvidence().operationId().toString());
+ payload.put("creationRequestDigest", evidence.creationEvidence().requestDigest());
+ payload.put("creationEvidenceDigest", evidence.creationEvidence().evidenceDigest());
+ payload.put(
+ "accountAuthorizationOperationId", evidence.accountAuthorizationOperationId().toString());
+ payload.put("accountAuthorizationDigest", evidence.accountAuthorizationDigest());
+ payload.put("creatorEvidenceDigest", evidence.evidenceDigest());
+ payload.put("sourceSnapshotDigest", sourceSnapshotDigest);
+ payload.put(
+ "membershipVersion",
+ Map.of(
+ evidence.creationEvidence().canonicalTenantId().toString(),
+ Long.toString(membershipVersion)));
+ payload.put("membershipAuthorityGeneration", Long.toString(membershipGeneration));
+ payload.put("outboxStreamKey", checkpoint.outboxStreamKey());
+ payload.put("outboxSequence", Long.toString(checkpoint.outboxSequence()));
+ payload.put("eventId", event.eventId());
+ payload.put("eventDigest", event.eventDigest());
+ payload.put("callerBoundAuthorityInvalidated", false);
+ try {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(payload));
+ } catch (IOException | RuntimeException failure) {
+ throw new IllegalStateException("Creator-bootstrap audit serialization failed", failure);
+ }
+ }
+
+ private AccountAuditEnvelope auditEnvelope(StoredOperation operation) {
+ return new AccountAuditEnvelope(
+ operation.auditEventId(),
+ "tenant",
+ AccountAuditTenantIdentity.canonicalTenantV2(operation.tenantUuid().toString()),
+ "account-service",
+ operation.auditEventType(),
+ operation.auditOccurredAt(),
+ 1,
+ 1,
+ operation.auditPayloadDigest(),
+ new String(operation.auditPayload(), StandardCharsets.UTF_8));
+ }
+
+ private static VerifiedTenantProvenance freshProvenance(FreshTenantCreationEvidence source) {
+ return new VerifiedTenantProvenance(
+ null,
+ TenantProvenanceKind.FRESH_GAME_DESIGN,
+ source.operationId(),
+ source.evidenceDigest());
+ }
+
+ private static void requireCommittedOperation(StoredOperation operation) {
+ if (!"COMMITTED".equals(operation.status())
+ || operation.membershipId() == null
+ || operation.membershipVersion() == null
+ || operation.membershipAuthorityGeneration() == null
+ || !"ACTIVE".equals(operation.membershipLifecycleState())
+ || !Boolean.FALSE.equals(operation.gameplayAdmissionAllowed())
+ || !Boolean.FALSE.equals(operation.callerBoundAuthorityInvalidated())
+ || operation.membershipRolesPayload() == null
+ || operation.eventPayload() == null
+ || operation.auditPayload() == null
+ || operation.resultPayload() == null
+ || operation.resultDigest() == null
+ || operation.committedAt() == null) {
+ throw new IllegalStateException("Incomplete creator-bootstrap operation cannot be replayed");
+ }
+ }
+
+ private static boolean sameMembership(
+ AccountTenantMembership expected, AccountTenantMembership actual) {
+ return Objects.equals(expected.getId(), actual.getId())
+ && Objects.equals(
+ expected.getAccount().getAccountUuid(), actual.getAccount().getAccountUuid())
+ && Objects.equals(expected.getTenantUuid(), actual.getTenantUuid())
+ && Objects.equals(expected.getTenantId(), actual.getTenantId())
+ && Objects.equals(expected.getTenantProvenanceKind(), actual.getTenantProvenanceKind())
+ && Objects.equals(
+ expected.getTenantSourceOperationId(), actual.getTenantSourceOperationId())
+ && Objects.equals(expected.getTenantProvenanceDigest(), actual.getTenantProvenanceDigest())
+ && Objects.equals(expected.getLifecycleState(), actual.getLifecycleState())
+ && expected.isGameplayAdmissionAllowed() == actual.isGameplayAdmissionAllowed()
+ && expected.getMembershipVersion() == actual.getMembershipVersion()
+ && expected.getMembershipAuthorityGeneration() == actual.getMembershipAuthorityGeneration()
+ && Objects.equals(expected.getAuthorityProvenance(), actual.getAuthorityProvenance());
+ }
+
+ private static void requireAccountIdentity(Account account, UUID expectedUuid) {
+ if (account.getId() == null
+ || account.getId() <= 0L
+ || !expectedUuid.equals(account.getAccountUuid())
+ || account.getAccountUuidProvenance() == null
+ || account.getAccountUuidSourceNumericId() == null
+ || !account.getId().equals(account.getAccountUuidSourceNumericId())) {
+ throw new IllegalStateException(
+ "Creator Account UUID provenance is incomplete or mismatched");
+ }
+ }
+
+ private static long positiveLong(String value, String label) {
+ if (value == null || !value.matches("[1-9][0-9]*")) {
+ throw new IllegalStateException("Creator-bootstrap " + label + " is not a positive decimal");
+ }
+ try {
+ long parsed = Long.parseLong(value);
+ if (parsed <= 0L) {
+ throw new IllegalStateException("Creator-bootstrap " + label + " is not positive");
+ }
+ return parsed;
+ } catch (NumberFormatException overflow) {
+ throw new IllegalStateException(
+ "Creator-bootstrap " + label + " exceeds Account BIGINT", overflow);
+ }
+ }
+
+ private static long increment(long value, String label) {
+ try {
+ return Math.addExact(value, 1L);
+ } catch (ArithmeticException overflow) {
+ throw new IllegalStateException("Account " + label + " is exhausted", overflow);
+ }
+ }
+
+ private static void requireWritableOwnerTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException("Creator bootstrap requires a writable Account transaction");
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecks.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecks.java
new file mode 100644
index 0000000000..84cc2f5016
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecks.java
@@ -0,0 +1,319 @@
+package net.firedevops.firemud.accountservice.service.controlui;
+
+import com.fasterxml.jackson.core.StreamReadFeature;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.time.Clock;
+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.Optional;
+import java.util.Set;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ActualClaimMaps;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ControlUiShape;
+import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier;
+import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy;
+import net.firedevops.firemud.common.security.AccountJwtExactValues;
+import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator;
+
+/**
+ * Account-owned signature, profile, catalog and exact active-registry claim predicates.
+ *
+ * This unwired prerequisite performs no issuance or registry mutation. Its private-minted
+ * inspection is deliberately non-authorizing: the owner still needs one complete current
+ * account-auth-evidence-bundle/v1, exact projection freshness, immutable signer-generation/kid
+ * retention and the operation's registry postconditions before creating a caller principal. Neither
+ * a raw actor UUID nor a caller-constructed snapshot can satisfy those missing producers.
+ */
+public final class AccountControlUiTokenChecks {
+ private static final Set RECORD_FIELDS =
+ Set.of(
+ "schemaVersion",
+ "registryVersion",
+ "tokenHash",
+ "kid",
+ "signerGeneration",
+ "accountId",
+ "issuer",
+ "profile",
+ "type",
+ "audience",
+ "jti",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "operationId",
+ "requestId",
+ "requestDigest",
+ "state",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence",
+ "authoritySourceVersions",
+ "authEvidenceBundle");
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+ .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .build();
+ private static final TypeReference> OBJECT = new TypeReference<>() {};
+
+ private final AccountAsymmetricJwtVerifier verifier;
+ private final AccountTokenProfileCatalog catalog;
+ private final Clock clock;
+
+ public AccountControlUiTokenChecks(
+ AccountAsymmetricJwtVerifier verifier, AccountTokenProfileCatalog catalog, Clock clock) {
+ this.verifier = Objects.requireNonNull(verifier);
+ this.catalog = Objects.requireNonNull(catalog);
+ this.clock = Objects.requireNonNull(clock);
+ }
+
+ /**
+ * Checks the exact record returned by the owning adapter's one atomic registry lookup. The
+ * route-derived applicability shape is owner policy, never request data. It keeps tenant and
+ * caller-membership scope sets independent, including the closed billing-safe exception.
+ */
+ public InspectedToken inspect(
+ String routeId, String compactJwt, byte[] exactRegistryBytes, ControlUiShape applicability) {
+ try {
+ Objects.requireNonNull(applicability);
+ var limits = catalog.requireProfile(AccountTokenProfileCatalog.CONTROL_UI);
+ ExplicitRouteProfilePolicy policy =
+ new ExplicitRouteProfilePolicy(
+ routeId,
+ ControlUiJwtProfileValidator.PROFILE,
+ ControlUiJwtProfileValidator.TOKEN_TYPE,
+ ControlUiJwtProfileValidator.ISSUER,
+ ControlUiJwtProfileValidator.AUDIENCE,
+ ControlUiJwtProfileValidator.REQUIRED_CLAIMS,
+ ControlUiJwtProfileValidator.OPTIONAL_CLAIMS,
+ limits.maxTokenLifetimeSeconds(),
+ 0L,
+ Math.toIntExact(limits.maxCompactJwtBytes()),
+ claims -> {
+ ControlUiJwtProfileValidator.validateClaims(
+ claims,
+ limits.maxControlUiTenantScopes().orElseThrow(),
+ limits.maxAuthorityTupleBytes());
+ });
+ var signed = verifier.verify(compactJwt, policy);
+ if (exactRegistryBytes == null
+ || exactRegistryBytes.length == 0
+ || exactRegistryBytes.length > limits.maxRegistryRecordBytes()) throw invalid();
+ Map record = JSON.readValue(exactRegistryBytes, OBJECT);
+ if (!record.keySet().equals(RECORD_FIELDS)
+ || !positiveCounter(record.get("schemaVersion")).equals(BigInteger.TWO)
+ || !positiveCounter(record.get("registryVersion")).equals(BigInteger.TWO)
+ || !"active".equals(record.get("state"))
+ || !ControlUiJwtProfileValidator.PROFILE.equals(record.get("profile"))
+ || !ControlUiJwtProfileValidator.TOKEN_TYPE.equals(record.get("type"))
+ || !signed.keyId().equals(record.get("kid"))
+ || !sha256(compactJwt).equals(record.get("tokenHash"))) throw invalid();
+ requirePositiveDecimal(record.get("signerGeneration"));
+ requireUuid(record.get("operationId"));
+ requireUuid(record.get("requestId"));
+ if (!(record.get("requestDigest") instanceof String digest)
+ || !digest.matches("[0-9a-f]{64}")) throw invalid();
+ Map claims = signed.claims();
+ requireEqual(record.get("issuer"), claims.get("iss"));
+ requireEqual(record.get("audience"), claims.get("aud"));
+ for (String field :
+ List.of(
+ "accountId",
+ "jti",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence")) {
+ requireEqual(record.get(field), claims.get(field));
+ }
+ if (clock.instant().getEpochSecond() >= positiveEpochSecond(record.get("exp")))
+ throw invalid();
+ requireSourceReferences(record);
+ if (!Arrays.equals(exactRegistryBytes, canonicalBytes(record))) throw invalid();
+ catalog.validatePreSignCandidate(
+ AccountTokenProfileCatalog.CONTROL_UI,
+ applicability,
+ actualMaps(claims),
+ positiveEpochSecond(claims.get("iat")),
+ positiveEpochSecond(claims.get("exp")),
+ canonicalText(claims.get("authorityTuple")));
+ catalog.validatePostSignCandidate(
+ AccountTokenProfileCatalog.CONTROL_UI, compactJwt, canonicalText(record));
+ return new InspectedToken(UUID.fromString((String) claims.get("accountId")), signed, record);
+ } catch (AccountAsymmetricJwtVerifier.VerificationUnavailableException failure) {
+ throw failure;
+ } catch (RuntimeException failure) {
+ throw invalid();
+ } catch (Exception failure) {
+ throw invalid();
+ }
+ }
+
+ private static ActualClaimMaps actualMaps(Map claims) {
+ Map membership = new LinkedHashMap<>();
+ object(claims.get("membershipVersion"))
+ .forEach(
+ (tenant, version) ->
+ membership.put(tenant, AccountJwtExactValues.nonNegativeDecimalCounter(version)));
+ Map> roles = new LinkedHashMap<>();
+ object(claims.get("scopedRoles"))
+ .forEach(
+ (tenant, value) -> {
+ if (!(value instanceof List> list)) throw invalid();
+ roles.put(
+ tenant,
+ list.stream()
+ .map(
+ item -> {
+ if (!(item instanceof String role)) throw invalid();
+ return role;
+ })
+ .toList());
+ });
+ return new ActualClaimMaps(Optional.of(membership), Optional.of(roles));
+ }
+
+ private static void requireSourceReferences(Map record) {
+ Map source = object(record.get("authoritySourceVersions"));
+ if (!source
+ .keySet()
+ .equals(
+ Set.of("issuerSourceVersion", "accountSourceVersion", "issuanceFenceSourceVersion"))) {
+ throw invalid();
+ }
+ source.values().forEach(AccountControlUiTokenChecks::positiveCounter);
+ Map bundle = object(record.get("authEvidenceBundle"));
+ if (!bundle
+ .keySet()
+ .equals(Set.of("bundleVersion", "sourceVersion", "linearization", "canonicalSha256"))) {
+ throw invalid();
+ }
+ for (String field : List.of("bundleVersion", "sourceVersion", "linearization")) {
+ requirePositiveDecimal(bundle.get(field));
+ }
+ if (!(bundle.get("canonicalSha256") instanceof String digest)
+ || !digest.matches("[0-9a-f]{64}")) throw invalid();
+ if (!"1".equals(bundle.get("bundleVersion"))) throw invalid();
+ // The bundle sourceVersion identifies its durable evidence capture. It is independent of
+ // each authority source counter; equality with the actual bundle and its exact source
+ // versions/checkpoints belongs to the missing owner-readback/currentness gate.
+ }
+
+ private static Map object(Object value) {
+ if (!(value instanceof Map, ?> map)) throw invalid();
+ Map copy = new LinkedHashMap<>();
+ map.forEach(
+ (key, item) -> {
+ if (!(key instanceof String text) || item == null) throw invalid();
+ copy.put(text, item);
+ });
+ return Map.copyOf(copy);
+ }
+
+ private static BigInteger positiveCounter(Object value) {
+ return AccountJwtExactValues.positiveCounter(value);
+ }
+
+ private static long positiveEpochSecond(Object value) {
+ return positiveCounter(value).longValueExact();
+ }
+
+ private static void requirePositiveDecimal(Object value) {
+ AccountJwtExactValues.positiveDecimalCounter(value);
+ }
+
+ private static void requireUuid(Object value) {
+ if (!(value instanceof String text)
+ || !UUID.fromString(text).toString().equals(text)
+ || new UUID(0L, 0L).toString().equals(text)) throw invalid();
+ }
+
+ private static void requireEqual(Object actual, Object expected) {
+ if (actual == null
+ || expected == null
+ || !AccountJwtExactValues.sameJsonValue(actual, expected)) throw invalid();
+ }
+
+ private static byte[] canonicalBytes(Object value) {
+ try {
+ return AccountJwtExactValues.losslessCanonicalBytes(value);
+ } catch (Exception failure) {
+ throw invalid();
+ }
+ }
+
+ private static String canonicalText(Object value) {
+ return new String(canonicalBytes(value), StandardCharsets.UTF_8);
+ }
+
+ private static String sha256(String compactJwt) {
+ try {
+ return HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(compactJwt.getBytes(StandardCharsets.US_ASCII)));
+ } catch (Exception failure) {
+ throw invalid();
+ }
+ }
+
+ private static InvalidTokenException invalid() {
+ return new InvalidTokenException();
+ }
+
+ /** An immutable cryptographic/record inspection, never a principal or freshness receipt. */
+ public static final class InspectedToken {
+ private final UUID accountId;
+ private final AccountAsymmetricJwtVerifier.VerifiedClaims signed;
+ private final Map record;
+
+ private InspectedToken(
+ UUID accountId,
+ AccountAsymmetricJwtVerifier.VerifiedClaims signed,
+ Map record) {
+ this.accountId = accountId;
+ this.signed = signed;
+ this.record = JSON.convertValue(record, OBJECT);
+ }
+
+ public UUID accountId() {
+ return accountId;
+ }
+
+ public Map claims() {
+ return signed.claims();
+ }
+
+ public Map registryRecord() {
+ return JSON.convertValue(record, OBJECT);
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiInspectedToken[non-authorizing]";
+ }
+ }
+
+ public static final class InvalidTokenException extends RuntimeException {
+ private InvalidTokenException() {
+ super("Account control-ui token inspection failed");
+ }
+ }
+}
diff --git a/services/account-service/src/main/resources/db/migration/V62__account_tenant_creation_control_only_provenance.sql b/services/account-service/src/main/resources/db/migration/V62__account_tenant_creation_control_only_provenance.sql
new file mode 100644
index 0000000000..b7ec289e2e
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V62__account_tenant_creation_control_only_provenance.sql
@@ -0,0 +1,15 @@
+-- Creator bootstrap is a distinct control-only membership provenance. The
+-- owner producer remains responsible for proving its source and membership
+-- state; this storage constraint only prevents it from admitting gameplay.
+ALTER TABLE account_tenant_membership
+ DROP CONSTRAINT account_membership_provenance_check;
+
+ALTER TABLE account_tenant_membership
+ ADD CONSTRAINT account_membership_provenance_check
+ CHECK (authority_provenance IN (
+ 'EXPLICIT_JOIN', 'LEGACY_UNVERIFIED', 'SEEDED_DEMO', 'TENANT_CREATION'));
+
+ALTER TABLE account_tenant_membership
+ ADD CONSTRAINT account_membership_tenant_creation_not_admitting_check
+ CHECK (authority_provenance <> 'TENANT_CREATION'
+ OR gameplay_admission_allowed = FALSE);
diff --git a/services/account-service/src/main/resources/db/migration/V64__account_tenant_creation_bootstrap.sql b/services/account-service/src/main/resources/db/migration/V64__account_tenant_creation_bootstrap.sql
new file mode 100644
index 0000000000..662c0252a7
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V64__account_tenant_creation_bootstrap.sql
@@ -0,0 +1,189 @@
+-- One immutable owner receipt for the first control-only Account membership created
+-- from an exact, authenticated Game Design tenant-creation source. This storage does
+-- not provide authentication or expose a mutation route.
+CREATE TABLE account_tenant_creation_bootstrap_operations (
+ request_id UUID PRIMARY KEY,
+ schema_version SMALLINT NOT NULL CHECK (schema_version = 1),
+ initiating_account_uuid UUID NOT NULL REFERENCES accounts (account_uuid),
+ tenant_uuid UUID NOT NULL,
+ creation_request_id UUID NOT NULL,
+ creation_operation_id UUID NOT NULL,
+ account_authorization_operation_id UUID NOT NULL,
+ account_authorization_digest VARCHAR(71) NOT NULL
+ CHECK (account_authorization_digest ~ '^sha256:[0-9a-f]{64}$'),
+ creator_evidence_digest VARCHAR(71) NOT NULL
+ CHECK (creator_evidence_digest ~ '^sha256:[0-9a-f]{64}$'),
+ creator_evidence_payload BYTEA NOT NULL,
+ source_snapshot_payload BYTEA NOT NULL,
+ source_snapshot_digest VARCHAR(71) NOT NULL
+ CHECK (source_snapshot_digest ~ '^sha256:[0-9a-f]{64}$'),
+ request_payload BYTEA NOT NULL,
+ request_digest VARCHAR(71) NOT NULL
+ CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'),
+ baseline_membership_version BIGINT NOT NULL CHECK (baseline_membership_version > 0),
+ baseline_membership_authority_generation BIGINT NOT NULL
+ CHECK (baseline_membership_authority_generation > 0),
+ baseline_event_sequence BIGINT NOT NULL CHECK (baseline_event_sequence = 0),
+ membership_id BIGINT,
+ membership_version BIGINT,
+ membership_authority_generation BIGINT,
+ membership_lifecycle_state VARCHAR(16),
+ gameplay_admission_allowed BOOLEAN,
+ membership_roles_payload BYTEA,
+ event_stream_key VARCHAR(256),
+ event_request_id VARCHAR(128),
+ event_sequence BIGINT,
+ event_id VARCHAR(512),
+ event_digest VARCHAR(71),
+ caller_bound_authority_invalidated BOOLEAN,
+ event_payload BYTEA,
+ audit_event_id UUID,
+ audit_event_type VARCHAR(80),
+ audit_occurred_at TIMESTAMPTZ,
+ audit_payload_digest VARCHAR(71),
+ audit_payload BYTEA,
+ result_payload BYTEA,
+ result_digest VARCHAR(71),
+ status VARCHAR(16) NOT NULL CHECK (status IN ('IN_PROGRESS', 'COMMITTED')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ committed_at TIMESTAMPTZ,
+ CONSTRAINT account_tenant_creation_bootstrap_authorization_identity_check
+ CHECK (request_id = account_authorization_operation_id),
+ CONSTRAINT account_tenant_creation_bootstrap_creator_tenant_uq
+ UNIQUE (tenant_uuid),
+ CONSTRAINT account_tenant_creation_bootstrap_creation_operation_uq
+ UNIQUE (creation_operation_id),
+ CONSTRAINT account_tenant_creation_bootstrap_membership_state_check
+ CHECK (membership_lifecycle_state IS NULL OR membership_lifecycle_state = 'ACTIVE'),
+ CONSTRAINT account_tenant_creation_bootstrap_admission_check
+ CHECK (gameplay_admission_allowed IS NULL OR gameplay_admission_allowed = FALSE),
+ CONSTRAINT account_tenant_creation_bootstrap_generation_check
+ CHECK (membership_authority_generation IS NULL OR
+ membership_authority_generation = baseline_membership_authority_generation),
+ CONSTRAINT account_tenant_creation_bootstrap_event_check
+ CHECK (event_sequence IS NULL OR event_sequence = 1),
+ CONSTRAINT account_tenant_creation_bootstrap_event_scope_check
+ CHECK (event_stream_key IS NULL OR event_stream_key =
+ 'account:auth-authority:v1:membership/' || initiating_account_uuid::TEXT || '/' || tenant_uuid::TEXT),
+ CONSTRAINT account_tenant_creation_bootstrap_event_request_check
+ CHECK (event_request_id IS NULL OR event_request_id = request_id::TEXT),
+ CONSTRAINT account_tenant_creation_bootstrap_invalidation_check
+ CHECK (caller_bound_authority_invalidated IS NULL OR caller_bound_authority_invalidated = FALSE),
+ CONSTRAINT account_tenant_creation_bootstrap_completion_shape CHECK (
+ (status = 'IN_PROGRESS'
+ AND membership_id IS NULL AND membership_version IS NULL
+ AND membership_authority_generation IS NULL AND membership_lifecycle_state IS NULL
+ AND gameplay_admission_allowed IS NULL AND membership_roles_payload IS NULL
+ AND event_stream_key IS NULL AND event_request_id IS NULL AND event_sequence IS NULL
+ AND event_id IS NULL AND event_digest IS NULL
+ AND caller_bound_authority_invalidated IS NULL AND event_payload IS NULL
+ AND audit_event_id IS NULL AND audit_event_type IS NULL AND audit_occurred_at IS NULL
+ AND audit_payload_digest IS NULL AND audit_payload IS NULL
+ AND result_payload IS NULL AND result_digest IS NULL AND committed_at IS NULL)
+ OR (status = 'COMMITTED'
+ AND membership_id IS NOT NULL AND membership_id > 0
+ AND membership_version = baseline_membership_version + 1
+ AND membership_authority_generation = baseline_membership_authority_generation
+ AND membership_lifecycle_state = 'ACTIVE'
+ AND gameplay_admission_allowed = FALSE
+ AND membership_roles_payload = convert_to('["tenantAdmin"]', 'UTF8')
+ AND event_stream_key IS NOT NULL AND event_request_id IS NOT NULL
+ AND event_sequence = 1 AND event_id IS NOT NULL AND length(btrim(event_id)) > 0
+ AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND caller_bound_authority_invalidated = FALSE AND event_payload IS NOT NULL
+ AND audit_event_id IS NOT NULL AND audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED'
+ AND audit_occurred_at IS NOT NULL
+ AND audit_payload_digest IS NOT NULL AND audit_payload_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND audit_payload IS NOT NULL
+ AND result_payload IS NOT NULL AND result_digest IS NOT NULL
+ AND result_digest ~ '^sha256:[0-9a-f]{64}$' AND committed_at IS NOT NULL))
+);
+
+CREATE INDEX account_tenant_creation_bootstrap_creator_idx
+ ON account_tenant_creation_bootstrap_operations
+ (initiating_account_uuid, tenant_uuid, request_id);
+
+-- [jooq ignore start]
+CREATE FUNCTION account_tenant_creation_bootstrap_update_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF NEW.request_id IS DISTINCT FROM OLD.request_id
+ OR NEW.schema_version IS DISTINCT FROM OLD.schema_version
+ OR NEW.initiating_account_uuid IS DISTINCT FROM OLD.initiating_account_uuid
+ OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid
+ OR NEW.creation_request_id IS DISTINCT FROM OLD.creation_request_id
+ OR NEW.creation_operation_id IS DISTINCT FROM OLD.creation_operation_id
+ OR NEW.account_authorization_operation_id IS DISTINCT FROM OLD.account_authorization_operation_id
+ OR NEW.account_authorization_digest IS DISTINCT FROM OLD.account_authorization_digest
+ OR NEW.creator_evidence_digest IS DISTINCT FROM OLD.creator_evidence_digest
+ OR NEW.creator_evidence_payload IS DISTINCT FROM OLD.creator_evidence_payload
+ OR NEW.source_snapshot_payload IS DISTINCT FROM OLD.source_snapshot_payload
+ OR NEW.source_snapshot_digest IS DISTINCT FROM OLD.source_snapshot_digest
+ OR NEW.request_payload IS DISTINCT FROM OLD.request_payload
+ OR NEW.request_digest IS DISTINCT FROM OLD.request_digest
+ OR NEW.baseline_membership_version IS DISTINCT FROM OLD.baseline_membership_version
+ OR NEW.baseline_membership_authority_generation IS DISTINCT FROM OLD.baseline_membership_authority_generation
+ OR NEW.baseline_event_sequence IS DISTINCT FROM OLD.baseline_event_sequence
+ OR NEW.created_at IS DISTINCT FROM OLD.created_at
+ OR OLD.status <> 'IN_PROGRESS'
+ OR NEW.status <> 'COMMITTED' THEN
+ RAISE EXCEPTION 'Account creator-bootstrap request is immutable'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_tenant_creation_bootstrap_identity_immutable';
+ END IF;
+ NEW.committed_at = CURRENT_TIMESTAMP;
+ RETURN NEW;
+END;
+$$;
+
+CREATE FUNCTION account_tenant_creation_bootstrap_insert_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF NEW.status <> 'IN_PROGRESS'
+ OR NEW.membership_id IS NOT NULL OR NEW.membership_version IS NOT NULL
+ OR NEW.membership_authority_generation IS NOT NULL
+ OR NEW.membership_lifecycle_state IS NOT NULL OR NEW.gameplay_admission_allowed IS NOT NULL
+ OR NEW.membership_roles_payload IS NOT NULL
+ OR NEW.event_stream_key IS NOT NULL OR NEW.event_request_id IS NOT NULL
+ OR NEW.event_sequence IS NOT NULL OR NEW.event_id IS NOT NULL OR NEW.event_digest IS NOT NULL
+ OR NEW.caller_bound_authority_invalidated IS NOT NULL OR NEW.event_payload IS NOT NULL
+ OR NEW.audit_event_id IS NOT NULL OR NEW.audit_event_type IS NOT NULL
+ OR NEW.audit_occurred_at IS NOT NULL OR NEW.audit_payload_digest IS NOT NULL
+ OR NEW.audit_payload IS NOT NULL OR NEW.result_payload IS NOT NULL
+ OR NEW.result_digest IS NOT NULL OR NEW.committed_at IS NOT NULL THEN
+ RAISE EXCEPTION 'Account creator-bootstrap operation must begin without a result'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_tenant_creation_bootstrap_initial_state';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE FUNCTION account_tenant_creation_bootstrap_no_delete()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RAISE EXCEPTION 'Account creator-bootstrap history cannot be deleted'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_tenant_creation_bootstrap_no_delete';
+ RETURN OLD;
+END;
+$$;
+
+CREATE TRIGGER account_tenant_creation_bootstrap_insert
+ BEFORE INSERT ON account_tenant_creation_bootstrap_operations
+ FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_insert_guard();
+
+CREATE TRIGGER account_tenant_creation_bootstrap_update
+ BEFORE UPDATE ON account_tenant_creation_bootstrap_operations
+ FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_update_guard();
+
+CREATE TRIGGER account_tenant_creation_bootstrap_delete
+ BEFORE DELETE ON account_tenant_creation_bootstrap_operations
+ FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_no_delete();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java
new file mode 100644
index 0000000000..cccccc11da
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java
@@ -0,0 +1,645 @@
+package integration.net.firedevops.firemud.accountservice;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.locks.ReentrantLock;
+import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult;
+import net.firedevops.firemud.accountservice.entity.AccountTenantMembership;
+import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation;
+import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantRoleOperationRepository;
+import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer;
+import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource;
+import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService;
+import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
+import org.flywaydb.core.Flyway;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/**
+ * Account transaction-composition proof using a synthetic current-source participant. The
+ * participant is test-only and does not establish production authentication or authorization.
+ */
+@Testcontainers(disabledWithoutDocker = true)
+class AccountTenantCreationBootstrapServicePostgresIntegrationTest {
+ private static final String TEST_NAMESPACE = "creator-bootstrap-proof";
+ private static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED";
+ private static final String SCHEMA_PREFIX = "creator_bootstrap_service_proof_";
+
+ @Container
+ static PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
+
+ @Test
+ void commitIsControlOnlyAndHistoricalRetryDoesNotOverwriteLaterMembershipAdvance() {
+ Fixture fixture = fixture(false);
+ AccountTenantCreationBootstrapResult original = bootstrap(fixture);
+ assertThat(original.membershipVersion())
+ .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2"));
+ assertThat(original.membershipAuthorityGeneration()).isEqualTo("1");
+ assertThat(original.roles()).containsExactly("tenantAdmin");
+ assertThat(original.gameplayAdmissionAllowed()).isFalse();
+ String streamKey = membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid());
+ AccountAuthorityOutboxRepository.Event originalOutboxEvent =
+ inTransaction(
+ fixture,
+ () ->
+ fixture
+ .outbox()
+ .findEvent(
+ streamKey, fixture.evidence().accountAuthorizationOperationId().toString())
+ .orElseThrow());
+ MembershipEvent originalEvent =
+ MembershipAuthorityEventV1Codec.verify(
+ new String(originalOutboxEvent.payload(), StandardCharsets.UTF_8));
+ assertThat(originalEvent.outboxSequence()).isEqualTo(1L);
+ assertThat(originalEvent.membershipLifecycleState()).isEqualTo("ACTIVE");
+ assertThat(originalEvent.membershipVersion())
+ .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2"));
+ assertThat(originalEvent.membershipAuthorityGeneration()).isEqualTo("1");
+ assertThat(originalEvent.authorityTuple().issuerAuthGeneration()).isEqualTo("1");
+ assertThat(originalEvent.authorityTuple().accountAuthorityGeneration()).isEqualTo("1");
+ assertThat(originalEvent.authorityTuple().tenantAuthorityGeneration())
+ .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1"));
+ assertThat(originalEvent.authorityTuple().membershipAuthorityGeneration())
+ .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1"));
+ assertThat(originalEvent.authorityTuple().privateRealmGrantVersions()).isEmpty();
+ assertThat(originalEvent.authorityTuple().accountSecurityCutoff()).isEmpty();
+ assertThat(originalEvent.authorityTuple().tenantBillingCutoff()).isEmpty();
+ assertThat(originalEvent.roles()).containsExactly("tenantAdmin");
+ assertThat(originalEvent.gameplayAdmissionAllowed()).isFalse();
+ assertThat(originalEvent.callerBoundAuthorityInvalidated()).isFalse();
+ assertThat(originalOutboxEvent.outboxSequence()).isEqualTo(1L);
+ assertThat(originalOutboxEvent.eventId()).isEqualTo(originalEvent.eventId());
+ assertThat(originalOutboxEvent.eventDigest()).isEqualTo(originalEvent.eventDigest());
+
+ AccountTenantMembership committedMembership =
+ inTransaction(
+ fixture,
+ () ->
+ fixture
+ .memberships()
+ .findCanonicalMembershipForUpdate(fixture.accountUuid(), fixture.tenantUuid())
+ .orElseThrow());
+ assertThat(committedMembership.getLifecycleState()).isEqualTo("ACTIVE");
+ assertThat(committedMembership.getMembershipVersion()).isEqualTo(2L);
+ assertThat(committedMembership.getMembershipAuthorityGeneration()).isEqualTo(1L);
+ assertThat(committedMembership.isGameplayAdmissionAllowed()).isFalse();
+ assertThat(
+ countQuery(
+ fixture.setupDsl(),
+ "SELECT count(*) FROM account_audit_outbox "
+ + "WHERE audit_event_id = ? AND event_type = ?",
+ auditEventId(fixture.evidence().accountAuthorizationOperationId()),
+ AUDIT_EVENT_TYPE))
+ .isEqualTo(1L);
+ StoredOperation receipt =
+ inTransaction(
+ fixture,
+ () ->
+ fixture
+ .operationRepository()
+ .findForUpdate(fixture.evidence().accountAuthorizationOperationId())
+ .orElseThrow());
+ assertThat(receipt.status()).isEqualTo("COMMITTED");
+ assertThat(receipt.result()).isEqualTo(original);
+ PairAuthority initialPair =
+ inTransaction(
+ fixture,
+ () ->
+ fixture
+ .pairAuthority()
+ .readForUpdate(fixture.accountUuid(), fixture.tenantUuid())
+ .orElseThrow());
+ assertThat(initialPair.membershipExists()).isTrue();
+ assertThat(initialPair.membershipVersion()).isEqualTo(2L);
+ assertThat(initialPair.membershipAuthorityGeneration()).isEqualTo(1L);
+ assertThat(initialPair.lastEventSequence()).isEqualTo(1L);
+ assertThat(initialPair.lastTransitionInvalidated()).isFalse();
+
+ advanceMembershipForLaterJoin(fixture, originalEvent);
+ AccountTenantCreationBootstrapResult replay = bootstrap(fixture);
+ assertThat(replay).isEqualTo(original);
+
+ CurrentState current = currentState(fixture);
+ assertThat(current.membership().getMembershipVersion()).isEqualTo(3L);
+ assertThat(current.membership().getMembershipAuthorityGeneration()).isEqualTo(1L);
+ assertThat(current.membership().isGameplayAdmissionAllowed()).isTrue();
+ assertThat(current.roles()).containsExactly("player", "tenantAdmin");
+ assertThat(current.pair().membershipVersion()).isEqualTo(3L);
+ assertThat(current.pair().lastEventSequence()).isEqualTo(2L);
+ }
+
+ @Test
+ void lateReceiptFailureRollsBackMembershipRolesPairEventAuditAndClaimTogether() {
+ Fixture fixture = fixture(true);
+ assertThatThrownBy(() -> bootstrap(fixture))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("injected after Account audit append");
+
+ String streamKey = membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid());
+ UUID auditId = auditEventId(fixture.evidence().accountAuthorizationOperationId());
+ assertThat(
+ count(
+ fixture.setupDsl(),
+ "account_tenant_membership",
+ "tenant_uuid",
+ fixture.tenantUuid()))
+ .isEqualTo(0L);
+ assertThat(
+ countQuery(
+ fixture.setupDsl(),
+ "SELECT count(*) FROM account_tenant_membership_role_snapshots s "
+ + "JOIN account_tenant_membership m ON m.id = s.membership_id "
+ + "WHERE m.tenant_uuid = ?",
+ fixture.tenantUuid()))
+ .isEqualTo(0L);
+ assertThat(
+ countQuery(
+ fixture.setupDsl(),
+ "SELECT count(*) FROM account_membership_pair_authority "
+ + "WHERE account_uuid = ? AND tenant_uuid = ?",
+ fixture.accountUuid(),
+ fixture.tenantUuid()))
+ .isEqualTo(0L);
+ assertThat(
+ countQuery(
+ fixture.setupDsl(),
+ "SELECT count(*) FROM account_authority_outbox_events "
+ + "WHERE outbox_stream_key = ?",
+ streamKey))
+ .isEqualTo(0L);
+ assertThat(
+ countQuery(
+ fixture.setupDsl(),
+ "SELECT count(*) FROM account_authority_outbox_streams "
+ + "WHERE outbox_stream_key = ?",
+ streamKey))
+ .isEqualTo(0L);
+ assertThat(
+ countQuery(
+ fixture.setupDsl(),
+ "SELECT count(*) FROM account_audit_outbox "
+ + "WHERE audit_event_id = ? AND event_type = ?",
+ auditId,
+ AUDIT_EVENT_TYPE))
+ .isEqualTo(0L);
+ assertThat(
+ countQuery(
+ fixture.setupDsl(),
+ "SELECT count(*) FROM account_tenant_creation_bootstrap_operations "
+ + "WHERE request_id = ?",
+ fixture.evidence().accountAuthorizationOperationId()))
+ .isEqualTo(0L);
+ assertThat(
+ countQuery(
+ fixture.setupDsl(),
+ "SELECT count(*) FROM account_authority_generations "
+ + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?",
+ fixture.accountUuid(),
+ fixture.tenantUuid()))
+ .isEqualTo(0L);
+ }
+
+ private static AccountTenantCreationBootstrapResult bootstrap(Fixture fixture) {
+ return fixture.transaction().execute(status -> fixture.service().bootstrap(fixture.evidence()));
+ }
+
+ private static void advanceMembershipForLaterJoin(
+ Fixture fixture, MembershipEvent originalEvent) {
+ inTransaction(
+ fixture,
+ () -> {
+ VerifiedTenantProvenance provenance = provenance(fixture.evidence().creationEvidence());
+ AccountTenantMembership membership =
+ fixture
+ .memberships()
+ .findCanonicalMembershipForUpdate(fixture.accountUuid(), fixture.tenantUuid())
+ .orElseThrow();
+ membership.setLifecycleState("ACTIVE");
+ membership.setGameplayAdmissionAllowed(true);
+ membership.setMembershipVersion(3L);
+ membership.setMembershipAuthorityGeneration(1L);
+ membership.setAuthorityProvenance("EXPLICIT_JOIN");
+ AccountTenantMembership persisted =
+ fixture
+ .memberships()
+ .saveCanonical(
+ membership, fixture.accountUuid(), fixture.tenantUuid(), provenance);
+ fixture
+ .roles()
+ .replaceCanonical(
+ persisted,
+ fixture.accountUuid(),
+ fixture.tenantUuid(),
+ provenance,
+ 3L,
+ List.of("player", "tenantAdmin"));
+
+ PairAuthority priorPair =
+ fixture
+ .pairAuthority()
+ .readForUpdate(fixture.accountUuid(), fixture.tenantUuid())
+ .orElseThrow();
+ String requestId = UUID.randomUUID().toString();
+ String eventId =
+ UUID.nameUUIDFromBytes(
+ (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId)
+ .getBytes(StandardCharsets.UTF_8))
+ .toString();
+ String streamKey = membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid());
+ Map preimage = new LinkedHashMap<>();
+ preimage.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION);
+ preimage.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE);
+ preimage.put("eventId", eventId);
+ preimage.put("requestId", requestId);
+ preimage.put("outboxStreamKey", streamKey);
+ preimage.put("outboxSequence", "2");
+ preimage.put(
+ "sourceScope", "membership/" + fixture.accountUuid() + "/" + fixture.tenantUuid());
+ preimage.put("accountId", fixture.accountUuid().toString());
+ preimage.put("tenantId", fixture.tenantUuid().toString());
+ preimage.put("membershipExists", true);
+ preimage.put("membershipLifecycleState", "ACTIVE");
+ preimage.put("membershipVersion", Map.of(fixture.tenantUuid().toString(), "3"));
+ preimage.put("membershipAuthorityGeneration", "1");
+ preimage.put(
+ "authorityTuple",
+ AccountTenantCreationBootstrapDigest.authorityTupleMap(
+ originalEvent.authorityTuple()));
+ preimage.put("issuanceFence", originalEvent.issuanceFence());
+ preimage.put("roles", List.of("player", "tenantAdmin"));
+ preimage.put("gameplayAdmissionAllowed", true);
+ preimage.put("callerBoundAuthorityInvalidated", false);
+ MembershipEvent laterEvent = MembershipAuthorityEventV1Codec.seal(preimage);
+ AccountAuthorityOutboxRepository.Event laterOutboxEvent =
+ fixture
+ .outbox()
+ .append(
+ streamKey,
+ requestId,
+ sequence -> {
+ if (sequence != 2L) {
+ throw new IllegalStateException(
+ "Later membership event sequence differs");
+ }
+ return new AccountAuthorityOutboxRepository.EventEvidence(
+ laterEvent.eventId(),
+ laterEvent.eventDigest(),
+ laterEvent.canonicalJsonUtf8());
+ });
+ fixture
+ .pairAuthority()
+ .commitTransition(
+ priorPair,
+ new PairTransition(
+ true, 2L, laterOutboxEvent.eventId(), laterOutboxEvent.eventDigest(), false));
+ return null;
+ });
+ }
+
+ private static CurrentState currentState(Fixture fixture) {
+ return inTransaction(
+ fixture,
+ () -> {
+ AccountTenantMembership membership =
+ fixture
+ .memberships()
+ .findCanonicalMembershipForUpdate(fixture.accountUuid(), fixture.tenantUuid())
+ .orElseThrow();
+ VerifiedTenantProvenance provenance = provenance(fixture.evidence().creationEvidence());
+ var roles =
+ fixture
+ .roles()
+ .findForCanonicalUpdate(
+ fixture.accountUuid(),
+ fixture.tenantUuid(),
+ provenance,
+ membership.getId(),
+ membership.getMembershipVersion())
+ .orElseThrow();
+ PairAuthority pair =
+ fixture
+ .pairAuthority()
+ .readForUpdate(fixture.accountUuid(), fixture.tenantUuid())
+ .orElseThrow();
+ return new CurrentState(membership, roles.roles(), pair);
+ });
+ }
+
+ private static Fixture fixture(boolean failAfterAudit) {
+ String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setUrl(postgres.getJdbcUrl());
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ dataSource.setSchema(schema);
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations("classpath:db/migration")
+ .load()
+ .migrate();
+ DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ DSLContext txDsl =
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ TransactionTemplate transaction =
+ new TransactionTemplate(new DataSourceTransactionManager(dataSource));
+
+ String suffix = UUID.randomUUID().toString().replace("-", "");
+ var accountRow =
+ setupDsl
+ .resultQuery(
+ "INSERT INTO accounts (username, email, password_hash) "
+ + "VALUES (?, ?, ?) RETURNING account_uuid",
+ "creator-bootstrap-" + suffix.substring(0, 16),
+ "creator-bootstrap-" + suffix + "@example.test",
+ "test-hash")
+ .fetchOne();
+ UUID accountUuid =
+ java.util.Objects.requireNonNull(accountRow, "Creator Account insert returned no row")
+ .get("account_uuid", UUID.class);
+ UUID tenantUuid = UUID.randomUUID();
+
+ AccountRepository accounts = new AccountRepository(txDsl);
+ LegacyTenantSourceEvidence legacySource = new LegacyTenantSourceEvidence(txDsl);
+ AccountAuthorityGenerationRepository generations =
+ new AccountAuthorityGenerationRepository(txDsl);
+ ApprovedLegacyTenantAssociationRepository approved =
+ new ApprovedLegacyTenantAssociationRepository(
+ txDsl, legacySource, TEST_NAMESPACE, generations);
+ AccountTenantIdentityResolver resolver =
+ new AccountTenantIdentityResolver(approved, legacySource, TEST_NAMESPACE);
+ FreshTenantIdentityAssociationRepository fresh =
+ new FreshTenantIdentityAssociationRepository(txDsl, TEST_NAMESPACE);
+ AccountTenantMembershipRepository memberships =
+ new AccountTenantMembershipRepository(txDsl, accounts, resolver, fresh);
+ AccountTenantMembershipRoleSnapshotRepository roles =
+ new AccountTenantMembershipRoleSnapshotRepository(txDsl);
+ AccountMembershipPairAuthorityRepository pairs =
+ new AccountMembershipPairAuthorityRepository(txDsl);
+ AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(txDsl);
+ AccountAuditOutboxRepository audit = new AccountAuditOutboxRepository(txDsl);
+ AccountConnectScopeRepository connectScopes =
+ new AccountConnectScopeRepository(txDsl, accounts, resolver, fresh);
+ AccountJoinOperationRepository joinOperations =
+ new AccountJoinOperationRepository(txDsl, connectScopes);
+ AccountPasswordResetOperationRepository passwordResets =
+ new AccountPasswordResetOperationRepository(txDsl);
+ AccountLogoutAllOperationRepository logoutAll = new AccountLogoutAllOperationRepository(txDsl);
+ AccountMembershipTransitionReceiptRepository transitionReceipts =
+ new AccountMembershipTransitionReceiptRepository(txDsl);
+ AccountTenantRoleOperationRepository roleOperations =
+ new AccountTenantRoleOperationRepository(txDsl);
+ AccountMembershipAuthorityEventProducer producer =
+ new AccountMembershipAuthorityEventProducer(
+ joinOperations,
+ pairs,
+ accounts,
+ resolver,
+ fresh,
+ generations,
+ outbox,
+ passwordResets,
+ logoutAll,
+ transitionReceipts,
+ memberships,
+ roles,
+ audit,
+ roleOperations);
+
+ FreshTenantCreatorEvidence evidence = creatorEvidence(accountUuid, tenantUuid);
+ setupDsl.execute(
+ "INSERT INTO account_authority_generations "
+ + "(scope_kind, account_uuid, generation, source_version) VALUES ('ACCOUNT', ?, 1, 1)",
+ accountUuid);
+ setupDsl.execute(
+ "INSERT INTO account_authority_issuance_fences "
+ + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)",
+ accountUuid);
+ transaction.executeWithoutResult(
+ status -> {
+ fresh.importVerified(evidence.creationEvidence());
+ generations.initializeTenantIfAbsent(tenantUuid);
+ generations.initializeIssuerIfAbsent(AccountServiceImpl.ACCOUNT_JWT_ISSUER);
+ });
+
+ AccountTenantCreationBootstrapOperationRepository operationRepository =
+ failAfterAudit
+ ? new FailingAfterAuditOperationRepository(txDsl)
+ : new AccountTenantCreationBootstrapOperationRepository(txDsl);
+ AccountTenantCreationBootstrapAuthorizationSource syntheticParticipant =
+ syntheticParticipant(evidence);
+ @SuppressWarnings("unchecked")
+ ObjectProvider provider =
+ mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(syntheticParticipant);
+ AccountTenantCreationBootstrapService service =
+ new AccountTenantCreationBootstrapService(
+ accounts,
+ fresh,
+ producer,
+ pairs,
+ memberships,
+ roles,
+ outbox,
+ audit,
+ operationRepository,
+ provider);
+ return new Fixture(
+ setupDsl,
+ transaction,
+ accountUuid,
+ tenantUuid,
+ evidence,
+ service,
+ memberships,
+ roles,
+ pairs,
+ outbox,
+ operationRepository);
+ }
+
+ private static FreshTenantCreatorEvidence creatorEvidence(UUID accountUuid, UUID tenantUuid) {
+ UUID creationRequestId = UUID.randomUUID();
+ UUID creationOperationId = UUID.randomUUID();
+ UUID authorizationOperationId = UUID.randomUUID();
+ String tenantKey = "creator-game-row-17";
+ String requestDigest =
+ GameTenantCreationDigest.requestDigest(
+ TEST_NAMESPACE, creationRequestId, tenantKey, "Creator fixture", null);
+ FreshTenantCreationEvidence creation =
+ new FreshTenantCreationEvidence(
+ 1,
+ TEST_NAMESPACE,
+ creationRequestId,
+ creationOperationId,
+ requestDigest,
+ tenantUuid,
+ 17L,
+ tenantKey,
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ TEST_NAMESPACE,
+ creationRequestId,
+ creationOperationId,
+ requestDigest,
+ tenantUuid,
+ 17L,
+ tenantKey,
+ "NEW_GAME_ROW"));
+ String authorizationDigest = "sha256:" + "8".repeat(64);
+ return new FreshTenantCreatorEvidence(
+ 1,
+ creation,
+ accountUuid,
+ authorizationOperationId,
+ authorizationDigest,
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, creation, accountUuid, authorizationOperationId, authorizationDigest));
+ }
+
+ private static AccountTenantCreationBootstrapAuthorizationSource syntheticParticipant(
+ FreshTenantCreatorEvidence expectedEvidence) {
+ ReentrantLock syntheticSourceFence = new ReentrantLock();
+ return (supplied, mutation) -> {
+ if (!expectedEvidence.equals(supplied)) {
+ throw new IllegalStateException("Synthetic component fixture source differs");
+ }
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || !TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(
+ "Synthetic source participant requires the outer Account transaction");
+ }
+ syntheticSourceFence.lock();
+ TransactionSynchronizationManager.registerSynchronization(
+ new TransactionSynchronization() {
+ @Override
+ public void afterCompletion(int status) {
+ syntheticSourceFence.unlock();
+ }
+ });
+ AccountTenantCreationBootstrapResult result = mutation.get();
+ if (!syntheticSourceFence.isHeldByCurrentThread()) {
+ throw new IllegalStateException(
+ "Synthetic source participant released its fence before Account completion");
+ }
+ return result;
+ };
+ }
+
+ private static VerifiedTenantProvenance provenance(FreshTenantCreationEvidence source) {
+ return new VerifiedTenantProvenance(
+ null,
+ TenantProvenanceKind.FRESH_GAME_DESIGN,
+ source.operationId(),
+ source.evidenceDigest());
+ }
+
+ private static String membershipStreamKey(UUID accountUuid, UUID tenantUuid) {
+ return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + accountUuid
+ + "/"
+ + tenantUuid;
+ }
+
+ private static UUID auditEventId(UUID authorizationOperationId) {
+ return UUID.nameUUIDFromBytes(
+ ("account-tenant-creation-bootstrap-audit/v1:" + authorizationOperationId)
+ .getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static long count(DSLContext dsl, String table, String column, UUID value) {
+ return countQuery(dsl, "SELECT count(*) FROM " + table + " WHERE " + column + " = ?", value);
+ }
+
+ private static long countQuery(DSLContext dsl, String query, Object... bindings) {
+ return java.util.Objects.requireNonNull(
+ java.util.Objects.requireNonNull(
+ dsl.fetchOne(query, bindings), "Count query returned no row")
+ .get(0, Long.class),
+ "Count query returned no value");
+ }
+
+ private static T inTransaction(Fixture fixture, java.util.function.Supplier work) {
+ return fixture.transaction().execute(status -> work.get());
+ }
+
+ private record CurrentState(
+ AccountTenantMembership membership, List roles, PairAuthority pair) {}
+
+ private record Fixture(
+ DSLContext setupDsl,
+ TransactionTemplate transaction,
+ UUID accountUuid,
+ UUID tenantUuid,
+ FreshTenantCreatorEvidence evidence,
+ AccountTenantCreationBootstrapService service,
+ AccountTenantMembershipRepository memberships,
+ AccountTenantMembershipRoleSnapshotRepository roles,
+ AccountMembershipPairAuthorityRepository pairAuthority,
+ AccountAuthorityOutboxRepository outbox,
+ AccountTenantCreationBootstrapOperationRepository operationRepository) {}
+
+ private static final class FailingAfterAuditOperationRepository
+ extends AccountTenantCreationBootstrapOperationRepository {
+ private FailingAfterAuditOperationRepository(DSLContext dsl) {
+ super(dsl);
+ }
+
+ @Override
+ public StoredOperation complete(UUID requestId, Completion completion) {
+ throw new IllegalStateException("injected after Account audit append");
+ }
+ }
+}
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationProvenancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationProvenancePostgresIntegrationTest.java
new file mode 100644
index 0000000000..799f446dd8
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationProvenancePostgresIntegrationTest.java
@@ -0,0 +1,324 @@
+package integration.net.firedevops.firemud.accountservice;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Map;
+import java.util.UUID;
+import javax.sql.DataSource;
+import org.flywaydb.core.Flyway;
+import org.flywaydb.core.api.MigrationVersion;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+@Testcontainers(disabledWithoutDocker = true)
+class AccountTenantCreationProvenancePostgresIntegrationTest {
+ private static final String HISTORY_TABLE = "flyway_schema_history_tenant_creation_provenance";
+ private static final String DIGEST = "sha256:" + "1".repeat(64);
+
+ @Container
+ static PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
+
+ @Test
+ void forwardMigrationPreservesRetainedStateAndAllowsOnlyControlOnlyCreatorShape()
+ throws Exception {
+ Database database = newDatabase();
+ flyway(database, "25").migrate();
+
+ AccountRow retained = insertAccount(database.dataSource(), "retained");
+ long retainedMembershipId = insertLegacyMembership(database.dataSource(), retained.id(), 41L);
+ AccountRow absent = insertAccount(database.dataSource(), "without-membership");
+ Map oldMembershipBefore =
+ row(
+ database.dataSource(),
+ "SELECT id, account_id, tenant_id, gameplay_admission_allowed "
+ + "FROM account_tenant_membership WHERE id = "
+ + retainedMembershipId);
+
+ flyway(database, null).migrate();
+
+ Map retainedAfter =
+ row(
+ database.dataSource(),
+ "SELECT id, account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, "
+ + "membership_version, membership_authority_generation, authority_provenance, "
+ + "tenant_provenance_kind, tenant_uuid FROM account_tenant_membership WHERE id = "
+ + retainedMembershipId);
+ assertThat(retainedAfter)
+ .containsEntry("id", retainedMembershipId)
+ .containsEntry("account_id", retained.id())
+ .containsEntry("tenant_id", 41L)
+ .containsEntry("gameplay_admission_allowed", false)
+ .containsEntry("lifecycle_state", "LEGACY_UNVERIFIED")
+ .containsEntry("membership_version", 1L)
+ .containsEntry("membership_authority_generation", 1L)
+ .containsEntry("authority_provenance", "LEGACY_UNVERIFIED")
+ .containsEntry("tenant_provenance_kind", "UNBRIDGED_RETAINED")
+ .containsEntry("tenant_uuid", null);
+ assertThat(oldMembershipBefore)
+ .containsEntry("id", retainedMembershipId)
+ .containsEntry("account_id", retained.id())
+ .containsEntry("tenant_id", 41L);
+ assertThat(
+ scalarLong(
+ database.dataSource(),
+ "SELECT COUNT(*) FROM account_legacy_membership_sources "
+ + "WHERE membership_id = "
+ + retainedMembershipId))
+ .isEqualTo(1L);
+ assertThat(
+ scalarLong(
+ database.dataSource(),
+ "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = " + absent.id()))
+ .isZero();
+
+ UUID tenantUuid = UUID.randomUUID();
+ UUID operationId = UUID.randomUUID();
+ insertSyntheticFreshTenantIdentity(database.dataSource(), tenantUuid, operationId);
+ long creatorMembershipId =
+ insertSyntheticCreatorMembership(
+ database.dataSource(), absent.id(), tenantUuid, operationId);
+ assertThat(
+ row(
+ database.dataSource(),
+ "SELECT account_id, tenant_id, tenant_uuid, tenant_provenance_kind, "
+ + "tenant_source_operation_id, tenant_provenance_digest, lifecycle_state, "
+ + "membership_version, membership_authority_generation, authority_provenance, "
+ + "gameplay_admission_allowed FROM account_tenant_membership WHERE id = "
+ + creatorMembershipId))
+ .containsEntry("account_id", absent.id())
+ .containsEntry("tenant_id", null)
+ .containsEntry("tenant_uuid", tenantUuid)
+ .containsEntry("tenant_provenance_kind", "FRESH_GAME_DESIGN")
+ .containsEntry("tenant_source_operation_id", operationId)
+ .containsEntry("tenant_provenance_digest", DIGEST)
+ .containsEntry("lifecycle_state", "ACTIVE")
+ .containsEntry("membership_version", 1L)
+ .containsEntry("membership_authority_generation", 1L)
+ .containsEntry("authority_provenance", "TENANT_CREATION")
+ .containsEntry("gameplay_admission_allowed", false);
+
+ assertConstraintRejects(
+ database.dataSource(),
+ "UPDATE account_tenant_membership SET gameplay_admission_allowed = TRUE " + "WHERE id = ?",
+ "account_membership_tenant_creation_not_admitting_check",
+ creatorMembershipId);
+ assertConstraintRejects(
+ database.dataSource(),
+ "INSERT INTO account_tenant_membership "
+ + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, "
+ + "membership_version, membership_authority_generation, authority_provenance) "
+ + "VALUES (?, 42, TRUE, 'LEGACY_UNVERIFIED', 1, 1, "
+ + "'LEGACY_UNVERIFIED')",
+ "account_membership_unverified_not_admitting_check",
+ absent.id());
+ assertConstraintRejects(
+ database.dataSource(),
+ "INSERT INTO account_tenant_membership "
+ + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, "
+ + "membership_version, membership_authority_generation, authority_provenance) "
+ + "VALUES (?, 43, FALSE, 'ACTIVE', 1, 1, 'NOT_A_PROVENANCE')",
+ "account_membership_provenance_check",
+ absent.id());
+ assertConstraintRejects(
+ database.dataSource(),
+ "INSERT INTO account_tenant_membership "
+ + "(account_id, tenant_uuid, tenant_provenance_kind, tenant_source_operation_id, "
+ + "tenant_provenance_digest, gameplay_admission_allowed, lifecycle_state, "
+ + "membership_version, membership_authority_generation, authority_provenance) "
+ + "VALUES (?, ?, 'FRESH_GAME_DESIGN', ?, ?, FALSE, 'ACTIVE', 1, 1, 'TENANT_CREATION')",
+ "Account membership tenant identity has no exact immutable source",
+ absent.id(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ DIGEST);
+
+ assertThat(
+ scalarLong(
+ database.dataSource(),
+ "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = " + absent.id()))
+ .isEqualTo(1L);
+ assertThat(
+ row(
+ database.dataSource(),
+ "SELECT authority_provenance, gameplay_admission_allowed "
+ + "FROM account_tenant_membership WHERE id = "
+ + creatorMembershipId))
+ .containsEntry("authority_provenance", "TENANT_CREATION")
+ .containsEntry("gameplay_admission_allowed", false);
+ }
+
+ private static Flyway flyway(Database database, String target) {
+ var configuration =
+ Flyway.configure()
+ .dataSource(database.dataSource())
+ .schemas(database.schema())
+ .defaultSchema(database.schema())
+ .table(HISTORY_TABLE)
+ .placeholders(Map.of("serviceSchema", database.schema()))
+ .locations("classpath:db/migration");
+ if (target != null) {
+ configuration.target(MigrationVersion.fromVersion(target));
+ }
+ return configuration.load();
+ }
+
+ private static Database newDatabase() throws SQLException {
+ String schema = "account_tenant_creation_" + UUID.randomUUID().toString().replace("-", "");
+ String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?";
+ DriverManagerDataSource dataSource =
+ new DriverManagerDataSource(
+ postgres.getJdbcUrl() + separator + "currentSchema=" + schema,
+ postgres.getUsername(),
+ postgres.getPassword());
+ dataSource.setDriverClassName("org.postgresql.Driver");
+ try (Connection connection = dataSource.getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("CREATE SCHEMA " + schema);
+ }
+ return new Database(schema, dataSource);
+ }
+
+ private static AccountRow insertAccount(DataSource dataSource, String label) throws SQLException {
+ try (Connection connection = dataSource.getConnection();
+ var statement =
+ connection.prepareStatement(
+ "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) "
+ + "RETURNING id")) {
+ String suffix = UUID.randomUUID().toString().replace("-", "");
+ statement.setString(1, label + "-" + suffix);
+ statement.setString(2, label + "-" + suffix + "@example.com");
+ statement.setString(3, "test-hash");
+ try (var result = statement.executeQuery()) {
+ assertThat(result.next()).isTrue();
+ return new AccountRow(result.getLong("id"));
+ }
+ }
+ }
+
+ private static long insertLegacyMembership(DataSource dataSource, long accountId, long tenantId)
+ throws SQLException {
+ try (Connection connection = dataSource.getConnection();
+ var statement =
+ connection.prepareStatement(
+ "INSERT INTO account_tenant_membership "
+ + "(account_id, tenant_id, gameplay_admission_allowed) VALUES (?, ?, TRUE) "
+ + "RETURNING id")) {
+ statement.setLong(1, accountId);
+ statement.setLong(2, tenantId);
+ try (var result = statement.executeQuery()) {
+ assertThat(result.next()).isTrue();
+ return result.getLong(1);
+ }
+ }
+ }
+
+ private static void insertSyntheticFreshTenantIdentity(
+ DataSource dataSource, UUID tenantUuid, UUID operationId) throws SQLException {
+ UUID creationRequestId = UUID.randomUUID();
+ String namespace = "firemud-test";
+ String tenantKey = "synthetic-" + UUID.randomUUID().toString().substring(0, 8);
+ long gameRowId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
+ if (gameRowId == 0) {
+ gameRowId = 1;
+ }
+ try (Connection connection = dataSource.getConnection()) {
+ execute(
+ connection,
+ "INSERT INTO account_fresh_tenant_identity_associations "
+ + "(schema_version, target_namespace, creation_request_id, operation_id, "
+ + "request_digest, canonical_tenant_id, source_game_row_id, "
+ + "source_game_tenant_key, provenance_kind, evidence_digest) "
+ + "VALUES (1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)",
+ namespace,
+ creationRequestId,
+ operationId,
+ DIGEST,
+ tenantUuid,
+ gameRowId,
+ tenantKey,
+ DIGEST);
+ }
+ }
+
+ private static long insertSyntheticCreatorMembership(
+ DataSource dataSource, long accountId, UUID tenantUuid, UUID operationId)
+ throws SQLException {
+ try (Connection connection = dataSource.getConnection();
+ var statement =
+ connection.prepareStatement(
+ "INSERT INTO account_tenant_membership "
+ + "(account_id, tenant_uuid, tenant_provenance_kind, "
+ + "tenant_source_operation_id, tenant_provenance_digest, "
+ + "gameplay_admission_allowed, lifecycle_state, membership_version, "
+ + "membership_authority_generation, authority_provenance) "
+ + "VALUES (?, ?, 'FRESH_GAME_DESIGN', ?, ?, FALSE, 'ACTIVE', 1, 1, "
+ + "'TENANT_CREATION') RETURNING id")) {
+ statement.setLong(1, accountId);
+ statement.setObject(2, tenantUuid);
+ statement.setObject(3, operationId);
+ statement.setString(4, DIGEST);
+ try (var result = statement.executeQuery()) {
+ assertThat(result.next()).isTrue();
+ return result.getLong(1);
+ }
+ }
+ }
+
+ private static Map row(DataSource dataSource, String sql) throws SQLException {
+ try (Connection connection = dataSource.getConnection();
+ var statement = connection.createStatement();
+ var result = statement.executeQuery(sql)) {
+ assertThat(result.next()).isTrue();
+ var metadata = result.getMetaData();
+ var row = new java.util.LinkedHashMap();
+ for (int column = 1; column <= metadata.getColumnCount(); column++) {
+ row.put(metadata.getColumnLabel(column), result.getObject(column));
+ }
+ return row;
+ }
+ }
+
+ private static long scalarLong(DataSource dataSource, String sql) throws SQLException {
+ try (Connection connection = dataSource.getConnection();
+ var statement = connection.createStatement();
+ var result = statement.executeQuery(sql)) {
+ assertThat(result.next()).isTrue();
+ return result.getLong(1);
+ }
+ }
+
+ private static void assertConstraintRejects(
+ DataSource dataSource, String sql, String expected, Object... values) throws SQLException {
+ try (Connection connection = dataSource.getConnection()) {
+ connection.setAutoCommit(false);
+ assertThatThrownBy(
+ () -> {
+ execute(connection, sql, values);
+ })
+ .isInstanceOf(SQLException.class)
+ .hasMessageContaining(expected);
+ connection.rollback();
+ }
+ }
+
+ private static void execute(Connection connection, String sql, Object... values)
+ throws SQLException {
+ try (var statement = connection.prepareStatement(sql)) {
+ for (int index = 0; index < values.length; index++) {
+ statement.setObject(index + 1, values[index]);
+ }
+ statement.executeUpdate();
+ }
+ }
+
+ private record Database(String schema, DataSource dataSource) {}
+
+ private record AccountRow(long id) {}
+}
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java
new file mode 100644
index 0000000000..1da0e8e19d
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java
@@ -0,0 +1,255 @@
+package integration.net.firedevops.firemud.accountservice.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.time.Clock;
+import java.time.ZoneOffset;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourceRepository;
+import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback;
+import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiTokenChecks.InspectedToken;
+import org.flywaydb.core.Flyway;
+import org.flywaydb.core.api.MigrationVersion;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionTemplate;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/**
+ * Real SQL source/lock proof only. Signed records and authority enrollment are explicit fixtures;
+ * this is not Account-issued credential, retained signer, Redis, bundle or creator activation
+ * proof.
+ */
+@Testcontainers(disabledWithoutDocker = true)
+class AccountControlUiCurrentSourcePostgresIntegrationTest {
+ private static final String ISSUER = "firemud-account-service";
+
+ @Container
+ static PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
+
+ @Test
+ void currentFreshSourceIsObservedAtOneOwnerTransactionWithoutEnrollmentOrMutation()
+ throws Exception {
+ Fixture fixture = fixture(true);
+ var candidate = candidate(fixture.accountId());
+ Long generationsBefore = count(fixture.dsl(), "account_authority_generations");
+ var observation =
+ fixture.tx().execute(status -> fixture.source().inspectUnscopedCurrent(candidate));
+ assertThat(observation).isNotNull();
+ assertThat(observation.accountId()).isEqualTo(fixture.accountId());
+ assertThat(observation.authority().issuer().generation()).isEqualTo(1L);
+ assertThat(observation.accountSource().sourceState().generation()).isEqualTo(1L);
+ assertThat(observation.globalRoleSourceVersion()).isEqualTo(1L);
+ assertThat(observation.toString()).contains("non-authorizing");
+ assertThat(count(fixture.dsl(), "account_authority_generations")).isEqualTo(generationsBefore);
+ assertThat(count(fixture.dsl(), "account_authority_outbox_events")).isZero();
+ assertThat(count(fixture.dsl(), "account_global_role_sources")).isEqualTo(1L);
+ }
+
+ @Test
+ void missingAuthorityFailsWithoutInventingAnInitialGeneration() throws Exception {
+ Fixture fixture = fixture(false);
+ var candidate = candidate(fixture.accountId());
+ assertThatThrownBy(
+ () ->
+ fixture.tx().execute(status -> fixture.source().inspectUnscopedCurrent(candidate)))
+ .isInstanceOf(IllegalStateException.class);
+ assertThat(count(fixture.dsl(), "account_authority_generations")).isZero();
+ assertThat(count(fixture.dsl(), "account_authority_issuance_fences")).isZero();
+ assertThat(count(fixture.dsl(), "account_authority_outbox_events")).isZero();
+ }
+
+ @Test
+ void absentOwnerTransactionAndReadOnlyTransactionCannotProduceObservation() throws Exception {
+ Fixture fixture = fixture(true);
+ var candidate = candidate(fixture.accountId());
+ assertThatThrownBy(() -> fixture.source().inspectUnscopedCurrent(candidate))
+ .isInstanceOf(IllegalStateException.class);
+ TransactionTemplate readOnly = new TransactionTemplate(fixture.tx().getTransactionManager());
+ readOnly.setReadOnly(true);
+ assertThatThrownBy(
+ () -> readOnly.execute(status -> fixture.source().inspectUnscopedCurrent(candidate)))
+ .isInstanceOf(IllegalStateException.class);
+ }
+
+ @Test
+ void committedIssuerAdvanceRejectsThePriorExactSignedAndActiveRecord() throws Exception {
+ Fixture fixture = fixture(true);
+ var candidate = candidate(fixture.accountId());
+ fixture
+ .tx()
+ .execute(
+ status -> {
+ var old = fixture.generations().read(AuthorityScope.issuer(ISSUER));
+ return fixture.generations().advance(old, null);
+ });
+ assertThatThrownBy(
+ () ->
+ fixture.tx().execute(status -> fixture.source().inspectUnscopedCurrent(candidate)))
+ .isInstanceOf(IllegalStateException.class);
+ assertThat(count(fixture.dsl(), "account_authority_outbox_events")).isZero();
+ }
+
+ @Test
+ void concurrentIssuerAdvanceSerializesOnTheObservationCompositeFence() throws Exception {
+ Fixture fixture = fixture(true);
+ var candidate = candidate(fixture.accountId());
+ CountDownLatch observationLocked = new CountDownLatch(1);
+ CountDownLatch releaseObservation = new CountDownLatch(1);
+ CountDownLatch advanceEntered = new CountDownLatch(1);
+ try (var executor = Executors.newFixedThreadPool(2)) {
+ var observed =
+ executor.submit(
+ () ->
+ fixture
+ .tx()
+ .execute(
+ status -> {
+ var result = fixture.source().inspectUnscopedCurrent(candidate);
+ observationLocked.countDown();
+ await(releaseObservation);
+ return result;
+ }));
+ assertThat(observationLocked.await(10L, TimeUnit.SECONDS)).isTrue();
+ var advanced =
+ executor.submit(
+ () ->
+ fixture
+ .tx()
+ .execute(
+ status -> {
+ advanceEntered.countDown();
+ var old = fixture.generations().read(AuthorityScope.issuer(ISSUER));
+ return fixture.generations().advance(old, null);
+ }));
+ assertThat(advanceEntered.await(10L, TimeUnit.SECONDS)).isTrue();
+ try {
+ assertThatThrownBy(() -> advanced.get(150L, TimeUnit.MILLISECONDS))
+ .isInstanceOf(TimeoutException.class);
+ } finally {
+ releaseObservation.countDown();
+ }
+ assertThat(observed.get(10L, TimeUnit.SECONDS).authority().issuer().generation())
+ .isEqualTo(1L);
+ assertThat(advanced.get(10L, TimeUnit.SECONDS).generation()).isEqualTo(2L);
+ assertThatThrownBy(
+ () ->
+ fixture
+ .tx()
+ .execute(status -> fixture.source().inspectUnscopedCurrent(candidate)))
+ .isInstanceOf(IllegalStateException.class);
+ } finally {
+ releaseObservation.countDown();
+ }
+ }
+
+ private static InspectedToken candidate(UUID accountId) throws Exception {
+ var crypto =
+ new AccountControlUiTokenFixture(
+ Clock.fixed(AccountControlUiTokenFixture.NOW, ZoneOffset.UTC));
+ var claims = crypto.claims(accountId);
+ String token = crypto.sign(claims);
+ return crypto
+ .checks()
+ .inspect(
+ "fresh-creator-candidate",
+ token,
+ AccountControlUiTokenFixture.canonical(crypto.registry(token, claims)),
+ AccountControlUiTokenFixture.unscopedShape());
+ }
+
+ private static Fixture fixture(boolean enrollAuthority) {
+ String schema = "control_ui_source_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?";
+ dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema);
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations("classpath:db/migration")
+ .target(MigrationVersion.fromVersion("55"))
+ .load()
+ .migrate();
+ DSLContext dsl =
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ var accounts = new AccountRepository(dsl);
+ Account account = new Account();
+ account.setUsername("control_ui_source");
+ account.setEmail("control-ui-source@example.test");
+ account.setPasswordHash("test-only-not-a-credential-proof");
+ accounts.save(account);
+ var generations = new AccountAuthorityGenerationRepository(dsl);
+ TransactionTemplate tx = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
+ tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ if (enrollAuthority)
+ tx.execute(
+ status -> {
+ generations.initializeIssuerIfAbsent(ISSUER);
+ return generations.initialize(AuthorityScope.account(account.getAccountUuid()));
+ });
+ var outbox = new AccountAuthorityOutboxRepository(dsl);
+ var readback =
+ new AccountAuthoritySourceEventReadback(
+ outbox,
+ new AccountPasswordResetOperationRepository(dsl),
+ new AccountLogoutAllOperationRepository(dsl));
+ var source =
+ new AccountControlUiCurrentSourceRepository(
+ dsl,
+ accounts,
+ new AccountGlobalRoleSourceRepository(dsl, dataSource),
+ generations,
+ readback);
+ return new Fixture(dsl, tx, account.getAccountUuid(), generations, source);
+ }
+
+ private static Long count(DSLContext dsl, String table) {
+ return java.util.Objects.requireNonNull(
+ dsl.fetchOne("SELECT COUNT(*) AS row_count FROM " + table),
+ "Count query returned no row")
+ .get("row_count", Long.class);
+ }
+
+ private static void await(CountDownLatch latch) {
+ try {
+ if (!latch.await(10L, TimeUnit.SECONDS))
+ throw new IllegalStateException("Fixture latch timed out");
+ } catch (InterruptedException failure) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Fixture was interrupted", failure);
+ }
+ }
+
+ private record Fixture(
+ DSLContext dsl,
+ TransactionTemplate tx,
+ UUID accountId,
+ AccountAuthorityGenerationRepository generations,
+ AccountControlUiCurrentSourceRepository source) {}
+}
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiTokenFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiTokenFixture.java
new file mode 100644
index 0000000000..09b2cf9622
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiTokenFixture.java
@@ -0,0 +1,254 @@
+package integration.net.firedevops.firemud.accountservice.repository;
+
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.MessageDigest;
+import java.security.Signature;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.AuthorityMapShape;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ClaimFieldPresence;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ControlUiShape;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.DeploymentCeilings;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ProfileLimits;
+import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiTokenChecks;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache;
+
+/**
+ * Integration-source-set-local signed records; these prove verification composition only, not
+ * Account issuance or signer custody.
+ */
+final class AccountControlUiTokenFixture {
+ static final Instant NOW = Instant.parse("2026-10-06T10:00:00Z");
+ private static final String KID = "control-ui-test-key";
+ private static final JsonMapper JSON = JsonMapper.builder().build();
+ private final KeyPair keys;
+ private final Clock clock;
+
+ AccountControlUiTokenFixture(Clock clock) throws Exception {
+ this.clock = clock;
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(3072);
+ this.keys = generator.generateKeyPair();
+ }
+
+ AccountControlUiTokenChecks checks() {
+ var pin =
+ new AccountPublicJwksCache.SourceIdentity(
+ "test",
+ "cluster-test",
+ "11111111-1111-4111-8111-111111111111",
+ "firemud-test",
+ "22222222-2222-4222-8222-222222222222",
+ "33333333-3333-4333-8333-333333333333",
+ "binding-test",
+ "https://kubernetes.example:6443",
+ "a".repeat(64));
+ RSAPublicKey key = (RSAPublicKey) keys.getPublic();
+ String jwks =
+ "{\"keys\":[{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\""
+ + KID
+ + "\",\"n\":\""
+ + unsigned(key.getModulus().toByteArray())
+ + "\",\"e\":\""
+ + unsigned(key.getPublicExponent().toByteArray())
+ + "\"}]}";
+ var cache =
+ new AccountPublicJwksCache(
+ () ->
+ new AccountPublicJwksCache.PublicJwksSnapshot(
+ pin, jwks.getBytes(StandardCharsets.UTF_8)),
+ pin,
+ clock,
+ Duration.ofSeconds(30));
+ return new AccountControlUiTokenChecks(
+ new AccountAsymmetricJwtVerifier(cache, clock), catalog(), clock);
+ }
+
+ Map claims(UUID accountId) {
+ Map claims = new LinkedHashMap<>();
+ claims.put("iss", "firemud-account-service");
+ claims.put("aud", "control-ui");
+ claims.put("sub", accountId.toString());
+ claims.put("accountId", accountId.toString());
+ claims.put("jti", UUID.randomUUID().toString());
+ claims.put("iat", NOW.getEpochSecond());
+ claims.put("nbf", NOW.getEpochSecond());
+ claims.put("exp", NOW.getEpochSecond() + 900L);
+ claims.put("tokenGeneration", "1");
+ claims.put("issuanceFence", "1");
+ claims.put("scopedRoles", Map.of());
+ claims.put(
+ "authorityTuple",
+ Map.of(
+ "issuerAuthGeneration",
+ "1",
+ "accountAuthorityGeneration",
+ "1",
+ "tenantAuthorityGeneration",
+ Map.of(),
+ "membershipAuthorityGeneration",
+ Map.of(),
+ "privateRealmGrantVersions",
+ List.of()));
+ claims.put("membershipVersion", Map.of());
+ return claims;
+ }
+
+ String sign(Map claims) throws Exception {
+ Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
+ String header =
+ encoder.encodeToString(
+ ("{\"alg\":\"RS256\",\"kid\":\"" + KID + "\",\"typ\":\"JWT\"}")
+ .getBytes(StandardCharsets.UTF_8));
+ // Preserve the signed JWT payload bytes instead of rewriting their JSON preimage.
+ String payload = encoder.encodeToString(JSON.writeValueAsBytes(claims));
+ Signature signer = Signature.getInstance("SHA256withRSA");
+ signer.initSign(keys.getPrivate());
+ signer.update((header + "." + payload).getBytes(StandardCharsets.US_ASCII));
+ return header + "." + payload + "." + encoder.encodeToString(signer.sign());
+ }
+
+ Map registry(String token, Map claims) throws Exception {
+ Map record = new LinkedHashMap<>();
+ record.put("schemaVersion", 2L);
+ record.put("registryVersion", 2L);
+ record.put(
+ "tokenHash",
+ HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(token.getBytes(StandardCharsets.US_ASCII))));
+ record.put("kid", KID);
+ record.put("signerGeneration", "1");
+ record.put("issuer", "firemud-account-service");
+ record.put("audience", "control-ui");
+ record.put("profile", "control-ui");
+ record.put("type", "control-ui");
+ record.put("operationId", UUID.randomUUID().toString());
+ record.put("requestId", UUID.randomUUID().toString());
+ record.put("requestDigest", "b".repeat(64));
+ record.put("state", "active");
+ for (String field :
+ List.of(
+ "accountId",
+ "jti",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence")) {
+ record.put(field, claims.get(field));
+ }
+ record.put(
+ "authoritySourceVersions",
+ Map.of(
+ "issuerSourceVersion",
+ 1L,
+ "accountSourceVersion",
+ 1L,
+ "issuanceFenceSourceVersion",
+ 1L));
+ record.put(
+ "authEvidenceBundle",
+ Map.of(
+ "bundleVersion",
+ "1",
+ "sourceVersion",
+ "1",
+ "linearization",
+ "123",
+ "canonicalSha256",
+ "c".repeat(64)));
+ return record;
+ }
+
+ static ControlUiShape unscopedShape() {
+ return shape(Set.of(), Set.of(), Set.of(), Set.of(), Set.of());
+ }
+
+ static ControlUiShape shape(
+ Set scopes,
+ Set roles,
+ Set tenants,
+ Set memberships,
+ Set billingSafe) {
+ return new ControlUiShape(
+ new ClaimFieldPresence(
+ true,
+ true,
+ true,
+ true,
+ "control-ui",
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false),
+ new AuthorityMapShape(tenants, memberships, memberships, Set.of(), List.of()),
+ scopes,
+ roles,
+ tenants,
+ memberships,
+ billingSafe,
+ Set.of());
+ }
+
+ static byte[] canonical(Object value) throws Exception {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value));
+ }
+
+ static byte[] exactJson(Object value) throws Exception {
+ return JSON.writeValueAsBytes(value);
+ }
+
+ private static AccountTokenProfileCatalog catalog() {
+ return new AccountTokenProfileCatalog(
+ AccountTokenProfileCatalog.VERSION,
+ Map.of(
+ "control-ui",
+ new ProfileLimits(
+ "control-ui", 1800, 4, 4, 4, 4, 0, 8192, 16384, 16384, Optional.of(4)),
+ "player-bootstrap",
+ new ProfileLimits(
+ "player-bootstrap", 300, 0, 0, 0, 0, 0, 8192, 16384, 16384, Optional.empty()),
+ "game-session-account-delegation",
+ new ProfileLimits(
+ "account-service", 300, 1, 1, 1, 1, 1, 8192, 16384, 16384, Optional.empty())),
+ new DeploymentCeilings(16384, 8192, 16384, 1800));
+ }
+
+ private static String unsigned(byte[] value) {
+ byte[] bytes =
+ value.length > 1 && value[0] == 0
+ ? java.util.Arrays.copyOfRange(value, 1, value.length)
+ : value;
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ }
+}
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java
new file mode 100644
index 0000000000..ee566af4d7
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java
@@ -0,0 +1,470 @@
+package integration.net.firedevops.firemud.accountservice.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import javax.sql.DataSource;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Claim;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.OperationConflictException;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry;
+import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
+import org.flywaydb.core.Flyway;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.transaction.support.TransactionTemplate;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/**
+ * Database-only storage proof for immutable creator-bootstrap receipts; synthetic evidence here is
+ * not proof of authenticated Account authorization or a production source participant.
+ */
+@Testcontainers(disabledWithoutDocker = true)
+class AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest {
+ private static final String SCHEMA_PREFIX = "creator_bootstrap_operation_proof_";
+ private static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED";
+
+ @Container
+ static PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
+
+ @Test
+ void exactImmutableInputReplaysOriginalReceiptAndChangedSnapshotConflicts() {
+ TestContext context = newTestContext();
+ FreshTenantCreatorEvidence evidence = evidence(UUID.randomUUID());
+ RequestInput input = input(evidence);
+ insertAccount(context.setupDsl(), evidence.initiatingAccountId());
+
+ StoredOperation committed =
+ inTransaction(
+ context.transaction(),
+ () -> {
+ Claim claim = claim(context.repository(), input);
+ assertThat(claim.claimed()).isTrue();
+ return context
+ .repository()
+ .complete(evidence.accountAuthorizationOperationId(), completion(evidence));
+ });
+
+ assertThat(committed.status()).isEqualTo("COMMITTED");
+ assertThat(committed.result().roles()).containsExactly("tenantAdmin");
+ assertThat(committed.result().gameplayAdmissionAllowed()).isFalse();
+ StoredOperation retry =
+ inTransaction(
+ context.transaction(),
+ () -> {
+ Claim claim = claim(context.repository(), input);
+ assertThat(claim.claimed()).isFalse();
+ return claim.operation();
+ });
+ assertThat(retry.result()).isEqualTo(committed.result());
+ assertThat(retry.resultPayload()).containsExactly(committed.resultPayload());
+
+ byte[] changedSource =
+ "same authorization ID, changed Account snapshot".getBytes(StandardCharsets.UTF_8);
+ byte[] changedRequest =
+ AccountTenantCreationBootstrapDigest.requestPayload(input.creatorPayload(), changedSource);
+ String changedSourceDigest = AccountTenantCreationBootstrapDigest.sha256(changedSource);
+ String changedRequestDigest = AccountTenantCreationBootstrapDigest.sha256(changedRequest);
+ assertThatThrownBy(
+ () ->
+ inTransaction(
+ context.transaction(),
+ () ->
+ context
+ .repository()
+ .claim(
+ evidence,
+ input.creatorPayload(),
+ changedSource,
+ changedSourceDigest,
+ changedRequest,
+ changedRequestDigest,
+ 1L,
+ 1L)))
+ .isInstanceOf(OperationConflictException.class)
+ .hasMessageContaining("changed source or Account snapshot");
+
+ RequestInput changedAuthorization =
+ input(withAuthorizationDigest(evidence, "sha256:" + "9".repeat(64)));
+ assertThatThrownBy(
+ () ->
+ inTransaction(
+ context.transaction(), () -> claim(context.repository(), changedAuthorization)))
+ .isInstanceOf(OperationConflictException.class)
+ .hasMessageContaining("changed source or Account snapshot");
+
+ assertThatThrownBy(
+ () ->
+ context
+ .setupDsl()
+ .execute(
+ "UPDATE account_tenant_creation_bootstrap_operations "
+ + "SET source_snapshot_payload = ? WHERE request_id = ?",
+ changedSource,
+ evidence.accountAuthorizationOperationId()))
+ .isInstanceOf(org.jooq.exception.DataAccessException.class);
+ assertThatThrownBy(
+ () ->
+ context
+ .setupDsl()
+ .execute(
+ "DELETE FROM account_tenant_creation_bootstrap_operations WHERE request_id = ?",
+ evidence.accountAuthorizationOperationId()))
+ .isInstanceOf(org.jooq.exception.DataAccessException.class);
+ }
+
+ @Test
+ void claimedReceiptRollsBackWithItsAccountTransaction() {
+ TestContext context = newTestContext();
+ FreshTenantCreatorEvidence evidence = evidence(UUID.randomUUID());
+ RequestInput input = input(evidence);
+ insertAccount(context.setupDsl(), evidence.initiatingAccountId());
+
+ assertThatThrownBy(
+ () ->
+ context
+ .transaction()
+ .execute(
+ status -> {
+ claim(context.repository(), input);
+ context
+ .repository()
+ .complete(
+ evidence.accountAuthorizationOperationId(), completion(evidence));
+ throw new IllegalStateException(
+ "injected after immutable receipt readback");
+ }))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("injected after immutable receipt readback");
+ assertThat(
+ java.util.Objects.requireNonNull(
+ context
+ .setupDsl()
+ .fetchOne(
+ "SELECT count(*) FROM account_tenant_creation_bootstrap_operations "
+ + "WHERE request_id = ?",
+ evidence.accountAuthorizationOperationId()),
+ "Rollback count query returned no row")
+ .get(0, Long.class))
+ .isEqualTo(0L);
+ }
+
+ @Test
+ void concurrentExactClaimsConvergeOnOneCommittedReceipt() throws Exception {
+ TestContext context = newTestContext();
+ FreshTenantCreatorEvidence evidence = evidence(UUID.randomUUID());
+ RequestInput input = input(evidence);
+ insertAccount(context.setupDsl(), evidence.initiatingAccountId());
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ CountDownLatch firstCommittedInsideTransaction = new CountDownLatch(1);
+ CountDownLatch releaseFirstTransaction = new CountDownLatch(1);
+ CountDownLatch secondStarted = new CountDownLatch(1);
+ try {
+ Future first =
+ workers.submit(
+ () ->
+ context
+ .transaction()
+ .execute(
+ status -> {
+ Claim initial = claim(context.repository(), input);
+ if (!initial.claimed()) {
+ throw new IllegalStateException("First exact claim was not unique");
+ }
+ context
+ .repository()
+ .complete(
+ evidence.accountAuthorizationOperationId(),
+ completion(evidence));
+ firstCommittedInsideTransaction.countDown();
+ await(releaseFirstTransaction);
+ return initial.claimed();
+ }));
+ assertThat(firstCommittedInsideTransaction.await(10, TimeUnit.SECONDS)).isTrue();
+ Future second =
+ workers.submit(
+ () -> {
+ secondStarted.countDown();
+ return context
+ .transaction()
+ .execute(status -> claim(context.repository(), input).claimed());
+ });
+ assertThat(secondStarted.await(10, TimeUnit.SECONDS)).isTrue();
+ releaseFirstTransaction.countDown();
+ assertThat(first.get(10, TimeUnit.SECONDS)).isTrue();
+ assertThat(second.get(10, TimeUnit.SECONDS)).isFalse();
+ assertThat(
+ java.util.Objects.requireNonNull(
+ context
+ .setupDsl()
+ .fetchOne(
+ "SELECT count(*) FROM account_tenant_creation_bootstrap_operations "
+ + "WHERE request_id = ? AND status = 'COMMITTED'",
+ evidence.accountAuthorizationOperationId()),
+ "Committed count query returned no row")
+ .get(0, Long.class))
+ .isEqualTo(1L);
+ } finally {
+ releaseFirstTransaction.countDown();
+ workers.shutdownNow();
+ }
+ }
+
+ private TestContext newTestContext() {
+ String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setUrl(postgres.getJdbcUrl());
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ dataSource.setSchema(schema);
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations("classpath:db/migration")
+ .load()
+ .migrate();
+ DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ DSLContext transactionDsl =
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ return new TestContext(
+ dataSource,
+ setupDsl,
+ new AccountTenantCreationBootstrapOperationRepository(transactionDsl),
+ new TransactionTemplate(new DataSourceTransactionManager(dataSource)));
+ }
+
+ private static UUID insertAccount(DSLContext dsl, UUID accountUuid) {
+ String suffix = UUID.randomUUID().toString().replace("-", "");
+ return dsl.resultQuery(
+ "INSERT INTO accounts (account_uuid, username, email, password_hash) "
+ + "VALUES (?, ?, ?, ?) RETURNING account_uuid",
+ accountUuid,
+ "creator_" + suffix.substring(0, 12),
+ suffix + "@example.test",
+ "test-hash")
+ .fetchOne(0, UUID.class);
+ }
+
+ private static RequestInput input(FreshTenantCreatorEvidence evidence) {
+ byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence);
+ byte[] sourcePayload =
+ AccountTenantCreationBootstrapDigest.sourceSnapshotPayload(
+ snapshot(
+ evidence.initiatingAccountId(), evidence.creationEvidence().canonicalTenantId()));
+ String sourceDigest = AccountTenantCreationBootstrapDigest.sha256(sourcePayload);
+ byte[] requestPayload =
+ AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload);
+ return new RequestInput(
+ evidence,
+ creatorPayload,
+ sourcePayload,
+ sourceDigest,
+ requestPayload,
+ AccountTenantCreationBootstrapDigest.sha256(requestPayload));
+ }
+
+ private static Claim claim(
+ AccountTenantCreationBootstrapOperationRepository repository, RequestInput input) {
+ return repository.claim(
+ input.evidence(),
+ input.creatorPayload(),
+ input.sourcePayload(),
+ input.sourceDigest(),
+ input.requestPayload(),
+ input.requestDigest(),
+ 1L,
+ 1L);
+ }
+
+ private static Completion completion(FreshTenantCreatorEvidence evidence) {
+ UUID tenantUuid = evidence.creationEvidence().canonicalTenantId();
+ String requestId = evidence.accountAuthorizationOperationId().toString();
+ String stream =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + evidence.initiatingAccountId()
+ + "/"
+ + tenantUuid;
+ byte[] event =
+ "synthetic event bytes for repository storage proof".getBytes(StandardCharsets.UTF_8);
+ byte[] audit =
+ "synthetic audit bytes for repository storage proof".getBytes(StandardCharsets.UTF_8);
+ byte[] result = "synthetic immutable result bytes".getBytes(StandardCharsets.UTF_8);
+ return new Completion(
+ 51L,
+ 2L,
+ 1L,
+ "ACTIVE",
+ false,
+ "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8),
+ stream,
+ requestId,
+ 1L,
+ "creator-bootstrap-event-1",
+ digest(1),
+ false,
+ event,
+ UUID.randomUUID(),
+ AUDIT_EVENT_TYPE,
+ Instant.parse("2026-10-02T00:00:00Z"),
+ digest(2),
+ audit,
+ result,
+ AccountTenantCreationBootstrapDigest.sha256(result));
+ }
+
+ private static NeverJoinedMembershipSnapshot snapshot(UUID accountUuid, UUID tenantUuid) {
+ String account = accountUuid.toString();
+ String tenant = tenantUuid.toString();
+ String stream =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + account
+ + "/"
+ + tenant;
+ return new NeverJoinedMembershipSnapshot(
+ account,
+ tenant,
+ Map.of(tenant, "1"),
+ "1",
+ new AuthorityTuple(
+ "1",
+ "1",
+ Map.of(tenant, "1"),
+ Map.of(tenant, "1"),
+ List.of(),
+ Optional.empty(),
+ Optional.empty()),
+ "1",
+ Instant.parse("2026-10-01T00:00:00Z"),
+ stream,
+ List.of(
+ new OutboxCheckpointEntry("account:auth-authority:v1:account/" + account, "0"),
+ new OutboxCheckpointEntry(
+ "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, "0"),
+ new OutboxCheckpointEntry(stream, "0"),
+ new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + tenant, "0")),
+ List.of());
+ }
+
+ private static FreshTenantCreatorEvidence evidence(UUID creatorUuid) {
+ UUID tenantUuid = UUID.randomUUID();
+ UUID creationRequestId = UUID.randomUUID();
+ UUID creationOperationId = UUID.randomUUID();
+ UUID authorizationOperationId = UUID.randomUUID();
+ String namespace = "firemud-test";
+ String tenantKey = "repository-proof-17";
+ String requestDigest =
+ GameTenantCreationDigest.requestDigest(
+ namespace, creationRequestId, tenantKey, "Example", null);
+ FreshTenantCreationEvidence creation =
+ new FreshTenantCreationEvidence(
+ 1,
+ namespace,
+ creationRequestId,
+ creationOperationId,
+ requestDigest,
+ tenantUuid,
+ 17L,
+ tenantKey,
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ namespace,
+ creationRequestId,
+ creationOperationId,
+ requestDigest,
+ tenantUuid,
+ 17L,
+ tenantKey,
+ "NEW_GAME_ROW"));
+ String authorizationDigest = "sha256:" + "7".repeat(64);
+ return new FreshTenantCreatorEvidence(
+ 1,
+ creation,
+ creatorUuid,
+ authorizationOperationId,
+ authorizationDigest,
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, creation, creatorUuid, authorizationOperationId, authorizationDigest));
+ }
+
+ private static FreshTenantCreatorEvidence withAuthorizationDigest(
+ FreshTenantCreatorEvidence original, String authorizationDigest) {
+ return new FreshTenantCreatorEvidence(
+ 1,
+ original.creationEvidence(),
+ original.initiatingAccountId(),
+ original.accountAuthorizationOperationId(),
+ authorizationDigest,
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1,
+ original.creationEvidence(),
+ original.initiatingAccountId(),
+ original.accountAuthorizationOperationId(),
+ authorizationDigest));
+ }
+
+ private static String digest(int marker) {
+ return "sha256:" + Integer.toHexString(marker).repeat(64).substring(0, 64);
+ }
+
+ private static void await(CountDownLatch latch) {
+ try {
+ if (!latch.await(10, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("Concurrent exact-claim proof timed out");
+ }
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Concurrent exact-claim proof was interrupted", interrupted);
+ }
+ }
+
+ private static T inTransaction(
+ TransactionTemplate transaction, java.util.function.Supplier work) {
+ return transaction.execute(status -> work.get());
+ }
+
+ private record RequestInput(
+ FreshTenantCreatorEvidence evidence,
+ byte[] creatorPayload,
+ byte[] sourcePayload,
+ String sourceDigest,
+ byte[] requestPayload,
+ String requestDigest) {}
+
+ private record TestContext(
+ DataSource dataSource,
+ DSLContext setupDsl,
+ AccountTenantCreationBootstrapOperationRepository repository,
+ TransactionTemplate transaction) {}
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java
index cd6f947603..8eff9c5332 100644
--- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java
@@ -38,9 +38,11 @@
import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor;
import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest;
import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse;
+import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreatorQualificationResponse;
import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -53,10 +55,17 @@ class GameDesignFreshTenantIdentityClientTest {
private static final UUID OPERATION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222");
private static final UUID CANONICAL_TENANT_ID =
UUID.fromString("33333333-3333-4333-8333-333333333333");
+ private static final UUID READ_REQUEST_ID =
+ UUID.fromString("55555555-5555-4555-8555-555555555555");
+ private static final UUID INITIATING_ACCOUNT_ID =
+ UUID.fromString("66666666-6666-4666-8666-666666666666");
+ private static final UUID AUTHORIZATION_OPERATION_ID =
+ UUID.fromString("77777777-7777-4777-8777-777777777777");
private static final UUID NIL_UUID = new UUID(0L, 0L);
private static final long SOURCE_GAME_ROW_ID = 91L;
private static final String SOURCE_GAME_TENANT_KEY = "fresh-owner-key-91";
private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64);
+ private static final String AUTHORIZATION_DIGEST = "sha256:" + "b".repeat(64);
@Test
void exactResponseIsValidatedAndStableOnReplayWithoutCallingRetainedRpcs() throws Exception {
@@ -138,6 +147,145 @@ void rejectsMalformedSelectorsBeforeAnyRpc() throws Exception {
verifyNoInteractions(stub);
}
+ @Test
+ void exactCreatorQualificationReadPreservesOriginalReceiptAndBindsDistinctReadIdentity()
+ throws Exception {
+ TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub();
+ when(stub.resolveFreshTenantCreatorQualification(any()))
+ .thenReturn(validCreatorQualificationResponse());
+ GameDesignFreshTenantIdentityClient client = newClient(stub);
+ FreshTenantCreationEvidence source = validFreshCreationEvidence();
+
+ var qualification =
+ client.resolveCreatorQualification(
+ READ_REQUEST_ID,
+ source,
+ INITIATING_ACCOUNT_ID,
+ AUTHORIZATION_OPERATION_ID,
+ AUTHORIZATION_DIGEST);
+
+ assertThat(qualification.creationEvidence()).isEqualTo(source);
+ assertThat(qualification.initiatingAccountId()).isEqualTo(INITIATING_ACCOUNT_ID);
+ assertThat(qualification.accountAuthorizationOperationId())
+ .isEqualTo(AUTHORIZATION_OPERATION_ID);
+ assertThat(qualification.accountAuthorizationDigest()).isEqualTo(AUTHORIZATION_DIGEST);
+ assertThat(qualification.evidenceDigest())
+ .isEqualTo(
+ validCreatorQualificationResponse().getCreatorQualification().getEvidenceDigest());
+ verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS);
+ ArgumentCaptor<
+ net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreatorQualificationRequest>
+ requestCaptor =
+ ArgumentCaptor.forClass(
+ net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreatorQualificationRequest
+ .class);
+ verify(stub).resolveFreshTenantCreatorQualification(requestCaptor.capture());
+ assertThat(requestCaptor.getValue().getReadRequestId()).isEqualTo(READ_REQUEST_ID.toString());
+ assertThat(requestCaptor.getValue().getCreationRequestId()).isEqualTo(REQUEST_ID.toString());
+ assertThat(requestCaptor.getValue().getExpectedRequestDigest()).isEqualTo(REQUEST_DIGEST);
+ assertThat(requestCaptor.getValue().getExpectedEvidenceDigest())
+ .isEqualTo(source.evidenceDigest());
+ assertThat(requestCaptor.getValue().getInitiatingAccountId())
+ .isEqualTo(INITIATING_ACCOUNT_ID.toString());
+ assertThat(requestCaptor.getValue().getAccountAuthorizationOperationId())
+ .isEqualTo(AUTHORIZATION_OPERATION_ID.toString());
+ assertThat(requestCaptor.getValue().getAccountAuthorizationDigest())
+ .isEqualTo(AUTHORIZATION_DIGEST);
+ }
+
+ @Test
+ void rejectsChangedReadIdentitySourceCreatorBindingAndUnknownResponseFields() throws Exception {
+ ResolveFreshTenantCreatorQualificationResponse valid = validCreatorQualificationResponse();
+ assertRejectedCreator(valid.toBuilder().setReadRequestId(OTHER_REQUEST_ID.toString()).build());
+ assertRejectedCreator(
+ valid.toBuilder()
+ .setCreationEvidence(
+ valid.getCreationEvidence().toBuilder()
+ .setSourceGameRowId(SOURCE_GAME_ROW_ID + 1)
+ .build())
+ .build());
+ assertRejectedCreator(
+ valid.toBuilder()
+ .setCreatorQualification(
+ valid.getCreatorQualification().toBuilder()
+ .setInitiatingAccountId(OTHER_REQUEST_ID.toString())
+ .build())
+ .build());
+ assertRejectedCreator(
+ valid.toBuilder()
+ .setCreatorQualification(
+ valid.getCreatorQualification().toBuilder()
+ .setEvidenceDigest("sha256:" + "c".repeat(64))
+ .build())
+ .build());
+ UnknownFieldSet unknownFields =
+ UnknownFieldSet.newBuilder()
+ .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build())
+ .build();
+ assertRejectedCreator(valid.toBuilder().setUnknownFields(unknownFields).build());
+ assertRejectedCreator(
+ valid.toBuilder()
+ .setCreatorQualification(
+ valid.getCreatorQualification().toBuilder().setUnknownFields(unknownFields))
+ .build());
+ assertRejectedCreator(
+ valid.toBuilder()
+ .setCreationEvidence(
+ valid.getCreationEvidence().toBuilder().setUnknownFields(unknownFields).build())
+ .build());
+ assertRejectedCreator(valid.toBuilder().clearCreatorQualification().build());
+ }
+
+ @Test
+ void malformedCreatorSelectorsAreRejectedBeforeTheRpc() throws Exception {
+ TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub();
+ GameDesignFreshTenantIdentityClient client = newClient(stub);
+ FreshTenantCreationEvidence source = validFreshCreationEvidence();
+
+ assertThatThrownBy(
+ () ->
+ client.resolveCreatorQualification(
+ NIL_UUID,
+ source,
+ INITIATING_ACCOUNT_ID,
+ AUTHORIZATION_OPERATION_ID,
+ AUTHORIZATION_DIGEST))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ client.resolveCreatorQualification(
+ READ_REQUEST_ID,
+ source,
+ NIL_UUID,
+ AUTHORIZATION_OPERATION_ID,
+ AUTHORIZATION_DIGEST))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ client.resolveCreatorQualification(
+ READ_REQUEST_ID, source, INITIATING_ACCOUNT_ID, NIL_UUID, AUTHORIZATION_DIGEST))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ client.resolveCreatorQualification(
+ READ_REQUEST_ID,
+ source,
+ INITIATING_ACCOUNT_ID,
+ AUTHORIZATION_OPERATION_ID,
+ "bad"))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ client.resolveCreatorQualification(
+ READ_REQUEST_ID,
+ null,
+ INITIATING_ACCOUNT_ID,
+ AUTHORIZATION_OPERATION_ID,
+ AUTHORIZATION_DIGEST))
+ .isInstanceOf(IllegalArgumentException.class);
+ verifyNoInteractions(stub);
+ }
+
@Test
void rejectsPlaintextAndIncompleteAccountMtlsConfigurationBeforeChannelCreation() {
GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class);
@@ -287,6 +435,23 @@ private static void assertRejected(ResolveFreshTenantCreationResponse response)
.isInstanceOf(IllegalStateException.class);
}
+ private static void assertRejectedCreator(ResolveFreshTenantCreatorQualificationResponse response)
+ throws Exception {
+ TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub();
+ when(stub.resolveFreshTenantCreatorQualification(any())).thenReturn(response);
+ GameDesignFreshTenantIdentityClient client = newClient(stub);
+
+ assertThatThrownBy(
+ () ->
+ client.resolveCreatorQualification(
+ READ_REQUEST_ID,
+ validFreshCreationEvidence(),
+ INITIATING_ACCOUNT_ID,
+ AUTHORIZATION_OPERATION_ID,
+ AUTHORIZATION_DIGEST))
+ .isInstanceOf(IllegalStateException.class);
+ }
+
private static GameDesignFreshTenantIdentityClient newClient(
TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) throws Exception {
GameDesignFreshTenantIdentityClient client =
@@ -351,6 +516,42 @@ private static ResolveFreshTenantCreationResponse validResponse(
.build();
}
+ private static FreshTenantCreationEvidence validFreshCreationEvidence() {
+ ResolveFreshTenantCreationResponse source = validResponse();
+ return new FreshTenantCreationEvidence(
+ source.getSchemaVersion(),
+ source.getTargetNamespace(),
+ UUID.fromString(source.getCreationRequestId()),
+ UUID.fromString(source.getOperationId()),
+ source.getRequestDigest(),
+ UUID.fromString(source.getCanonicalTenantId()),
+ source.getSourceGameRowId(),
+ source.getSourceGameTenantKey(),
+ source.getProvenanceKind(),
+ source.getEvidenceDigest());
+ }
+
+ private static ResolveFreshTenantCreatorQualificationResponse
+ validCreatorQualificationResponse() {
+ FreshTenantCreationEvidence source = validFreshCreationEvidence();
+ String creatorDigest =
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATING_ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST);
+ return ResolveFreshTenantCreatorQualificationResponse.newBuilder()
+ .setReadRequestId(READ_REQUEST_ID.toString())
+ .setCreationEvidence(validResponse())
+ .setCreatorQualification(
+ net.firedevops.firemud.gamedesign.v1.FreshTenantCreatorQualificationEvidence
+ .newBuilder()
+ .setSchemaVersion(1)
+ .setInitiatingAccountId(INITIATING_ACCOUNT_ID.toString())
+ .setAccountAuthorizationOperationId(AUTHORIZATION_OPERATION_ID.toString())
+ .setAccountAuthorizationDigest(AUTHORIZATION_DIGEST)
+ .setEvidenceDigest(creatorDigest)
+ .build())
+ .build();
+ }
+
private static CommonGrpcClientProperties mtlsProperties() {
CommonGrpcClientProperties tls = new CommonGrpcClientProperties();
tls.setCertChain("certs/account-client.crt");
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigestTest.java
new file mode 100644
index 0000000000..27521f7547
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigestTest.java
@@ -0,0 +1,188 @@
+package unit.net.firedevops.firemud.accountservice.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry;
+import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
+import org.junit.jupiter.api.Test;
+
+/** Digest proof covers original creator qualification plus the complete fenced Account snapshot. */
+class AccountTenantCreationBootstrapDigestTest {
+ @Test
+ void resultPayloadCarriesCompleteTenantBoundMembershipVersionMap() {
+ UUID tenantUuid = UUID.randomUUID();
+
+ byte[] result = resultPayload(tenantUuid, Map.of(tenantUuid.toString(), "2"));
+
+ assertThat(resultJson(result)).contains("\"membershipVersion\":{\"" + tenantUuid + "\":\"2\"}");
+ }
+
+ @Test
+ void resultPayloadRejectsMissingExtraAndWrongTenantMembershipVersionEntries() {
+ UUID tenantUuid = UUID.randomUUID();
+ UUID otherTenantUuid = UUID.randomUUID();
+
+ assertThatThrownBy(() -> resultPayload(tenantUuid, Map.of()))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ resultPayload(
+ tenantUuid,
+ Map.of(tenantUuid.toString(), "2", otherTenantUuid.toString(), "3")))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> resultPayload(tenantUuid, Map.of(otherTenantUuid.toString(), "2")))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void requestIdentityChangesWithAccountSnapshotAndRetainsCompleteAuthorityMaps() {
+ UUID accountUuid = UUID.randomUUID();
+ UUID tenantUuid = UUID.randomUUID();
+ FreshTenantCreatorEvidence evidence = evidence(accountUuid, tenantUuid);
+ NeverJoinedMembershipSnapshot first = snapshot(accountUuid, tenantUuid, "3");
+ NeverJoinedMembershipSnapshot laterFence = snapshot(accountUuid, tenantUuid, "4");
+
+ byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence);
+ byte[] firstSource = AccountTenantCreationBootstrapDigest.sourceSnapshotPayload(first);
+ byte[] laterSource = AccountTenantCreationBootstrapDigest.sourceSnapshotPayload(laterFence);
+ Map tuple =
+ AccountTenantCreationBootstrapDigest.authorityTupleMap(first.authorityTuple());
+
+ assertThat(new String(creatorPayload, StandardCharsets.UTF_8))
+ .contains(evidence.creationEvidence().sourceGameTenantKey())
+ .contains(evidence.accountAuthorizationOperationId().toString())
+ .contains(evidence.accountAuthorizationDigest());
+ assertThat(firstSource).isNotEqualTo(laterSource);
+ assertThat(tuple)
+ .containsEntry("tenantAuthorityGeneration", Map.of(tenantUuid.toString(), "1"))
+ .containsEntry("membershipAuthorityGeneration", Map.of(tenantUuid.toString(), "1"));
+ assertThat(AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, firstSource))
+ .isNotEqualTo(
+ AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, laterSource));
+ }
+
+ private static NeverJoinedMembershipSnapshot snapshot(
+ UUID accountUuid, UUID tenantUuid, String issuanceFence) {
+ String account = accountUuid.toString();
+ String tenant = tenantUuid.toString();
+ String stream =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + account
+ + "/"
+ + tenant;
+ AuthorityTuple tuple =
+ new AuthorityTuple(
+ "1",
+ "1",
+ Map.of(tenant, "1"),
+ Map.of(tenant, "1"),
+ List.of(),
+ Optional.empty(),
+ Optional.empty());
+ return new NeverJoinedMembershipSnapshot(
+ account,
+ tenant,
+ Map.of(tenant, "1"),
+ "1",
+ tuple,
+ issuanceFence,
+ Instant.parse("2026-10-01T00:00:00Z"),
+ stream,
+ List.of(
+ new OutboxCheckpointEntry("account:auth-authority:v1:account/" + account, "0"),
+ new OutboxCheckpointEntry(
+ "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, "0"),
+ new OutboxCheckpointEntry(stream, "0"),
+ new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + tenant, "0")),
+ List.of());
+ }
+
+ private static FreshTenantCreatorEvidence evidence(UUID accountUuid, UUID tenantUuid) {
+ UUID requestId = UUID.randomUUID();
+ UUID creationOperationId = UUID.randomUUID();
+ UUID authorizationOperationId = UUID.randomUUID();
+ String namespace = "firemud-test";
+ String tenantKey = "world-source-17";
+ String requestDigest =
+ GameTenantCreationDigest.requestDigest(namespace, requestId, tenantKey, "Example", null);
+ FreshTenantCreationEvidence creation =
+ new FreshTenantCreationEvidence(
+ 1,
+ namespace,
+ requestId,
+ creationOperationId,
+ requestDigest,
+ tenantUuid,
+ 17L,
+ tenantKey,
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ namespace,
+ requestId,
+ creationOperationId,
+ requestDigest,
+ tenantUuid,
+ 17L,
+ tenantKey,
+ "NEW_GAME_ROW"));
+ String authorizationDigest = "sha256:" + "6".repeat(64);
+ return new FreshTenantCreatorEvidence(
+ 1,
+ creation,
+ accountUuid,
+ authorizationOperationId,
+ authorizationDigest,
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, creation, accountUuid, authorizationOperationId, authorizationDigest));
+ }
+
+ private static byte[] resultPayload(UUID tenantUuid, Map membershipVersion) {
+ return AccountTenantCreationBootstrapDigest.resultPayload(
+ "request-id",
+ "sha256:" + "1".repeat(64),
+ "sha256:" + "2".repeat(64),
+ tenantUuid,
+ membershipVersion,
+ "1",
+ "membership-stream",
+ "event-request-id",
+ 1L,
+ "event-id",
+ "sha256:" + "3".repeat(64),
+ new byte[] {1},
+ UUID.randomUUID(),
+ "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED",
+ "2026-10-01T00:00:00Z",
+ "sha256:" + "4".repeat(64),
+ new byte[] {2},
+ new byte[] {3},
+ new byte[] {4});
+ }
+
+ private static String resultJson(byte[] payload) {
+ ByteBuffer buffer = ByteBuffer.wrap(payload);
+ int domainLength = buffer.getInt();
+ buffer.position(buffer.position() + domainLength);
+ int resultLength = buffer.getInt();
+ byte[] result = new byte[resultLength];
+ buffer.get(result);
+ return new String(result, StandardCharsets.UTF_8);
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalogTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalogTest.java
index f9fa7f4b07..eaf15c2c04 100644
--- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalogTest.java
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalogTest.java
@@ -1,5 +1,6 @@
package unit.net.firedevops.firemud.accountservice.security;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -761,6 +762,27 @@ void bindsActualMembershipVersionAndScopedRoleValuesToTypedScopeWithoutRounding(
AccountTokenProfileCatalog.CONTROL_UI, shape, copied, 1_000, 1_900, tupleJson(shape));
}
+ @Test
+ void acceptsZeroMembershipVersionWithoutChangingScopeOrGenerationRequirements() {
+ AccountTokenProfileCatalog catalog = catalog();
+ ControlUiShape shape = controlUiShape();
+ ActualClaimMaps valid = actualClaimMaps(shape);
+ assertDoesNotThrow(
+ () ->
+ catalog.validatePreSignCandidate(
+ AccountTokenProfileCatalog.CONTROL_UI,
+ shape,
+ new ActualClaimMaps(
+ Optional.of(
+ Map.of(
+ TENANT_A.toString(), BigInteger.ZERO,
+ TENANT_B.toString(), BigInteger.ONE)),
+ valid.scopedRoles()),
+ 1_000L,
+ 1_900L,
+ tupleJson(shape)));
+ }
+
@Test
void rejectsActualMembershipVersionAndScopedRoleScopeOrValueMismatches() {
AccountTokenProfileCatalog catalog = catalog();
@@ -806,16 +828,6 @@ void rejectsActualMembershipVersionAndScopedRoleScopeOrValueMismatches() {
TENANT_B.toString(),
BigInteger.ONE)),
valid.scopedRoles()));
- assertInvalidClaimMaps(
- catalog,
- AccountTokenProfileCatalog.CONTROL_UI,
- shape,
- new ActualClaimMaps(
- Optional.of(
- Map.of(
- TENANT_A.toString(), BigInteger.ZERO,
- TENANT_B.toString(), BigInteger.ONE)),
- valid.scopedRoles()));
assertInvalidClaimMaps(
catalog,
AccountTokenProfileCatalog.CONTROL_UI,
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapServiceTest.java
new file mode 100644
index 0000000000..9d52c1e8c3
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapServiceTest.java
@@ -0,0 +1,138 @@
+package net.firedevops.firemud.accountservice.service;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Focused proof that no DTO-only or unregistered source can activate creator membership. */
+@ExtendWith(MockitoExtension.class)
+class AccountTenantCreationBootstrapServiceTest {
+ @Mock private AccountRepository accountRepository;
+ @Mock private FreshTenantIdentityAssociationRepository tenantAssociationRepository;
+ @Mock private AccountMembershipAuthorityEventProducer eventProducer;
+ @Mock private AccountMembershipPairAuthorityRepository pairAuthorityRepository;
+ @Mock private AccountTenantMembershipRepository membershipRepository;
+ @Mock private AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository;
+ @Mock private AccountAuthorityOutboxRepository authorityOutboxRepository;
+ @Mock private AccountAuditOutboxRepository auditOutboxRepository;
+ @Mock private AccountTenantCreationBootstrapOperationRepository operationRepository;
+
+ @Mock
+ private ObjectProvider
+ authorizationSourceProvider;
+
+ @InjectMocks private AccountTenantCreationBootstrapService service;
+
+ @AfterEach
+ void clearSyntheticTransactionState() {
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
+ }
+
+ @Test
+ void exactCreatorDtoCannotCommitWithoutRegisteredCurrentAccountAuthorizationSource() {
+ FreshTenantCreatorEvidence evidence = evidence();
+ Account creator = account(evidence.initiatingAccountId());
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
+ when(accountRepository.findByAccountUuidForUpdate(evidence.initiatingAccountId()))
+ .thenReturn(Optional.of(creator));
+ when(operationRepository.findForUpdate(evidence.accountAuthorizationOperationId()))
+ .thenReturn(Optional.empty());
+ when(operationRepository.findRequestIdByTenantForUpdate(
+ evidence.creationEvidence().canonicalTenantId()))
+ .thenReturn(Optional.empty());
+ when(authorizationSourceProvider.getIfAvailable()).thenReturn(null);
+
+ assertThatThrownBy(() -> service.bootstrap(evidence))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("No current Account creator-authorization/source participant");
+
+ verify(authorizationSourceProvider).getIfAvailable();
+ verifyNoInteractions(
+ tenantAssociationRepository,
+ eventProducer,
+ pairAuthorityRepository,
+ membershipRepository,
+ roleSnapshotRepository,
+ authorityOutboxRepository,
+ auditOutboxRepository);
+ }
+
+ private static Account account(UUID accountUuid) {
+ Account account = new Account();
+ account.setId(17L);
+ account.setAccountUuid(accountUuid);
+ account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT);
+ account.setAccountUuidSourceNumericId(17L);
+ return account;
+ }
+
+ private static FreshTenantCreatorEvidence evidence() {
+ UUID creatorUuid = UUID.randomUUID();
+ UUID tenantUuid = UUID.randomUUID();
+ UUID creationRequestId = UUID.randomUUID();
+ UUID creationOperationId = UUID.randomUUID();
+ UUID authorizationOperationId = UUID.randomUUID();
+ String targetNamespace = "firemud-test";
+ String tenantKey = "source-tenant-17";
+ String requestDigest =
+ GameTenantCreationDigest.requestDigest(
+ targetNamespace, creationRequestId, tenantKey, "Example", null);
+ FreshTenantCreationEvidence creationEvidence =
+ new FreshTenantCreationEvidence(
+ 1,
+ targetNamespace,
+ creationRequestId,
+ creationOperationId,
+ requestDigest,
+ tenantUuid,
+ 17L,
+ tenantKey,
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ targetNamespace,
+ creationRequestId,
+ creationOperationId,
+ requestDigest,
+ tenantUuid,
+ 17L,
+ tenantKey,
+ "NEW_GAME_ROW"));
+ String authorizationDigest = "sha256:" + "4".repeat(64);
+ return new FreshTenantCreatorEvidence(
+ 1,
+ creationEvidence,
+ creatorUuid,
+ authorizationOperationId,
+ authorizationDigest,
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, creationEvidence, creatorUuid, authorizationOperationId, authorizationDigest));
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecksTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecksTest.java
new file mode 100644
index 0000000000..90057e4f43
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecksTest.java
@@ -0,0 +1,384 @@
+package unit.net.firedevops.firemud.accountservice.service.controlui;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.time.Clock;
+import java.time.ZoneOffset;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiTokenChecks;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class AccountControlUiTokenChecksTest {
+ private AccountControlUiTokenFixture fixture;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ fixture =
+ new AccountControlUiTokenFixture(
+ Clock.fixed(AccountControlUiTokenFixture.NOW, ZoneOffset.UTC));
+ }
+
+ @Test
+ void realRs256UnscopedTokenAndExactActiveRecordProduceOnlyNonAuthorizingInspection()
+ throws Exception {
+ UUID accountId = UUID.randomUUID();
+ Map claims = fixture.claims(accountId);
+ String token = fixture.sign(claims);
+ var inspected =
+ fixture
+ .checks()
+ .inspect(
+ "fresh-creator-candidate",
+ token,
+ AccountControlUiTokenFixture.canonical(fixture.registry(token, claims)),
+ AccountControlUiTokenFixture.unscopedShape());
+ assertThat(inspected.accountId()).isEqualTo(accountId);
+ assertThat(inspected.toString()).contains("non-authorizing").doesNotContain(token);
+ inspected.registryRecord().put("state", "revoked");
+ assertThat(inspected.registryRecord().get("state")).isEqualTo("active");
+ assertThatThrownBy(() -> inspected.claims().put("actorId", UUID.randomUUID()))
+ .isInstanceOf(UnsupportedOperationException.class);
+ }
+
+ @Test
+ void adjacentLargeSignedAndRegistryCountersCannotMatchThroughCanonicalRounding()
+ throws Exception {
+ Map claims = fixture.claims(UUID.randomUUID());
+ claims.put("issuanceFence", "9007199254740993");
+ String token = fixture.sign(claims);
+ Map record = fixture.registry(token, claims);
+ record.put("issuanceFence", "9007199254740992");
+ byte[] bytes = AccountControlUiTokenFixture.canonical(record);
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "fresh-creator-candidate",
+ token,
+ bytes,
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ }
+
+ @Test
+ void numericAuthorityCounterDeniesWithoutCompatibility() throws Exception {
+ Map claims = fixture.claims(UUID.randomUUID());
+ claims.put("tokenGeneration", new java.math.BigInteger("9007199254740993"));
+ String token = fixture.sign(claims);
+ byte[] exactRecord = AccountControlUiTokenFixture.exactJson(fixture.registry(token, claims));
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "fresh-creator-candidate",
+ token,
+ exactRecord,
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ }
+
+ @Test
+ void largeDecimalStringCountersPreserveExactSignedRegistryAndCatalogCorrespondence()
+ throws Exception {
+ for (String counter :
+ List.of(
+ "9007199254740992", "9007199254740993", "9223372036854775808", "9223372036854775809")) {
+ Map claims = fixture.claims(UUID.randomUUID());
+ claims.put("tokenGeneration", counter);
+ claims.put("issuanceFence", counter);
+ Map tuple =
+ new LinkedHashMap<>((Map) claims.get("authorityTuple"));
+ tuple.put("issuerAuthGeneration", counter);
+ tuple.put("accountAuthorityGeneration", counter);
+ claims.put("authorityTuple", tuple);
+ String token = fixture.sign(claims);
+ var inspected =
+ fixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ token,
+ AccountControlUiTokenFixture.canonical(fixture.registry(token, claims)),
+ AccountControlUiTokenFixture.unscopedShape());
+ assertThat(inspected.claims().get("tokenGeneration")).isEqualTo(counter);
+ assertThat(inspected.registryRecord().get("issuanceFence")).isEqualTo(counter);
+ assertThat(inspected.registryRecord().get("authorityTuple")).isEqualTo(tuple);
+ }
+ }
+
+ @Test
+ void positiveLineageAndFenceCountersRejectAllNoncanonicalWireForms() throws Exception {
+ for (Object invalid : List.of(1L, "0", "-1", "+1", "01", " 1", "1 ", "1.0", "1e3", "", "bad")) {
+ for (String field : List.of("tokenGeneration", "issuanceFence")) {
+ Map claims = fixture.claims(UUID.randomUUID());
+ claims.put(field, invalid);
+ String token = fixture.sign(claims);
+ byte[] record = AccountControlUiTokenFixture.canonical(fixture.registry(token, claims));
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ token,
+ record,
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ }
+ }
+ }
+
+ @Test
+ void rewritingSignedNumericBytesCannotRescueAHistoricalToken() throws Exception {
+ Map claims = fixture.claims(UUID.randomUUID());
+ claims.put("tokenGeneration", 1L);
+ String numericToken = fixture.sign(claims);
+ String[] parts = numericToken.split("\\.");
+ String numericPayload =
+ new String(
+ java.util.Base64.getUrlDecoder().decode(parts[1]),
+ java.nio.charset.StandardCharsets.UTF_8);
+ String rewrittenPayload =
+ numericPayload.replace("\"tokenGeneration\":1", "\"tokenGeneration\":\"1\"");
+ assertThat(rewrittenPayload).isNotEqualTo(numericPayload);
+ String rewrittenToken =
+ parts[0]
+ + "."
+ + java.util.Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(rewrittenPayload.getBytes(java.nio.charset.StandardCharsets.UTF_8))
+ + "."
+ + parts[2];
+ claims.put("tokenGeneration", "1");
+ byte[] record =
+ AccountControlUiTokenFixture.canonical(fixture.registry(rewrittenToken, claims));
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ rewrittenToken,
+ record,
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ }
+
+ @Test
+ void durableCaptureVersionAndAccountSourceVersionAdvanceIndependently() throws Exception {
+ Map claims = fixture.claims(UUID.randomUUID());
+ String token = fixture.sign(claims);
+ var checks = fixture.checks();
+ for (long[] versions :
+ List.of(new long[] {71L, 3L}, new long[] {72L, 3L}, new long[] {72L, 4L})) {
+ Map record = fixture.registry(token, claims);
+ record.put(
+ "authoritySourceVersions",
+ Map.of(
+ "issuerSourceVersion",
+ 1L,
+ "accountSourceVersion",
+ versions[1],
+ "issuanceFenceSourceVersion",
+ 1L));
+ record.put(
+ "authEvidenceBundle",
+ Map.of(
+ "bundleVersion",
+ "1",
+ "sourceVersion",
+ Long.toString(versions[0]),
+ "linearization",
+ "123",
+ "canonicalSha256",
+ "c".repeat(64)));
+ var inspected =
+ checks.inspect(
+ "fresh-creator-candidate",
+ token,
+ AccountControlUiTokenFixture.canonical(record),
+ AccountControlUiTokenFixture.unscopedShape());
+ assertThat(inspected.registryRecord().get("authEvidenceBundle"))
+ .isEqualTo(record.get("authEvidenceBundle"));
+ assertThat(inspected.toString()).contains("non-authorizing");
+ }
+ }
+
+ @Test
+ void billingSafeMembershipDoesNotCreateTargetTenantAuthority() throws Exception {
+ UUID tenant = UUID.randomUUID();
+ Map claims = fixture.claims(UUID.randomUUID());
+ Map tuple =
+ new LinkedHashMap<>((Map) claims.get("authorityTuple"));
+ tuple.put("membershipAuthorityGeneration", Map.of(tenant.toString(), "9223372036854775808"));
+ claims.put("authorityTuple", tuple);
+ claims.put("membershipVersion", Map.of(tenant.toString(), "9223372036854775809"));
+ claims.put("scopedRoles", Map.of(tenant.toString(), List.of("tenantAdmin")));
+ String token = fixture.sign(claims);
+ var inspected =
+ fixture
+ .checks()
+ .inspect(
+ "billing-safe-candidate",
+ token,
+ AccountControlUiTokenFixture.canonical(fixture.registry(token, claims)),
+ AccountControlUiTokenFixture.shape(
+ Set.of(tenant), Set.of(tenant), Set.of(), Set.of(tenant), Set.of(tenant)));
+ assertThat(
+ ((Map, ?>) inspected.claims().get("authorityTuple")).get("tenantAuthorityGeneration"))
+ .isEqualTo(Map.of());
+ }
+
+ @Test
+ void canonicalZeroMembershipVersionPassesCatalogWithoutInferringMembershipAuthority()
+ throws Exception {
+ UUID tenant = UUID.randomUUID();
+ Map claims = fixture.claims(UUID.randomUUID());
+ Map tuple =
+ new LinkedHashMap<>((Map) claims.get("authorityTuple"));
+ tuple.put("membershipAuthorityGeneration", Map.of(tenant.toString(), "9223372036854775808"));
+ claims.put("authorityTuple", tuple);
+ claims.put("membershipVersion", Map.of(tenant.toString(), "0"));
+ claims.put("scopedRoles", Map.of(tenant.toString(), List.of("tenantAdmin")));
+ String token = fixture.sign(claims);
+ var inspected =
+ fixture
+ .checks()
+ .inspect(
+ "billing-safe-candidate",
+ token,
+ AccountControlUiTokenFixture.canonical(fixture.registry(token, claims)),
+ AccountControlUiTokenFixture.shape(
+ Set.of(tenant), Set.of(tenant), Set.of(), Set.of(tenant), Set.of(tenant)));
+ assertThat(inspected.registryRecord().get("membershipVersion"))
+ .isEqualTo(Map.of(tenant.toString(), "0"));
+ assertThat(inspected.toString()).contains("non-authorizing");
+ }
+
+ @Test
+ void exactRecordIdentityStateTimesProfileTupleAndMembershipMustMatch() throws Exception {
+ Map claims = fixture.claims(UUID.randomUUID());
+ String token = fixture.sign(claims);
+ for (Map.Entry change :
+ Map.ofEntries(
+ Map.entry("state", "pending"),
+ Map.entry("profile", "game-session-account-delegation"),
+ Map.entry("type", "private_player_delegation"),
+ Map.entry("issuer", "other"),
+ Map.entry("audience", "player-bootstrap"),
+ Map.entry("accountId", UUID.randomUUID().toString()),
+ Map.entry("kid", "other-key"),
+ Map.entry("signerGeneration", "0"),
+ Map.entry("tokenHash", "0".repeat(64)),
+ Map.entry("exp", AccountControlUiTokenFixture.NOW.getEpochSecond() + 901L),
+ Map.entry("issuanceFence", "2"),
+ Map.entry("membershipVersion", Map.of(UUID.randomUUID().toString(), "1")),
+ Map.entry("schemaVersion", 1L),
+ Map.entry("registryVersion", 1L),
+ Map.entry("authorityTuple", Map.of()))
+ .entrySet()) {
+ Map record = fixture.registry(token, claims);
+ record.put(change.getKey(), change.getValue());
+ byte[] bytes = AccountControlUiTokenFixture.canonical(record);
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ token,
+ bytes,
+ AccountControlUiTokenFixture.unscopedShape()))
+ .as(change.getKey())
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class)
+ .hasNoCause();
+ }
+ }
+
+ @Test
+ void omittedRequiredEmptyCollectionsAndPrivateDelegationCannotSubstituteForControlUi()
+ throws Exception {
+ for (String field : List.of("scopedRoles", "membershipVersion", "authorityTuple")) {
+ Map claims = fixture.claims(UUID.randomUUID());
+ claims.remove(field);
+ String token = fixture.sign(claims);
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ token,
+ new byte[0],
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ }
+ Map privateClaims = fixture.claims(UUID.randomUUID());
+ privateClaims.put("aud", "account-service");
+ String privateToken = fixture.sign(privateClaims);
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ privateToken,
+ new byte[0],
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ }
+
+ @Test
+ void canonicalRecordMissingRegistryAndLogicalExpiryFailClosed() throws Exception {
+ Map claims = fixture.claims(UUID.randomUUID());
+ String token = fixture.sign(claims);
+ byte[] record = AccountControlUiTokenFixture.canonical(fixture.registry(token, claims));
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ token,
+ null,
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ byte[] whitespace =
+ (" " + new String(record, java.nio.charset.StandardCharsets.UTF_8))
+ .getBytes(java.nio.charset.StandardCharsets.UTF_8);
+ assertThatThrownBy(
+ () ->
+ fixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ token,
+ whitespace,
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ var expiredFixture =
+ new AccountControlUiTokenFixture(
+ Clock.fixed(AccountControlUiTokenFixture.NOW.plusSeconds(900L), ZoneOffset.UTC));
+ String expiredToken = expiredFixture.sign(claims);
+ byte[] expiredRecord =
+ AccountControlUiTokenFixture.canonical(expiredFixture.registry(expiredToken, claims));
+ assertThatThrownBy(
+ () ->
+ expiredFixture
+ .checks()
+ .inspect(
+ "creator-candidate",
+ expiredToken,
+ expiredRecord,
+ AccountControlUiTokenFixture.unscopedShape()))
+ .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class);
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenFixture.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenFixture.java
new file mode 100644
index 0000000000..b1b673e93b
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenFixture.java
@@ -0,0 +1,250 @@
+package unit.net.firedevops.firemud.accountservice.service.controlui;
+
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.MessageDigest;
+import java.security.Signature;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.AuthorityMapShape;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ClaimFieldPresence;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ControlUiShape;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.DeploymentCeilings;
+import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ProfileLimits;
+import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiTokenChecks;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache;
+
+/** Test-only signed records; these do not claim real Account issuance or custody proof. */
+public final class AccountControlUiTokenFixture {
+ public static final Instant NOW = Instant.parse("2026-10-06T10:00:00Z");
+ private static final String KID = "control-ui-test-key";
+ private static final JsonMapper JSON = JsonMapper.builder().build();
+ private final KeyPair keys;
+ private final Clock clock;
+
+ public AccountControlUiTokenFixture(Clock clock) throws Exception {
+ this.clock = clock;
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(3072);
+ this.keys = generator.generateKeyPair();
+ }
+
+ public AccountControlUiTokenChecks checks() {
+ var pin =
+ new AccountPublicJwksCache.SourceIdentity(
+ "test",
+ "cluster-test",
+ "11111111-1111-4111-8111-111111111111",
+ "firemud-test",
+ "22222222-2222-4222-8222-222222222222",
+ "33333333-3333-4333-8333-333333333333",
+ "binding-test",
+ "https://kubernetes.example:6443",
+ "a".repeat(64));
+ RSAPublicKey key = (RSAPublicKey) keys.getPublic();
+ String jwks =
+ "{\"keys\":[{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\""
+ + KID
+ + "\",\"n\":\""
+ + unsigned(key.getModulus().toByteArray())
+ + "\",\"e\":\""
+ + unsigned(key.getPublicExponent().toByteArray())
+ + "\"}]}";
+ var cache =
+ new AccountPublicJwksCache(
+ () ->
+ new AccountPublicJwksCache.PublicJwksSnapshot(
+ pin, jwks.getBytes(StandardCharsets.UTF_8)),
+ pin,
+ clock,
+ Duration.ofSeconds(30));
+ return new AccountControlUiTokenChecks(
+ new AccountAsymmetricJwtVerifier(cache, clock), catalog(), clock);
+ }
+
+ public Map claims(UUID accountId) {
+ Map claims = new LinkedHashMap<>();
+ claims.put("iss", "firemud-account-service");
+ claims.put("aud", "control-ui");
+ claims.put("sub", accountId.toString());
+ claims.put("accountId", accountId.toString());
+ claims.put("jti", UUID.randomUUID().toString());
+ claims.put("iat", NOW.getEpochSecond());
+ claims.put("nbf", NOW.getEpochSecond());
+ claims.put("exp", NOW.getEpochSecond() + 900L);
+ claims.put("tokenGeneration", "1");
+ claims.put("issuanceFence", "1");
+ claims.put("scopedRoles", Map.of());
+ claims.put(
+ "authorityTuple",
+ Map.of(
+ "issuerAuthGeneration",
+ "1",
+ "accountAuthorityGeneration",
+ "1",
+ "tenantAuthorityGeneration",
+ Map.of(),
+ "membershipAuthorityGeneration",
+ Map.of(),
+ "privateRealmGrantVersions",
+ List.of()));
+ claims.put("membershipVersion", Map.of());
+ return claims;
+ }
+
+ public String sign(Map claims) throws Exception {
+ Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
+ String header =
+ encoder.encodeToString(
+ ("{\"alg\":\"RS256\",\"kid\":\"" + KID + "\",\"typ\":\"JWT\"}")
+ .getBytes(StandardCharsets.UTF_8));
+ // JWT payloads need not be JCS. Preserve canonical counter strings and exact numeric negative
+ // cases without rewriting their signed preimage before the verifier sees it.
+ String payload = encoder.encodeToString(JSON.writeValueAsBytes(claims));
+ Signature signer = Signature.getInstance("SHA256withRSA");
+ signer.initSign(keys.getPrivate());
+ signer.update((header + "." + payload).getBytes(StandardCharsets.US_ASCII));
+ return header + "." + payload + "." + encoder.encodeToString(signer.sign());
+ }
+
+ public Map registry(String token, Map claims) throws Exception {
+ Map record = new LinkedHashMap<>();
+ record.put("schemaVersion", 2L);
+ record.put("registryVersion", 2L);
+ record.put(
+ "tokenHash",
+ HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(token.getBytes(StandardCharsets.US_ASCII))));
+ record.put("kid", KID);
+ record.put("signerGeneration", "1");
+ record.put("issuer", "firemud-account-service");
+ record.put("audience", "control-ui");
+ record.put("profile", "control-ui");
+ record.put("type", "control-ui");
+ record.put("operationId", UUID.randomUUID().toString());
+ record.put("requestId", UUID.randomUUID().toString());
+ record.put("requestDigest", "b".repeat(64));
+ record.put("state", "active");
+ for (String field :
+ List.of(
+ "accountId",
+ "jti",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence")) record.put(field, claims.get(field));
+ record.put(
+ "authoritySourceVersions",
+ Map.of(
+ "issuerSourceVersion",
+ 1L,
+ "accountSourceVersion",
+ 1L,
+ "issuanceFenceSourceVersion",
+ 1L));
+ record.put(
+ "authEvidenceBundle",
+ Map.of(
+ "bundleVersion",
+ "1",
+ "sourceVersion",
+ "1",
+ "linearization",
+ "123",
+ "canonicalSha256",
+ "c".repeat(64)));
+ return record;
+ }
+
+ public static ControlUiShape unscopedShape() {
+ return shape(Set.of(), Set.of(), Set.of(), Set.of(), Set.of());
+ }
+
+ public static ControlUiShape shape(
+ Set scopes,
+ Set roles,
+ Set tenants,
+ Set memberships,
+ Set billingSafe) {
+ return new ControlUiShape(
+ new ClaimFieldPresence(
+ true,
+ true,
+ true,
+ true,
+ "control-ui",
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false),
+ new AuthorityMapShape(tenants, memberships, memberships, Set.of(), List.of()),
+ scopes,
+ roles,
+ tenants,
+ memberships,
+ billingSafe,
+ Set.of());
+ }
+
+ public static byte[] canonical(Object value) throws Exception {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value));
+ }
+
+ public static byte[] exactJson(Object value) throws Exception {
+ return JSON.writeValueAsBytes(value);
+ }
+
+ private static AccountTokenProfileCatalog catalog() {
+ return new AccountTokenProfileCatalog(
+ AccountTokenProfileCatalog.VERSION,
+ Map.of(
+ "control-ui",
+ new ProfileLimits(
+ "control-ui", 1800, 4, 4, 4, 4, 0, 8192, 16384, 16384, Optional.of(4)),
+ "player-bootstrap",
+ new ProfileLimits(
+ "player-bootstrap", 300, 0, 0, 0, 0, 0, 8192, 16384, 16384, Optional.empty()),
+ "game-session-account-delegation",
+ new ProfileLimits(
+ "account-service", 300, 1, 1, 1, 1, 1, 8192, 16384, 16384, Optional.empty())),
+ new DeploymentCeilings(16384, 8192, 16384, 1800));
+ }
+
+ private static String unsigned(byte[] value) {
+ byte[] bytes =
+ value.length > 1 && value[0] == 0
+ ? java.util.Arrays.copyOfRange(value, 1, value.length)
+ : value;
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java
new file mode 100644
index 0000000000..8a153c841e
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java
@@ -0,0 +1,103 @@
+package net.firedevops.firemud.common.tenant;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+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;
+
+/** Canonical digest for the distinct Account-initiator qualification on fresh tenant creation. */
+public final class FreshTenantCreatorDigest {
+ private static final int SCHEMA_VERSION = 1;
+ private static final String QUALIFICATION_DOMAIN = "game-design-tenant-creator-qualification/v1";
+ private static final String DIGEST_PREFIX = "sha256:";
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+
+ private FreshTenantCreatorDigest() {}
+
+ /**
+ * Digests every original creation-evidence field, then the initiating Account and Account-owned
+ * authorization identity/digest, using decimal-byte-length-prefixed UTF-8 segments.
+ */
+ public static String evidenceDigest(
+ int schemaVersion,
+ FreshTenantCreationEvidence creationEvidence,
+ UUID initiatingAccountId,
+ UUID accountAuthorizationOperationId,
+ String accountAuthorizationDigest) {
+ if (schemaVersion != SCHEMA_VERSION) {
+ throw new IllegalArgumentException("Unsupported fresh tenant creator evidence version");
+ }
+ Objects.requireNonNull(creationEvidence, "creationEvidence");
+ requireNonNil(initiatingAccountId, "initiatingAccountId");
+ requireNonNil(accountAuthorizationOperationId, "accountAuthorizationOperationId");
+ if (!GameTenantCreationDigest.isDigest(accountAuthorizationDigest)) {
+ throw new IllegalArgumentException(
+ "accountAuthorizationDigest must be a lowercase SHA-256 digest");
+ }
+
+ return digest(
+ QUALIFICATION_DOMAIN,
+ Integer.toString(schemaVersion),
+ Integer.toString(creationEvidence.schemaVersion()),
+ creationEvidence.targetNamespace(),
+ creationEvidence.creationRequestId().toString(),
+ creationEvidence.operationId().toString(),
+ creationEvidence.requestDigest(),
+ creationEvidence.canonicalTenantId().toString(),
+ Long.toString(creationEvidence.sourceGameRowId()),
+ creationEvidence.sourceGameTenantKey(),
+ creationEvidence.provenanceKind(),
+ creationEvidence.evidenceDigest(),
+ initiatingAccountId.toString(),
+ accountAuthorizationOperationId.toString(),
+ accountAuthorizationDigest);
+ }
+
+ private static void requireNonNil(UUID value, String label) {
+ Objects.requireNonNull(value, label);
+ if (NIL_UUID.equals(value)) {
+ throw new IllegalArgumentException(label + " must not be nil");
+ }
+ }
+
+ private static String digest(String... segments) {
+ ByteArrayOutputStream preimage = new ByteArrayOutputStream();
+ for (String segment : segments) {
+ byte[] bytes = encodeUtf8(segment);
+ byte[] length = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
+ preimage.writeBytes(length);
+ preimage.write(':');
+ preimage.writeBytes(bytes);
+ }
+ try {
+ byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray());
+ return DIGEST_PREFIX + HexFormat.of().formatHex(digest);
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private static byte[] encodeUtf8(String value) {
+ Objects.requireNonNull(value, "digest segment");
+ try {
+ ByteBuffer encoded =
+ StandardCharsets.UTF_8
+ .newEncoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .encode(CharBuffer.wrap(value));
+ byte[] bytes = new byte[encoded.remaining()];
+ encoded.get(bytes);
+ return bytes;
+ } catch (CharacterCodingException exception) {
+ throw new IllegalArgumentException("Creator evidence must contain valid Unicode", exception);
+ }
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java
new file mode 100644
index 0000000000..ebdc4bc8a3
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java
@@ -0,0 +1,54 @@
+package net.firedevops.firemud.common.tenant;
+
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * Immutable creator-qualification evidence bound to one exact fresh tenant source operation.
+ *
+ * This record validates a closed digest-bound tuple. The Account UUID and authorization
+ * operation fields are data, not authenticated proof by themselves; the Account-owned producer must
+ * supply and protect their authority.
+ */
+public record FreshTenantCreatorEvidence(
+ int schemaVersion,
+ FreshTenantCreationEvidence creationEvidence,
+ UUID initiatingAccountId,
+ UUID accountAuthorizationOperationId,
+ String accountAuthorizationDigest,
+ String evidenceDigest) {
+ private static final int SCHEMA_VERSION = 1;
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+
+ public FreshTenantCreatorEvidence {
+ if (schemaVersion != SCHEMA_VERSION) {
+ throw new IllegalArgumentException("Unsupported fresh tenant creator evidence version");
+ }
+ Objects.requireNonNull(creationEvidence, "creationEvidence");
+ requireNonNil(initiatingAccountId, "initiatingAccountId");
+ requireNonNil(accountAuthorizationOperationId, "accountAuthorizationOperationId");
+ if (!GameTenantCreationDigest.isDigest(accountAuthorizationDigest)) {
+ throw new IllegalArgumentException(
+ "accountAuthorizationDigest must be a lowercase SHA-256 digest");
+ }
+ Objects.requireNonNull(evidenceDigest, "evidenceDigest");
+ String expectedDigest =
+ FreshTenantCreatorDigest.evidenceDigest(
+ schemaVersion,
+ creationEvidence,
+ initiatingAccountId,
+ accountAuthorizationOperationId,
+ accountAuthorizationDigest);
+ if (!expectedDigest.equals(evidenceDigest)) {
+ throw new IllegalArgumentException(
+ "Creator evidence digest does not match the immutable qualification tuple");
+ }
+ }
+
+ private static void requireNonNil(UUID value, String label) {
+ Objects.requireNonNull(value, label);
+ if (NIL_UUID.equals(value)) {
+ throw new IllegalArgumentException(label + " must not be nil");
+ }
+ }
+}
diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java
new file mode 100644
index 0000000000..91ddb4f2b7
--- /dev/null
+++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java
@@ -0,0 +1,82 @@
+package net.firedevops.firemud.common.tenant;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.UUID;
+import org.junit.jupiter.api.Test;
+
+class FreshTenantCreatorDigestTest {
+ private static final UUID INITIATOR_ID = UUID.fromString("55555555-5555-4555-8555-555555555555");
+ private static final UUID AUTHORIZATION_OPERATION_ID =
+ UUID.fromString("66666666-6666-4666-8666-666666666666");
+ private static final String AUTHORIZATION_DIGEST = "sha256:" + "a".repeat(64);
+
+ @Test
+ void exactTupleProducesStableCanonicalSha256Digest() {
+ FreshTenantCreationEvidence source = freshTenantEvidence();
+
+ String first =
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST);
+ String retry =
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST);
+
+ assertThat(first).matches("sha256:[0-9a-f]{64}").isEqualTo(retry);
+ }
+
+ @Test
+ void rejectsInvalidSchemaNilIdsAndNoncanonicalAccountDigest() {
+ FreshTenantCreationEvidence source = freshTenantEvidence();
+
+ assertThatThrownBy(
+ () ->
+ FreshTenantCreatorDigest.evidenceDigest(
+ 2, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, new UUID(0L, 0L), AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATOR_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, "bad"))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ private static FreshTenantCreationEvidence freshTenantEvidence() {
+ UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111");
+ UUID operationId = UUID.fromString("22222222-2222-4222-8222-222222222222");
+ UUID tenantId = UUID.fromString("33333333-3333-4333-8333-333333333333");
+ String sourceKey = "new-game-owner-key";
+ String requestDigest =
+ GameTenantCreationDigest.requestDigest("prod", requestId, sourceKey, "World", null);
+ return new FreshTenantCreationEvidence(
+ 1,
+ "prod",
+ requestId,
+ operationId,
+ requestDigest,
+ tenantId,
+ 42L,
+ sourceKey,
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ "prod",
+ requestId,
+ operationId,
+ requestDigest,
+ tenantId,
+ 42L,
+ sourceKey,
+ "NEW_GAME_ROW"));
+ }
+}
diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java
new file mode 100644
index 0000000000..d72cfac8dd
--- /dev/null
+++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java
@@ -0,0 +1,153 @@
+package net.firedevops.firemud.common.tenant;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.UUID;
+import org.junit.jupiter.api.Test;
+
+class FreshTenantCreatorEvidenceTest {
+ private static final UUID INITIATOR_ID = UUID.fromString("55555555-5555-4555-8555-555555555555");
+ private static final UUID AUTHORIZATION_OPERATION_ID =
+ UUID.fromString("66666666-6666-4666-8666-666666666666");
+ private static final String AUTHORIZATION_DIGEST = "sha256:" + "a".repeat(64);
+
+ @Test
+ void acceptsExactCreatorQualificationWithoutChangingOriginalCreationEvidence() {
+ FreshTenantCreationEvidence source = freshTenantEvidence();
+ String creatorDigest =
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST);
+
+ FreshTenantCreatorEvidence qualification =
+ new FreshTenantCreatorEvidence(
+ 1,
+ source,
+ INITIATOR_ID,
+ AUTHORIZATION_OPERATION_ID,
+ AUTHORIZATION_DIGEST,
+ creatorDigest);
+
+ assertThat(qualification.creationEvidence()).isSameAs(source);
+ assertThat(qualification.initiatingAccountId()).isEqualTo(INITIATOR_ID);
+ assertThat(qualification.accountAuthorizationOperationId())
+ .isEqualTo(AUTHORIZATION_OPERATION_ID);
+ assertThat(qualification.accountAuthorizationDigest()).isEqualTo(AUTHORIZATION_DIGEST);
+ assertThat(qualification.evidenceDigest()).isEqualTo(creatorDigest);
+ }
+
+ @Test
+ void rejectsUnsupportedVersionNilIdentitiesMalformedAuthorizationDigestAndChangedBinding() {
+ FreshTenantCreationEvidence source = freshTenantEvidence();
+ String digest =
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST);
+
+ assertInvalid(
+ 2, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST, digest);
+ assertInvalid(
+ 1, source, new UUID(0L, 0L), AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST, digest);
+ assertInvalid(1, source, INITIATOR_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST, digest);
+ assertInvalid(
+ 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, "SHA256:" + "a".repeat(64), digest);
+ assertInvalid(
+ 1,
+ source,
+ INITIATOR_ID,
+ AUTHORIZATION_OPERATION_ID,
+ AUTHORIZATION_DIGEST,
+ "sha256:" + "b".repeat(64));
+ }
+
+ @Test
+ void creatorDigestBindsEveryCreationReceiptAndAuthorizationIdentity() {
+ FreshTenantCreationEvidence source = freshTenantEvidence();
+ String original =
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST);
+
+ assertThat(
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1,
+ source,
+ UUID.fromString("77777777-7777-4777-8777-777777777777"),
+ AUTHORIZATION_OPERATION_ID,
+ AUTHORIZATION_DIGEST))
+ .isNotEqualTo(original);
+ assertThat(
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1,
+ source,
+ INITIATOR_ID,
+ UUID.fromString("77777777-7777-4777-8777-777777777777"),
+ AUTHORIZATION_DIGEST))
+ .isNotEqualTo(original);
+ assertThat(
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, "sha256:" + "b".repeat(64)))
+ .isNotEqualTo(original);
+
+ FreshTenantCreationEvidence changedSource =
+ freshTenantEvidence(
+ UUID.fromString("88888888-8888-4888-8888-888888888888"),
+ source.sourceGameRowId() + 1,
+ source.sourceGameTenantKey());
+ assertThat(
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, changedSource, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST))
+ .isNotEqualTo(original);
+ }
+
+ private static void assertInvalid(
+ int schemaVersion,
+ FreshTenantCreationEvidence source,
+ UUID initiatingAccountId,
+ UUID authorizationOperationId,
+ String authorizationDigest,
+ String evidenceDigest) {
+ assertThatThrownBy(
+ () ->
+ new FreshTenantCreatorEvidence(
+ schemaVersion,
+ source,
+ initiatingAccountId,
+ authorizationOperationId,
+ authorizationDigest,
+ evidenceDigest))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ private static FreshTenantCreationEvidence freshTenantEvidence() {
+ return freshTenantEvidence(
+ UUID.fromString("33333333-3333-4333-8333-333333333333"), 42L, "new-game-owner-key");
+ }
+
+ private static FreshTenantCreationEvidence freshTenantEvidence(
+ UUID canonicalTenantId, long sourceRowId, String sourceKey) {
+ UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111");
+ UUID operationId = UUID.fromString("22222222-2222-4222-8222-222222222222");
+ String requestDigest =
+ GameTenantCreationDigest.requestDigest("prod", requestId, sourceKey, "World", null);
+ String sourceDigest =
+ GameTenantCreationDigest.evidenceDigest(
+ "prod",
+ requestId,
+ operationId,
+ requestDigest,
+ canonicalTenantId,
+ sourceRowId,
+ sourceKey,
+ "NEW_GAME_ROW");
+ return new FreshTenantCreationEvidence(
+ 1,
+ "prod",
+ requestId,
+ operationId,
+ requestDigest,
+ canonicalTenantId,
+ sourceRowId,
+ sourceKey,
+ "NEW_GAME_ROW",
+ sourceDigest);
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifier.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifier.java
new file mode 100644
index 0000000000..fd8c041013
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifier.java
@@ -0,0 +1,370 @@
+package net.firedevops.firemud.common.security;
+
+import com.fasterxml.jackson.core.StreamReadFeature;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jws;
+import io.jsonwebtoken.Jwts;
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/**
+ * Strict RS256 compact-JWT verification for an explicitly selected route/profile policy.
+ *
+ *
The result is immutable validated claims only. It is not an authenticated principal, admission
+ * decision, SecurityContext, active-registry proof, or current Account authority proof.
+ */
+public final class AccountAsymmetricJwtVerifier {
+ private static final int MAX_HEADER_BYTES = 2 * 1024;
+ private static final int MAX_CLAIMS_BYTES = 12 * 1024;
+ private static final int MAX_COMPACT_TOKEN_BYTES = 16 * 1024;
+ private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+ .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .build();
+ private static final TypeReference> OBJECT = new TypeReference<>() {};
+
+ private final AccountPublicJwksCache keyCache;
+ private final Clock clock;
+
+ public AccountAsymmetricJwtVerifier(AccountPublicJwksCache keyCache, Clock clock) {
+ this.keyCache = Objects.requireNonNull(keyCache, "Account public JWKS cache is required");
+ this.clock = Objects.requireNonNull(clock, "clock is required");
+ }
+
+ /** Verifies a compact RS256 signature and exact route policy without granting authority. */
+ public VerifiedClaims verify(String compactJwt, ExplicitRouteProfilePolicy policy) {
+ Objects.requireNonNull(policy, "explicit route/profile policy is required");
+ try {
+ CompactParts parts = splitCompact(compactJwt, policy.maxCompactTokenBytes());
+ Map header = parseObject(parts.header(), MAX_HEADER_BYTES);
+ String keyId = validateHeader(header);
+ Map claims = parseObject(parts.claims(), MAX_CLAIMS_BYTES);
+ validateClaims(claims, policy, clock.instant());
+
+ RSAPublicKey key = keyCache.keyFor(keyId);
+ Jws verified =
+ Jwts.parser()
+ .verifyWith(key)
+ .clock(() -> Date.from(clock.instant()))
+ .clockSkewSeconds(policy.allowedClockSkewSeconds())
+ .build()
+ .parseSignedClaims(compactJwt);
+ if (!"RS256".equals(verified.getHeader().getAlgorithm())
+ || !keyId.equals(verified.getHeader().getKeyId())) {
+ throw new VerificationException();
+ }
+ Map immutableClaims = deepImmutableMap(claims);
+ policy.claimShapeValidator().validate(immutableClaims);
+ return new VerifiedClaims(
+ policy.routeId(), policy.profile(), policy.tokenType(), keyId, immutableClaims);
+ } catch (AccountPublicJwksCache.SourceUnavailableException ex) {
+ throw new VerificationUnavailableException();
+ } catch (VerificationException ex) {
+ throw ex;
+ } catch (RuntimeException ex) {
+ // Do not retain token, source, JWK, or parser details in externally visible failures.
+ throw new VerificationException();
+ }
+ }
+
+ private static CompactParts splitCompact(String compactJwt, int maximumBytes) {
+ if (compactJwt == null
+ || compactJwt.isEmpty()
+ || compactJwt.length() > maximumBytes
+ || compactJwt.length() > MAX_COMPACT_TOKEN_BYTES) {
+ throw new VerificationException();
+ }
+ for (int index = 0; index < compactJwt.length(); index++) {
+ if (compactJwt.charAt(index) > 0x7f) {
+ throw new VerificationException();
+ }
+ }
+ String[] parts = compactJwt.split("\\.", -1);
+ if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty() || parts[2].isEmpty()) {
+ throw new VerificationException();
+ }
+ return new CompactParts(
+ decodeSegment(parts[0]), decodeSegment(parts[1]), decodeSegment(parts[2]));
+ }
+
+ private static byte[] decodeSegment(String segment) {
+ if (!segment.matches("[A-Za-z0-9_-]+")) {
+ throw new VerificationException();
+ }
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(segment);
+ if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(segment)) {
+ throw new VerificationException();
+ }
+ return decoded;
+ } catch (IllegalArgumentException ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static String validateHeader(Map header) {
+ if (!Set.of("alg", "kid", "typ").containsAll(header.keySet())
+ || !header.keySet().containsAll(Set.of("alg", "kid"))
+ || !"RS256".equals(header.get("alg"))
+ || !(header.get("kid") instanceof String kid)
+ || !KID.matcher(kid).matches()
+ || (header.containsKey("typ") && !"JWT".equals(header.get("typ")))) {
+ throw new VerificationException();
+ }
+ return kid;
+ }
+
+ private static Map parseObject(byte[] bytes, int maximumBytes) {
+ if (bytes.length == 0 || bytes.length > maximumBytes) {
+ throw new VerificationException();
+ }
+ try {
+ String json =
+ StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ Map parsed = JSON.readValue(json, OBJECT);
+ if (parsed == null) {
+ throw new VerificationException();
+ }
+ return parsed;
+ } catch (VerificationException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static void validateClaims(
+ Map claims, ExplicitRouteProfilePolicy policy, Instant now) {
+ if (!policy.allowedClaims().containsAll(claims.keySet())
+ || !claims.keySet().containsAll(policy.requiredClaims())
+ || !policy.issuer().equals(claims.get("iss"))
+ || !policy.audience().equals(claims.get("aud"))) {
+ throw new VerificationException();
+ }
+ long issuedAt = positiveIntegerClaim(claims, "iat");
+ long notBefore = positiveIntegerClaim(claims, "nbf");
+ long expiresAt = positiveIntegerClaim(claims, "exp");
+ long nowSeconds = now.getEpochSecond();
+ long skew = policy.allowedClockSkewSeconds();
+ if (issuedAt > safeAdd(nowSeconds, skew)
+ || notBefore > safeAdd(nowSeconds, skew)
+ || expiresAt <= safeSubtract(nowSeconds, skew)
+ || notBefore > expiresAt
+ || issuedAt >= expiresAt
+ || safeSubtract(notBefore, issuedAt) > skew
+ || safeSubtract(expiresAt, issuedAt) > policy.maximumLifetimeSeconds()) {
+ throw new VerificationException();
+ }
+
+ requireNonEmptyText(claims, "sub");
+ requireNonEmptyText(claims, "jti");
+ if (claims.containsKey("accountId")) {
+ requireNonEmptyText(claims, "accountId");
+ }
+ if (claims.containsKey("tokenGeneration")) {
+ AccountJwtExactValues.positiveDecimalCounter(claims.get("tokenGeneration"));
+ }
+ if (claims.containsKey("issuanceFence")) {
+ AccountJwtExactValues.positiveDecimalCounter(claims.get("issuanceFence"));
+ }
+ if (claims.containsKey("authorityTuple")
+ && !(claims.get("authorityTuple") instanceof Map, ?>)) {
+ throw new VerificationException();
+ }
+ if (claims.containsKey("membershipVersion")
+ && !(claims.get("membershipVersion") instanceof Map, ?>)) {
+ throw new VerificationException();
+ }
+ }
+
+ private static long positiveIntegerClaim(Map claims, String field) {
+ Object value = claims.get(field);
+ if (!(value instanceof Number number)) {
+ throw new VerificationException();
+ }
+ try {
+ long result = new BigDecimal(number.toString()).longValueExact();
+ if (result <= 0L) {
+ throw new VerificationException();
+ }
+ return result;
+ } catch (ArithmeticException | NumberFormatException ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static void requireNonEmptyText(Map claims, String field) {
+ if (!(claims.get(field) instanceof String value) || value.isBlank() || value.length() > 512) {
+ throw new VerificationException();
+ }
+ }
+
+ private static long safeAdd(long left, long right) {
+ try {
+ return Math.addExact(left, right);
+ } catch (ArithmeticException ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static long safeSubtract(long left, long right) {
+ try {
+ return Math.subtractExact(left, right);
+ } catch (ArithmeticException ex) {
+ throw new VerificationException();
+ }
+ }
+
+ private static Map deepImmutableMap(Map source) {
+ Map result = new LinkedHashMap<>();
+ source.forEach((key, value) -> result.put(key, immutableValue(value)));
+ return Collections.unmodifiableMap(result);
+ }
+
+ private static Object immutableValue(Object value) {
+ if (value instanceof Map, ?> map) {
+ Map copy = new LinkedHashMap<>();
+ for (Map.Entry, ?> entry : map.entrySet()) {
+ if (!(entry.getKey() instanceof String key)) {
+ throw new VerificationException();
+ }
+ copy.put(key, immutableValue(entry.getValue()));
+ }
+ return Collections.unmodifiableMap(copy);
+ }
+ if (value instanceof List> list) {
+ List copy = new ArrayList<>(list.size());
+ for (Object item : list) {
+ copy.add(immutableValue(item));
+ }
+ return Collections.unmodifiableList(copy);
+ }
+ if (value == null
+ || value instanceof String
+ || value instanceof Number
+ || value instanceof Boolean) {
+ return value;
+ }
+ throw new VerificationException();
+ }
+
+ /** Explicit, caller-owned policy for one route and one token profile/type pair. */
+ public record ExplicitRouteProfilePolicy(
+ String routeId,
+ String profile,
+ String tokenType,
+ String issuer,
+ String audience,
+ Set requiredClaims,
+ Set optionalClaims,
+ long maximumLifetimeSeconds,
+ long allowedClockSkewSeconds,
+ int maxCompactTokenBytes,
+ ClaimShapeValidator claimShapeValidator) {
+ public ExplicitRouteProfilePolicy {
+ if (routeId == null
+ || routeId.isBlank()
+ || profile == null
+ || profile.isBlank()
+ || tokenType == null
+ || tokenType.isBlank()
+ || issuer == null
+ || issuer.isBlank()
+ || audience == null
+ || audience.isBlank()
+ || requiredClaims == null
+ || optionalClaims == null
+ || claimShapeValidator == null
+ || maximumLifetimeSeconds <= 0L
+ || allowedClockSkewSeconds < 0L
+ || allowedClockSkewSeconds > 60L
+ || maxCompactTokenBytes <= 0
+ || maxCompactTokenBytes > MAX_COMPACT_TOKEN_BYTES) {
+ throw new IllegalArgumentException("Account JWT route profile policy is invalid");
+ }
+ Set required = Set.copyOf(requiredClaims);
+ Set optional = Set.copyOf(optionalClaims);
+ if (required.isEmpty()
+ || !required.containsAll(Set.of("iss", "aud", "sub", "jti", "iat", "nbf", "exp"))
+ || !Collections.disjoint(required, optional)
+ || required.stream().anyMatch(value -> value == null || value.isBlank())
+ || optional.stream().anyMatch(value -> value == null || value.isBlank())) {
+ throw new IllegalArgumentException("Account JWT route profile policy is invalid");
+ }
+ requiredClaims = Collections.unmodifiableSet(new LinkedHashSet<>(required));
+ optionalClaims = Collections.unmodifiableSet(new LinkedHashSet<>(optional));
+ }
+
+ public Set allowedClaims() {
+ Set result = new LinkedHashSet<>(requiredClaims);
+ result.addAll(optionalClaims);
+ return Collections.unmodifiableSet(result);
+ }
+ }
+
+ /** Exact profile-shape validation performed only after the compact signature is verified. */
+ @FunctionalInterface
+ public interface ClaimShapeValidator {
+ void validate(Map immutableClaims);
+ }
+
+ /** Immutable claims and route metadata; intentionally carries no principal or authority. */
+ public record VerifiedClaims(
+ String routeId, String profile, String tokenType, String keyId, Map claims) {
+ public VerifiedClaims {
+ Objects.requireNonNull(routeId, "route ID is required");
+ Objects.requireNonNull(profile, "profile metadata is required");
+ Objects.requireNonNull(tokenType, "token type metadata is required");
+ Objects.requireNonNull(keyId, "verified key ID is required");
+ claims = deepImmutableMap(Objects.requireNonNull(claims, "verified claims are required"));
+ }
+
+ @Override
+ public Map claims() {
+ return deepImmutableMap(claims);
+ }
+ }
+
+ public static final class VerificationException extends RuntimeException {
+ public VerificationException() {
+ super("Account JWT verification failed");
+ }
+ }
+
+ /** A retryable trust-source outage, distinct from invalid or revoked token evidence. */
+ public static final class VerificationUnavailableException extends RuntimeException {
+ public VerificationUnavailableException() {
+ super("Account JWT verification is unavailable");
+ }
+ }
+
+ private record CompactParts(byte[] header, byte[] claims, byte[] signature) {}
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtExactValues.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtExactValues.java
new file mode 100644
index 0000000000..509c70a852
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtExactValues.java
@@ -0,0 +1,113 @@
+package net.firedevops.firemud.common.security;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.List;
+import java.util.Map;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+
+/** Exact counter and complete JSON-value comparisons at Account JWT inspection boundaries. */
+public final class AccountJwtExactValues {
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+ .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .build();
+
+ private AccountJwtExactValues() {}
+
+ /**
+ * Parses an exact positive JSON number for numeric epoch/schema fields and separately owned
+ * source evidence. Authority counters use {@link #positiveDecimalCounter(Object)} instead.
+ */
+ public static BigInteger positiveCounter(Object value) {
+ if (!(value instanceof Number number)) throw invalid();
+ try {
+ BigInteger integer = exactNumber(number).toBigIntegerExact();
+ if (integer.signum() <= 0) throw invalid();
+ return integer;
+ } catch (ArithmeticException failure) {
+ throw invalid();
+ }
+ }
+
+ /** Parses canonical positive decimal-string authority counters without a BIGINT ceiling. */
+ public static BigInteger positiveDecimalCounter(Object value) {
+ if (!(value instanceof String text) || !text.matches("[1-9][0-9]*")) throw invalid();
+ return new BigInteger(text);
+ }
+
+ /** Parses a canonical unsigned decimal string where the owning field permits zero. */
+ public static BigInteger nonNegativeDecimalCounter(Object value) {
+ if (!(value instanceof String text) || !text.matches("0|[1-9][0-9]*")) throw invalid();
+ return new BigInteger(text);
+ }
+
+ /**
+ * Compares the complete nested JSON structure and exact numeric values. RFC 8785 bytes are not an
+ * equality oracle: its binary64 rendering can collapse adjacent large integers.
+ */
+ public static boolean sameJsonValue(Object left, Object right) {
+ if (left == null || right == null) return left == right;
+ if (left instanceof Number leftNumber && right instanceof Number rightNumber) {
+ try {
+ return exactNumber(leftNumber).compareTo(exactNumber(rightNumber)) == 0;
+ } catch (IllegalArgumentException failure) {
+ return false;
+ }
+ }
+ if (left instanceof Map, ?> leftMap && right instanceof Map, ?> rightMap) {
+ if (!leftMap.keySet().equals(rightMap.keySet())) return false;
+ for (Map.Entry, ?> entry : leftMap.entrySet()) {
+ if (!(entry.getKey() instanceof String)
+ || !sameJsonValue(entry.getValue(), rightMap.get(entry.getKey()))) return false;
+ }
+ return true;
+ }
+ if (left instanceof List> leftList && right instanceof List> rightList) {
+ if (leftList.size() != rightList.size()) return false;
+ for (int index = 0; index < leftList.size(); index++) {
+ if (!sameJsonValue(leftList.get(index), rightList.get(index))) return false;
+ }
+ return true;
+ }
+ return (left instanceof String && right instanceof String
+ || left instanceof Boolean && right instanceof Boolean)
+ && left.equals(right);
+ }
+
+ /**
+ * Measures the required canonical bytes only when their exact decoded values survive unchanged.
+ * Unrepresentable numeric candidates fail; no wire type is changed to rescue a candidate.
+ */
+ public static byte[] losslessCanonicalBytes(Object value) {
+ try {
+ byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value));
+ Object decoded = JSON.readValue(canonical, Object.class);
+ if (!sameJsonValue(value, decoded)) throw invalid();
+ return canonical;
+ } catch (IOException | RuntimeException failure) {
+ throw invalid();
+ }
+ }
+
+ private static BigDecimal exactNumber(Number value) {
+ if (value instanceof BigInteger integer) return new BigDecimal(integer);
+ if (value instanceof BigDecimal decimal) return decimal;
+ if (value instanceof Byte
+ || value instanceof Short
+ || value instanceof Integer
+ || value instanceof Long) {
+ return BigDecimal.valueOf(value.longValue());
+ }
+ // Binary floating-point values cannot establish the original exact counter preimage.
+ throw invalid();
+ }
+
+ private static IllegalArgumentException invalid() {
+ return new IllegalArgumentException("Account JWT numeric value is not exact");
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java
new file mode 100644
index 0000000000..30f12d4270
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java
@@ -0,0 +1,287 @@
+package net.firedevops.firemud.common.security;
+
+import java.math.BigInteger;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+
+/** Shared exact-shape helpers for the Account JWT profile validators. */
+final class AccountJwtProfileClaimSupport {
+ static final Set REQUIRED_BASE_CLAIMS =
+ Set.of(
+ "iss",
+ "sub",
+ "jti",
+ "accountId",
+ "aud",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence");
+ static final Set AUTHORITY_TUPLE_FIELDS =
+ Set.of(
+ "issuerAuthGeneration",
+ "accountAuthorityGeneration",
+ "tenantAuthorityGeneration",
+ "membershipAuthorityGeneration",
+ "privateRealmGrantVersions");
+
+ private AccountJwtProfileClaimSupport() {}
+
+ static void requireClaimFields(
+ Map claims, Set required, Set optional) {
+ if (claims == null
+ || !claims.keySet().containsAll(required)
+ || !union(required, optional).containsAll(claims.keySet())) {
+ throw invalid();
+ }
+ }
+
+ static void requireCommonIdentity(Map claims, String issuer, String audience) {
+ if (!issuer.equals(claims.get("iss")) || !audience.equals(claims.get("aud"))) {
+ throw invalid();
+ }
+ String subject = requireUuid(claims.get("sub"));
+ String accountId = requireUuid(claims.get("accountId"));
+ requireUuid(claims.get("jti"));
+ if (!subject.equals(accountId)) {
+ throw invalid();
+ }
+ requirePositiveLong(claims.get("iat"));
+ requirePositiveLong(claims.get("nbf"));
+ requirePositiveLong(claims.get("exp"));
+ requirePositiveCounter(claims.get("tokenGeneration"));
+ requirePositiveCounter(claims.get("issuanceFence"));
+ }
+
+ static String requireUuid(Object value) {
+ if (!(value instanceof String text)) {
+ throw invalid();
+ }
+ try {
+ UUID uuid = UUID.fromString(text);
+ if (!uuid.toString().equals(text) || new UUID(0L, 0L).equals(uuid)) {
+ throw invalid();
+ }
+ return text;
+ } catch (IllegalArgumentException failure) {
+ throw invalid();
+ }
+ }
+
+ static long requirePositiveLong(Object value) {
+ try {
+ return AccountJwtExactValues.positiveCounter(value).longValueExact();
+ } catch (IllegalArgumentException | ArithmeticException failure) {
+ throw invalid();
+ }
+ }
+
+ static Map requireObjectMap(Object value) {
+ if (!(value instanceof Map, ?> source)) {
+ throw invalid();
+ }
+ Map result = new LinkedHashMap<>();
+ for (Map.Entry, ?> entry : source.entrySet()) {
+ if (!(entry.getKey() instanceof String key)) {
+ throw invalid();
+ }
+ result.put(key, entry.getValue());
+ }
+ return result;
+ }
+
+ static BigInteger requirePositiveCounter(Object value) {
+ try {
+ return AccountJwtExactValues.positiveDecimalCounter(value);
+ } catch (IllegalArgumentException failure) {
+ throw invalid();
+ }
+ }
+
+ static Map requireGenerationMap(Object value) {
+ Map source = requireObjectMap(value);
+ Map result = new LinkedHashMap<>();
+ source.forEach(
+ (key, generation) -> {
+ requireUuid(key);
+ result.put(key, requirePositiveCounter(generation));
+ });
+ return result;
+ }
+
+ static void requireRoleList(Object value) {
+ if (!(value instanceof List> roles)) {
+ throw invalid();
+ }
+ Set distinct = new java.util.HashSet<>();
+ for (Object role : roles) {
+ if (!(role instanceof String text)
+ || text.isBlank()
+ || text.length() > 64
+ || text.codePoints().anyMatch(Character::isISOControl)
+ || !distinct.add(text)) {
+ throw invalid();
+ }
+ }
+ }
+
+ static Map requireAuthorityTuple(
+ Object value,
+ boolean allowTenantBillingCutoff,
+ boolean requireUnscoped,
+ boolean requireAccountCutoffForAdvancedGeneration,
+ long maximumAuthorityTupleBytes) {
+ Map tuple = requireObjectMap(value);
+ Set allowed = new java.util.HashSet<>(AUTHORITY_TUPLE_FIELDS);
+ allowed.add("accountSecurityCutoff");
+ if (allowTenantBillingCutoff) {
+ allowed.add("tenantBillingCutoff");
+ }
+ if (!allowed.containsAll(tuple.keySet())
+ || !tuple.keySet().containsAll(AUTHORITY_TUPLE_FIELDS)) {
+ throw invalid();
+ }
+ requirePositiveCounter(tuple.get("issuerAuthGeneration"));
+ requirePositiveCounter(tuple.get("accountAuthorityGeneration"));
+ Map tenantGenerations =
+ requireGenerationMap(tuple.get("tenantAuthorityGeneration"));
+ Map membershipGenerations =
+ requireGenerationMap(tuple.get("membershipAuthorityGeneration"));
+ if (requireUnscoped && (!tenantGenerations.isEmpty() || !membershipGenerations.isEmpty())) {
+ throw invalid();
+ }
+ if (!(tuple.get("privateRealmGrantVersions") instanceof List> grants)) {
+ throw invalid();
+ }
+ if (requireUnscoped && !grants.isEmpty()) {
+ throw invalid();
+ }
+ requireAuthorityTupleByteBound(tuple, maximumAuthorityTupleBytes);
+ BigInteger accountGeneration = requirePositiveCounter(tuple.get("accountAuthorityGeneration"));
+ Object accountCutoff = tuple.get("accountSecurityCutoff");
+ if (tuple.containsKey("accountSecurityCutoff")) {
+ if (accountCutoff == null) {
+ throw invalid();
+ }
+ validateAccountSecurityCutoff(accountCutoff, accountGeneration);
+ } else if (requireAccountCutoffForAdvancedGeneration
+ && !accountGeneration.equals(BigInteger.ONE)) {
+ throw invalid();
+ }
+ Object billingCutoff = tuple.get("tenantBillingCutoff");
+ if (tuple.containsKey("tenantBillingCutoff")) {
+ if (!allowTenantBillingCutoff || billingCutoff == null) {
+ throw invalid();
+ }
+ validateTenantBillingCutoff(billingCutoff);
+ }
+ return tuple;
+ }
+
+ static Map requireVersionMap(Object value) {
+ Map source = requireObjectMap(value);
+ Map result = new LinkedHashMap<>();
+ source.forEach(
+ (key, version) -> {
+ requireUuid(key);
+ try {
+ result.put(key, AccountJwtExactValues.nonNegativeDecimalCounter(version));
+ } catch (IllegalArgumentException failure) {
+ throw invalid();
+ }
+ });
+ return result;
+ }
+
+ static void validateAccountSecurityCutoff(Object value, BigInteger accountGeneration) {
+ Map cutoff = requireObjectMap(value);
+ if (!cutoff
+ .keySet()
+ .equals(Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"))) {
+ throw invalid();
+ }
+ if (!(cutoff.get("accountAuthorityGeneration") instanceof String generation)
+ || !(cutoff.get("outboxStreamKey") instanceof String streamKey)
+ || !(cutoff.get("outboxSequence") instanceof String sequence)) {
+ throw invalid();
+ }
+ if (accountGeneration.compareTo(BigInteger.ONE) <= 0
+ || !accountGeneration.toString().equals(generation)
+ || streamKey.length() > 2048
+ || !streamKey.startsWith("account:auth-authority:v1:account/")
+ || streamKey.codePoints().anyMatch(Character::isISOControl)) {
+ throw invalid();
+ }
+ try {
+ AccountJwtExactValues.positiveDecimalCounter(sequence);
+ requireUuid(streamKey.substring("account:auth-authority:v1:account/".length()));
+ } catch (RuntimeException failure) {
+ throw invalid();
+ }
+ }
+
+ private static void validateTenantBillingCutoff(Object value) {
+ Map cutoffs = requireObjectMap(value);
+ if (cutoffs.isEmpty()) {
+ throw invalid();
+ }
+ cutoffs.forEach(
+ (tenantId, cutoffValue) -> {
+ requireUuid(tenantId);
+ Map cutoff = requireObjectMap(cutoffValue);
+ if (!cutoff
+ .keySet()
+ .equals(
+ Set.of(
+ "tenantAuthorityGeneration",
+ "tenantBillingSequence",
+ "outboxStreamKey",
+ "outboxSequence"))) {
+ throw invalid();
+ }
+ requirePositiveCounter(cutoff.get("tenantAuthorityGeneration"));
+ requirePositiveCounter(cutoff.get("tenantBillingSequence"));
+ requirePositiveCounter(cutoff.get("outboxSequence"));
+ requireBoundedText(cutoff.get("outboxStreamKey"), 2048);
+ });
+ }
+
+ static void requireBoundedText(Object value, int maximumLength) {
+ if (!(value instanceof String text)
+ || text.isBlank()
+ || text.length() > maximumLength
+ || text.codePoints().anyMatch(Character::isISOControl)) {
+ throw invalid();
+ }
+ }
+
+ static AccountAsymmetricJwtVerifier.VerificationException invalid() {
+ return new AccountAsymmetricJwtVerifier.VerificationException();
+ }
+
+ private static Set union(Set required, Set optional) {
+ Set result = new java.util.HashSet<>(Objects.requireNonNull(required));
+ result.addAll(Objects.requireNonNull(optional));
+ return result;
+ }
+
+ private static void requireAuthorityTupleByteBound(
+ Map tuple, long maximumAuthorityTupleBytes) {
+ byte[] canonicalBytes;
+ try {
+ canonicalBytes = AccountJwtExactValues.losslessCanonicalBytes(tuple);
+ } catch (IllegalArgumentException failure) {
+ throw invalid();
+ }
+ if (maximumAuthorityTupleBytes <= 0L || canonicalBytes.length > maximumAuthorityTupleBytes) {
+ throw invalid();
+ }
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java
new file mode 100644
index 0000000000..c38e8ad9d2
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java
@@ -0,0 +1,442 @@
+package net.firedevops.firemud.common.security;
+
+import com.fasterxml.jackson.core.StreamReadFeature;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.URI;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.KeyFactory;
+import java.security.MessageDigest;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.RSAPublicKeySpec;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/**
+ * A finite public-only RS256 key cache bound to one owner-supplied, authenticated JWKS source.
+ *
+ * The source and its identity pin are deliberately injected by the owning service. This class
+ * does not discover endpoints, read Kubernetes credentials, or establish signer readiness. A
+ * verified key is only cryptographic evidence; callers still have to prove active registry state
+ * and current Account authority independently.
+ */
+public final class AccountPublicJwksCache {
+ public static final int MAX_JWKS_BYTES = 256 * 1024;
+ public static final int MAX_KEYS = 64;
+ private static final int MAX_REMEMBERED_KIDS = 256;
+ private static final int MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT = 256;
+ private static final Duration STALE_SOURCE_RETRY_BACKOFF = Duration.ofSeconds(1);
+ private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+ private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?");
+ private static final Pattern UID =
+ 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 CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}");
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+ private static final TypeReference> OBJECT = new TypeReference<>() {};
+
+ private final TrustedPublicJwksSource source;
+ private final SourceIdentity expectedSource;
+ private final Clock clock;
+ private final Duration maximumAge;
+ private final Object monitor = new Object();
+ private final Map rememberedFingerprints = new LinkedHashMap<>();
+ private final Set hardDeniedKids = new LinkedHashSet<>();
+
+ private Map keys = Map.of();
+ private Instant loadedAt;
+ private String loadedJwksFingerprint;
+ private Instant lastStaleSourceUnavailableAt;
+ private final Set unknownKidsRefreshedForSnapshot = new LinkedHashSet<>();
+
+ public AccountPublicJwksCache(
+ TrustedPublicJwksSource source,
+ SourceIdentity expectedSource,
+ Clock clock,
+ Duration maximumAge) {
+ this.source = Objects.requireNonNull(source, "trusted public JWKS source is required");
+ this.expectedSource = Objects.requireNonNull(expectedSource, "source pin is required");
+ this.clock = Objects.requireNonNull(clock, "clock is required");
+ this.maximumAge = Objects.requireNonNull(maximumAge, "maximum cache age is required");
+ if (maximumAge.isNegative()
+ || maximumAge.isZero()
+ || maximumAge.compareTo(Duration.ofMinutes(5)) > 0) {
+ throw new IllegalArgumentException("Account public JWKS cache age is outside its bound");
+ }
+ }
+
+ /** Returns a currently usable key, forcing at most one bounded refresh for an unknown kid. */
+ public RSAPublicKey keyFor(String kid) {
+ if (kid == null || !KID.matcher(kid).matches()) {
+ throw new UnknownKeyException();
+ }
+ synchronized (monitor) {
+ rejectHardDenied(kid);
+ Instant now = clock.instant();
+ if (!isFresh(now)
+ && lastStaleSourceUnavailableAt != null
+ && !now.isBefore(lastStaleSourceUnavailableAt)
+ && Duration.between(lastStaleSourceUnavailableAt, now)
+ .compareTo(STALE_SOURCE_RETRY_BACKOFF)
+ < 0) {
+ throw new SourceUnavailableException();
+ }
+ if (isFresh(now)) {
+ RSAPublicKey existing = keys.get(kid);
+ if (existing != null) {
+ return existing;
+ }
+ if (!unknownKidsRefreshedForSnapshot.contains(kid)
+ && unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ unknownKidsRefreshedForSnapshot.add(kid);
+ refreshFromSource();
+ rejectHardDenied(kid);
+ RSAPublicKey refreshed = keys.get(kid);
+ if (refreshed != null) {
+ return refreshed;
+ }
+ if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ unknownKidsRefreshedForSnapshot.add(kid);
+ }
+ }
+ throw new UnknownKeyException();
+ }
+
+ try {
+ refreshFromSource();
+ } catch (SourceUnavailableException unavailable) {
+ lastStaleSourceUnavailableAt = clock.instant();
+ if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ unknownKidsRefreshedForSnapshot.add(kid);
+ }
+ throw unavailable;
+ }
+ lastStaleSourceUnavailableAt = null;
+ rejectHardDenied(kid);
+ RSAPublicKey refreshed = keys.get(kid);
+ if (refreshed == null) {
+ if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) {
+ unknownKidsRefreshedForSnapshot.add(kid);
+ }
+ throw new UnknownKeyException();
+ }
+ return refreshed;
+ }
+ }
+
+ /** Permanently denies this kid for this cache instance, including during source outages. */
+ public void invalidateKid(String kid) {
+ if (kid == null || !KID.matcher(kid).matches()) {
+ throw new IllegalArgumentException("Account public JWKS key identifier is invalid");
+ }
+ synchronized (monitor) {
+ if (!hardDeniedKids.contains(kid) && hardDeniedKids.size() >= MAX_KEYS) {
+ throw new IllegalStateException("Account public JWKS hard-cutover bound is exhausted");
+ }
+ hardDeniedKids.add(kid);
+ Map remaining = new LinkedHashMap<>(keys);
+ remaining.remove(kid);
+ keys = Collections.unmodifiableMap(remaining);
+ }
+ }
+
+ /** Exposes only the non-secret source pin for integration correspondence checks. */
+ public SourceIdentity sourceIdentity() {
+ return expectedSource;
+ }
+
+ private boolean isFresh(Instant now) {
+ if (loadedAt == null || now.isBefore(loadedAt)) {
+ return false;
+ }
+ return Duration.between(loadedAt, now).compareTo(maximumAge) < 0;
+ }
+
+ private void refreshFromSource() {
+ final PublicJwksSnapshot snapshot;
+ try {
+ snapshot = source.load();
+ } catch (SourceUnavailableException unavailable) {
+ if (loadedAt == null || !isFresh(clock.instant())) {
+ throw new SourceUnavailableException();
+ }
+ return;
+ } catch (RuntimeException invalidSource) {
+ throw new InvalidJwksException();
+ }
+ if (snapshot == null || !expectedSource.equals(snapshot.sourceIdentity())) {
+ throw new InvalidJwksException();
+ }
+
+ byte[] snapshotBytes = snapshot.jwksBytes();
+ Map parsed = parseJwks(snapshotBytes);
+ Map nextFingerprints = new LinkedHashMap<>(rememberedFingerprints);
+ for (Map.Entry entry : parsed.entrySet()) {
+ String fingerprint = fingerprint(entry.getValue());
+ String prior = nextFingerprints.putIfAbsent(entry.getKey(), fingerprint);
+ if (prior != null && !prior.equals(fingerprint)) {
+ throw new InvalidJwksException();
+ }
+ if (nextFingerprints.size() > MAX_REMEMBERED_KIDS) {
+ throw new InvalidJwksException();
+ }
+ }
+ rememberedFingerprints.clear();
+ rememberedFingerprints.putAll(nextFingerprints);
+ keys = Collections.unmodifiableMap(parsed);
+ String nextJwksFingerprint = fingerprintBytes(snapshotBytes);
+ if (!Objects.equals(loadedJwksFingerprint, nextJwksFingerprint)) {
+ unknownKidsRefreshedForSnapshot.clear();
+ }
+ loadedJwksFingerprint = nextJwksFingerprint;
+ loadedAt = clock.instant();
+ lastStaleSourceUnavailableAt = null;
+ }
+
+ private void rejectHardDenied(String kid) {
+ if (hardDeniedKids.contains(kid)) {
+ throw new UnknownKeyException();
+ }
+ }
+
+ private static Map parseJwks(byte[] bytes) {
+ if (bytes == null || bytes.length == 0 || bytes.length > MAX_JWKS_BYTES) {
+ throw new InvalidJwksException();
+ }
+ try {
+ String text = strictUtf8(bytes);
+ Map root = JSON.readValue(text, OBJECT);
+ requireExactFields(root, Set.of("keys"));
+ if (!(root.get("keys") instanceof List> list) || list.isEmpty() || list.size() > MAX_KEYS) {
+ throw new InvalidJwksException();
+ }
+ Map parsed = new LinkedHashMap<>();
+ for (Object item : list) {
+ if (!(item instanceof Map, ?> raw)) {
+ throw new InvalidJwksException();
+ }
+ Map key = stringKeyedMap(raw);
+ Set allowed = Set.of("kty", "use", "alg", "kid", "n", "e", "key_ops");
+ if (!allowed.containsAll(key.keySet())
+ || !key.keySet().containsAll(Set.of("kty", "use", "alg", "kid", "n", "e"))) {
+ throw new InvalidJwksException();
+ }
+ if (!(key.get("kty") instanceof String kty)
+ || !"RSA".equals(kty)
+ || !(key.get("use") instanceof String use)
+ || !"sig".equals(use)
+ || !(key.get("alg") instanceof String alg)
+ || !"RS256".equals(alg)
+ || !(key.get("kid") instanceof String kid)
+ || !KID.matcher(kid).matches()) {
+ throw new InvalidJwksException();
+ }
+ if (key.containsKey("key_ops")
+ && (!(key.get("key_ops") instanceof List> ops) || !ops.equals(List.of("verify")))) {
+ throw new InvalidJwksException();
+ }
+ BigInteger modulus = decodeUnsigned(key.get("n"), 2048);
+ BigInteger exponent = decodeUnsigned(key.get("e"), 8);
+ if (modulus.bitLength() < 3072
+ || modulus.bitLength() > 16384
+ || !modulus.testBit(0)
+ || !BigInteger.valueOf(65537).equals(exponent)) {
+ throw new InvalidJwksException();
+ }
+ RSAPublicKey publicKey =
+ (RSAPublicKey)
+ KeyFactory.getInstance("RSA")
+ .generatePublic(new RSAPublicKeySpec(modulus, exponent));
+ if (parsed.putIfAbsent(kid, publicKey) != null) {
+ throw new InvalidJwksException();
+ }
+ }
+ return parsed;
+ } catch (InvalidJwksException ex) {
+ throw ex;
+ } catch (IOException | GeneralSecurityException | RuntimeException ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static BigInteger decodeUnsigned(Object encodedValue, int maximumBytes) {
+ if (!(encodedValue instanceof String encoded)
+ || encoded.isEmpty()
+ || encoded.indexOf('=') >= 0
+ || !encoded.matches("[A-Za-z0-9_-]+")) {
+ throw new InvalidJwksException();
+ }
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(encoded);
+ if (decoded.length == 0
+ || decoded.length > maximumBytes
+ || decoded[0] == 0
+ || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(encoded)) {
+ throw new InvalidJwksException();
+ }
+ return new BigInteger(1, decoded);
+ } catch (IllegalArgumentException ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static void requireExactFields(Map object, Set expected) {
+ if (object == null || !object.keySet().equals(expected)) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static Map stringKeyedMap(Map, ?> source) {
+ Map result = new LinkedHashMap<>();
+ for (Map.Entry, ?> entry : source.entrySet()) {
+ if (!(entry.getKey() instanceof String key)
+ || result.putIfAbsent(key, entry.getValue()) != null) {
+ throw new InvalidJwksException();
+ }
+ }
+ return result;
+ }
+
+ 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 new InvalidJwksException();
+ }
+ }
+
+ private static String fingerprint(RSAPublicKey key) {
+ try {
+ byte[] material =
+ (key.getModulus().toString(16) + ":" + key.getPublicExponent().toString(16))
+ .getBytes(StandardCharsets.US_ASCII);
+ return java.util.HexFormat.of()
+ .formatHex(MessageDigest.getInstance("SHA-256").digest(material));
+ } catch (Exception ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ private static String fingerprintBytes(byte[] bytes) {
+ try {
+ return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ } catch (Exception ex) {
+ throw new InvalidJwksException();
+ }
+ }
+
+ /** Exact protected API/cluster/resource identity expected from every source read. */
+ public record SourceIdentity(
+ String environmentId,
+ String clusterId,
+ String clusterIncarnationUid,
+ String namespace,
+ String namespaceUid,
+ String configMapUid,
+ String bindingRevision,
+ String apiServerOrigin,
+ String servingCaSha256) {
+ public SourceIdentity {
+ if (environmentId == null
+ || !NAMESPACE.matcher(environmentId).matches()
+ || clusterId == null
+ || !CLUSTER.matcher(clusterId).matches()
+ || clusterIncarnationUid == null
+ || !UID.matcher(clusterIncarnationUid).matches()
+ || namespace == null
+ || !NAMESPACE.matcher(namespace).matches()
+ || namespaceUid == null
+ || !UID.matcher(namespaceUid).matches()
+ || configMapUid == null
+ || !UID.matcher(configMapUid).matches()
+ || bindingRevision == null
+ || !CLUSTER.matcher(bindingRevision).matches()
+ || apiServerOrigin == null
+ || !validApiOrigin(apiServerOrigin)
+ || servingCaSha256 == null
+ || !SHA256.matcher(servingCaSha256).matches()) {
+ throw new IllegalArgumentException("Account public JWKS source identity is invalid");
+ }
+ }
+
+ private static boolean validApiOrigin(String value) {
+ try {
+ URI uri = URI.create(value);
+ return "https".equalsIgnoreCase(uri.getScheme())
+ && uri.getHost() != null
+ && uri.getPort() > 0
+ && uri.getRawUserInfo() == null
+ && uri.getRawQuery() == null
+ && uri.getRawFragment() == null
+ && (uri.getRawPath() == null
+ || uri.getRawPath().isEmpty()
+ || "/".equals(uri.getRawPath()));
+ } catch (IllegalArgumentException invalid) {
+ return false;
+ }
+ }
+ }
+
+ /** Owner-provided authenticated retrieval seam; implementations must verify their trust pins. */
+ @FunctionalInterface
+ public interface TrustedPublicJwksSource {
+ PublicJwksSnapshot load() throws SourceUnavailableException;
+ }
+
+ /** A single exact public ConfigMap data value plus its independently established source pin. */
+ public record PublicJwksSnapshot(SourceIdentity sourceIdentity, byte[] jwksBytes) {
+ public PublicJwksSnapshot {
+ Objects.requireNonNull(sourceIdentity, "source identity is required");
+ jwksBytes = jwksBytes == null ? null : jwksBytes.clone();
+ }
+
+ @Override
+ public byte[] jwksBytes() {
+ return jwksBytes == null ? null : jwksBytes.clone();
+ }
+ }
+
+ public static final class SourceUnavailableException extends RuntimeException {
+ public SourceUnavailableException() {
+ super("Account public JWKS source is unavailable");
+ }
+ }
+
+ public static final class InvalidJwksException extends RuntimeException {
+ public InvalidJwksException() {
+ super("Account public JWKS source data is invalid");
+ }
+ }
+
+ public static final class UnknownKeyException extends RuntimeException {
+ public UnknownKeyException() {
+ super("Account public JWKS key is unavailable");
+ }
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java
new file mode 100644
index 0000000000..ce155d5b85
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java
@@ -0,0 +1,104 @@
+package net.firedevops.firemud.common.security;
+
+import java.math.BigInteger;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Validates the canonical claim shape of the registry-backed control-ui JWT profile. Authority
+ * counters are unsigned decimal strings; epoch timestamps remain exact bounded JSON numbers.
+ */
+public final class ControlUiJwtProfileValidator {
+ public static final String PROFILE = "control-ui";
+ public static final String AUDIENCE = "control-ui";
+ public static final String TOKEN_TYPE = "control-ui";
+ public static final String ISSUER = "firemud-account-service";
+ public static final Set REQUIRED_CLAIMS;
+ public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles");
+
+ static {
+ Set required =
+ new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS);
+ required.add("scopedRoles");
+ REQUIRED_CLAIMS = Set.copyOf(required);
+ }
+
+ private ControlUiJwtProfileValidator() {}
+
+ /**
+ * Checks claim shape only; it does not validate a registry record or current Account authority.
+ *
+ * @param claims immutable verified claims
+ * @param maxControlUiTenantScopes explicit finite profile cap for every applicable tenant map
+ */
+ public static void validateClaims(
+ Map claims, int maxControlUiTenantScopes, long maximumAuthorityTupleBytes) {
+ if (maxControlUiTenantScopes <= 0 || maximumAuthorityTupleBytes <= 0L) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS);
+ AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE);
+
+ Map tuple =
+ AccountJwtProfileClaimSupport.requireAuthorityTuple(
+ claims.get("authorityTuple"), true, false, false, maximumAuthorityTupleBytes);
+ if (!(tuple.get("privateRealmGrantVersions") instanceof List> grants) || !grants.isEmpty()) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ Map tenantGenerations =
+ AccountJwtProfileClaimSupport.requireGenerationMap(tuple.get("tenantAuthorityGeneration"));
+ Map membershipGenerations =
+ AccountJwtProfileClaimSupport.requireGenerationMap(
+ tuple.get("membershipAuthorityGeneration"));
+ Map membershipVersions =
+ AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion"));
+ String accountId = (String) claims.get("accountId");
+ // The canonical profile forbids an accountId as a tenant-map key; this is shape rejection,
+ // not evidence about tenant ownership or an authorization predicate.
+ if (!membershipGenerations.keySet().equals(membershipVersions.keySet())
+ || tenantGenerations.containsKey(accountId)
+ || membershipGenerations.containsKey(accountId)
+ || membershipVersions.containsKey(accountId)) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+
+ Map scopedRoles =
+ AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles"));
+ scopedRoles.forEach(
+ (tenantId, roles) -> {
+ AccountJwtProfileClaimSupport.requireUuid(tenantId);
+ AccountJwtProfileClaimSupport.requireRoleList(roles);
+ if (((List>) roles).isEmpty() || tenantId.equals(claims.get("accountId"))) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ });
+ if (!scopedRoles.keySet().containsAll(tenantGenerations.keySet())) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+
+ requireAtMost(scopedRoles.size(), maxControlUiTenantScopes);
+ requireAtMost(tenantGenerations.size(), maxControlUiTenantScopes);
+ requireAtMost(membershipGenerations.size(), maxControlUiTenantScopes);
+ requireAtMost(membershipVersions.size(), maxControlUiTenantScopes);
+
+ Object billingCutoff = tuple.get("tenantBillingCutoff");
+ if (billingCutoff != null) {
+ Map billingCutoffs =
+ AccountJwtProfileClaimSupport.requireObjectMap(billingCutoff);
+ requireAtMost(billingCutoffs.size(), maxControlUiTenantScopes);
+ if (!scopedRoles.keySet().containsAll(billingCutoffs.keySet())) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ }
+ if (claims.containsKey("globalRoles")) {
+ AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles"));
+ }
+ }
+
+ private static void requireAtMost(int entries, int maximum) {
+ if (entries > maximum) {
+ throw AccountJwtProfileClaimSupport.invalid();
+ }
+ }
+}
diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifierTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifierTest.java
new file mode 100644
index 0000000000..cf814b3ce0
--- /dev/null
+++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountAsymmetricJwtVerifierTest.java
@@ -0,0 +1,566 @@
+package net.firedevops.firemud.common.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Signature;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class AccountAsymmetricJwtVerifierTest {
+ private static final Instant NOW = Instant.parse("2026-10-05T10:00:00Z");
+ private static final String KID = "signer-1";
+ private static final AccountPublicJwksCache.SourceIdentity PIN =
+ new AccountPublicJwksCache.SourceIdentity(
+ "prod",
+ "cluster-a",
+ "11111111-1111-4111-8111-111111111111",
+ "firemud-prod",
+ "22222222-2222-4222-8222-222222222222",
+ "33333333-3333-4333-8333-333333333333",
+ "binding-7",
+ "https://kubernetes.example:6443",
+ "a".repeat(64));
+ private static final Set CLAIMS =
+ Set.of(
+ "iss",
+ "sub",
+ "jti",
+ "accountId",
+ "aud",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence",
+ "scopedRoles");
+
+ private final MutableClock clock = new MutableClock(NOW);
+ private KeyPair keyPair;
+ private AccountAsymmetricJwtVerifier verifier;
+ private AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy policy;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ keyPair = rsa3072();
+ String jwks = jwks(jwk(KID, (RSAPublicKey) keyPair.getPublic()));
+ AccountPublicJwksCache cache =
+ new AccountPublicJwksCache(
+ () ->
+ new AccountPublicJwksCache.PublicJwksSnapshot(
+ PIN, jwks.getBytes(StandardCharsets.UTF_8)),
+ PIN,
+ clock,
+ Duration.ofSeconds(30));
+ verifier = new AccountAsymmetricJwtVerifier(cache, clock);
+ policy =
+ new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ "credential-authenticate-account",
+ ControlUiJwtProfileValidator.PROFILE,
+ ControlUiJwtProfileValidator.TOKEN_TYPE,
+ ControlUiJwtProfileValidator.ISSUER,
+ ControlUiJwtProfileValidator.AUDIENCE,
+ CLAIMS,
+ Set.of(),
+ 1800L,
+ 5,
+ 16 * 1024,
+ claims -> ControlUiJwtProfileValidator.validateClaims(claims, 8, 4096L));
+ }
+
+ @Test
+ void verifiesRealRs256SignatureAndReturnsOnlyImmutableRouteBoundClaims() throws Exception {
+ String token =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair);
+
+ AccountAsymmetricJwtVerifier.VerifiedClaims verified = verifier.verify(token, policy);
+
+ assertThat(verified.routeId()).isEqualTo("credential-authenticate-account");
+ assertThat(verified.profile()).isEqualTo(ControlUiJwtProfileValidator.PROFILE);
+ assertThat(verified.tokenType()).isEqualTo(ControlUiJwtProfileValidator.TOKEN_TYPE);
+ assertThat(verified.keyId()).isEqualTo(KID);
+ assertThat(verified.claims().get("iss")).isEqualTo(ControlUiJwtProfileValidator.ISSUER);
+ assertThat(verified.claims()).doesNotContainKeys("tokenType", "tokenProfile");
+ assertThat(verified.getClass().getDeclaredFields())
+ .extracting(java.lang.reflect.Field::getName)
+ .containsExactlyInAnyOrder("routeId", "profile", "tokenType", "keyId", "claims");
+ assertThatThrownBy(() -> verified.claims().put("extra", "value"))
+ .isInstanceOf(UnsupportedOperationException.class);
+ @SuppressWarnings("unchecked")
+ Map tuple = (Map) verified.claims().get("authorityTuple");
+ assertThat(tuple.get("issuerAuthGeneration")).isEqualTo("1");
+ assertThat(tuple.get("accountAuthorityGeneration")).isEqualTo("1");
+ assertThat(tuple.get("tenantAuthorityGeneration")).isEqualTo(Map.of());
+ assertThat(tuple.get("membershipAuthorityGeneration")).isEqualTo(Map.of());
+ assertThat(tuple.get("privateRealmGrantVersions")).isEqualTo(java.util.List.of());
+ assertThat(verified.claims().get("tokenGeneration")).isEqualTo("1");
+ assertThat(verified.claims().get("issuanceFence")).isEqualTo("1");
+ for (String field : java.util.List.of("iat", "nbf", "exp")) {
+ assertThat(verified.claims().get(field)).isInstanceOf(Number.class);
+ }
+ assertThatThrownBy(() -> tuple.put("tenant", "x"))
+ .isInstanceOf(UnsupportedOperationException.class);
+ }
+
+ @Test
+ void exactOversizedCountersSurviveSignatureVerificationAndFractionalCountersDeny()
+ throws Exception {
+ java.math.BigInteger value = java.math.BigInteger.TEN.pow(100).add(java.math.BigInteger.ONE);
+ Map claims =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120L);
+ claims.put("tokenGeneration", value.toString());
+ claims.put("issuanceFence", value.add(java.math.BigInteger.ONE).toString());
+ String compact = token(claims, "RS256", KID, "JWT", keyPair);
+ var verified = verifier.verify(compact, policy);
+ assertThat(verified.claims().get("tokenGeneration")).isEqualTo(value.toString());
+ assertThat(verified.claims().get("issuanceFence"))
+ .isEqualTo(value.add(java.math.BigInteger.ONE).toString());
+ claims.put("tokenGeneration", new java.math.BigDecimal("1.000000000000000000001"));
+ assertDenied(token(claims, "RS256", KID, "JWT", keyPair));
+ claims.put("tokenGeneration", 0L);
+ assertDenied(token(claims, "RS256", KID, "JWT", keyPair));
+ claims.put("tokenGeneration", -1L);
+ assertDenied(token(claims, "RS256", KID, "JWT", keyPair));
+ claims.put("tokenGeneration", 1L);
+ assertDenied(token(claims, "RS256", KID, "JWT", keyPair));
+ }
+
+ @Test
+ void verifierChecksCanonicalLineageAndFenceBeforeTheProfileCallback() throws Exception {
+ AtomicInteger profileCalls = new AtomicInteger();
+ // Isolate the verifier-owned wire checks: a profile validator must not mask a missed reader.
+ var counterPolicy =
+ new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ policy.routeId(),
+ policy.profile(),
+ policy.tokenType(),
+ policy.issuer(),
+ policy.audience(),
+ policy.requiredClaims(),
+ policy.optionalClaims(),
+ policy.maximumLifetimeSeconds(),
+ policy.allowedClockSkewSeconds(),
+ policy.maxCompactTokenBytes(),
+ claims -> profileCalls.incrementAndGet());
+ for (String value :
+ java.util.List.of(
+ "1",
+ "9007199254740992",
+ "9007199254740993",
+ "9223372036854775808",
+ "9223372036854775809")) {
+ Map claims =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120L);
+ claims.put("tokenGeneration", value);
+ claims.put("issuanceFence", value);
+ var verified = verifier.verify(token(claims, "RS256", KID, "JWT", keyPair), counterPolicy);
+ assertThat(verified.claims().get("tokenGeneration")).isEqualTo(value);
+ assertThat(verified.claims().get("issuanceFence")).isEqualTo(value);
+ for (String field : java.util.List.of("iat", "nbf", "exp")) {
+ assertThat(verified.claims().get(field)).isInstanceOf(Number.class);
+ }
+ }
+ assertThat(profileCalls).hasValue(5);
+ for (String field : java.util.List.of("tokenGeneration", "issuanceFence")) {
+ for (Object invalid :
+ java.util.List.of(
+ 1L,
+ 1.0d,
+ new java.math.BigDecimal("1.5"),
+ "0",
+ "-1",
+ "+1",
+ "01",
+ " 1",
+ "1 ",
+ "1.0",
+ "1e3",
+ "",
+ "bad")) {
+ Map claims =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120L);
+ claims.put(field, invalid);
+ String signed = token(claims, "RS256", KID, "JWT", keyPair);
+ assertThatThrownBy(() -> verifier.verify(signed, counterPolicy))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class)
+ .hasNoCause();
+ }
+ }
+ assertThat(profileCalls).hasValue(5);
+ }
+
+ @Test
+ void wrongIssuerAudienceHeaderTypeAlgorithmAndTimeAreDenied() throws Exception {
+ Map wrongIssuer =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ wrongIssuer.put("iss", "other-issuer");
+ assertDenied(token(wrongIssuer, "RS256", KID, "JWT", keyPair));
+
+ Map wrongAudience =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ wrongAudience.put("aud", "other-audience");
+ assertDenied(token(wrongAudience, "RS256", KID, "JWT", keyPair));
+
+ assertDenied(
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "HS256",
+ KID,
+ "JWT",
+ keyPair));
+ assertDenied(
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "private_player_delegation",
+ keyPair));
+ assertDenied(
+ token(
+ validClaims(
+ NOW.getEpochSecond() - 400, NOW.getEpochSecond() - 400, NOW.getEpochSecond() - 1),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair));
+ assertDenied(
+ token(
+ validClaims(
+ NOW.getEpochSecond() + 20, NOW.getEpochSecond() + 20, NOW.getEpochSecond() + 100),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair));
+ }
+
+ @Test
+ void rejectsDuplicateTrailingExtraClaimsAndMismatchedSignatureKey() throws Exception {
+ String validPayload =
+ claimsJson(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120));
+ assertDenied(
+ rawToken(
+ "{\"alg\":\"RS256\",\"kid\":\"" + KID + "\",\"typ\":\"JWT\"}",
+ validPayload.replaceFirst("\\{", "{\"iss\":\"duplicate\","),
+ keyPair));
+ assertDenied(
+ rawToken(
+ "{\"alg\":\"RS256\",\"kid\":\"" + KID + "\",\"typ\":\"JWT\"}",
+ validPayload + " {}",
+ keyPair));
+ Map extra =
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120);
+ extra.put("unrecognized", true);
+ assertDenied(token(extra, "RS256", KID, "JWT", keyPair));
+
+ KeyPair other = rsa3072();
+ assertDenied(
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ other));
+ }
+
+ @Test
+ void cacheUnavailableAfterMaximumAgeDoesNotPermitStaleSignatureUse() throws Exception {
+ String jwks = jwks(jwk(KID, (RSAPublicKey) keyPair.getPublic()));
+ boolean[] unavailable = {false};
+ AccountPublicJwksCache cache =
+ new AccountPublicJwksCache(
+ () -> {
+ if (unavailable[0]) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return new AccountPublicJwksCache.PublicJwksSnapshot(
+ PIN, jwks.getBytes(StandardCharsets.UTF_8));
+ },
+ PIN,
+ clock,
+ Duration.ofSeconds(5));
+ AccountAsymmetricJwtVerifier staleVerifier = new AccountAsymmetricJwtVerifier(cache, clock);
+ String valid =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair);
+ assertThat(staleVerifier.verify(valid, policy).claims().get("jti"))
+ .isEqualTo("22222222-2222-4222-8222-222222222222");
+ unavailable[0] = true;
+ clock.advance(Duration.ofSeconds(6));
+ assertThatThrownBy(() -> staleVerifier.verify(valid, policy))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationUnavailableException.class)
+ .hasNoCause();
+ assertThatThrownBy(() -> staleVerifier.verify(valid, policy))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationUnavailableException.class)
+ .hasNoCause();
+ }
+
+ @Test
+ void unknownKidForcesOneSnapshotRefreshAndThenVerifiesAgainstTheNewPublicKey() throws Exception {
+ KeyPair rotated = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference currentJwks =
+ new AtomicReference<>(jwks(jwk(KID, (RSAPublicKey) keyPair.getPublic())));
+ AccountPublicJwksCache cache =
+ new AccountPublicJwksCache(
+ () -> {
+ loads.incrementAndGet();
+ return new AccountPublicJwksCache.PublicJwksSnapshot(
+ PIN, currentJwks.get().getBytes(StandardCharsets.UTF_8));
+ },
+ PIN,
+ clock,
+ Duration.ofSeconds(30));
+ AccountAsymmetricJwtVerifier rotationVerifier = new AccountAsymmetricJwtVerifier(cache, clock);
+ String oldToken =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair);
+ rotationVerifier.verify(oldToken, policy);
+ currentJwks.set(
+ jwks(
+ jwk(KID, (RSAPublicKey) keyPair.getPublic())
+ + ","
+ + jwk("signer-2", (RSAPublicKey) rotated.getPublic())));
+
+ String rotatedToken =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ "signer-2",
+ "JWT",
+ rotated);
+ assertThat(rotationVerifier.verify(rotatedToken, policy).claims().get("iss"))
+ .isEqualTo(ControlUiJwtProfileValidator.ISSUER);
+ assertThat(rotationVerifier.verify(rotatedToken, policy).claims().get("iss"))
+ .isEqualTo(ControlUiJwtProfileValidator.ISSUER);
+ assertThat(loads).hasValue(2);
+ }
+
+ @Test
+ void claimShapeValidationRunsOnlyAfterSuccessfulSignatureVerification() throws Exception {
+ AtomicInteger shapeValidations = new AtomicInteger();
+ AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy observingPolicy =
+ new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ "credential-authenticate-account",
+ ControlUiJwtProfileValidator.PROFILE,
+ ControlUiJwtProfileValidator.TOKEN_TYPE,
+ ControlUiJwtProfileValidator.ISSUER,
+ ControlUiJwtProfileValidator.AUDIENCE,
+ CLAIMS,
+ Set.of(),
+ 1800L,
+ 5,
+ 16 * 1024,
+ claims -> {
+ shapeValidations.incrementAndGet();
+ ControlUiJwtProfileValidator.validateClaims(claims, 8, 4096L);
+ });
+ String valid =
+ token(
+ validClaims(NOW.getEpochSecond(), NOW.getEpochSecond(), NOW.getEpochSecond() + 120),
+ "RS256",
+ KID,
+ "JWT",
+ keyPair);
+
+ verifier.verify(valid, observingPolicy);
+ assertThat(shapeValidations).hasValue(1);
+
+ String invalidSignature = corruptSignature(valid);
+ assertThatThrownBy(() -> verifier.verify(invalidSignature, observingPolicy))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class)
+ .hasNoCause();
+ assertThat(shapeValidations).hasValue(1);
+ }
+
+ private void assertDenied(String token) {
+ assertDenied(verifier, token);
+ }
+
+ private static void assertDenied(AccountAsymmetricJwtVerifier verifier, String token) {
+ assertThatThrownBy(() -> verifier.verify(token, policyForTest()))
+ .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class)
+ .hasMessage("Account JWT verification failed")
+ .hasNoCause();
+ }
+
+ private static AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy policyForTest() {
+ return new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ "credential-authenticate-account",
+ ControlUiJwtProfileValidator.PROFILE,
+ ControlUiJwtProfileValidator.TOKEN_TYPE,
+ ControlUiJwtProfileValidator.ISSUER,
+ ControlUiJwtProfileValidator.AUDIENCE,
+ CLAIMS,
+ Set.of(),
+ 300,
+ 5,
+ 16 * 1024,
+ claims -> ControlUiJwtProfileValidator.validateClaims(claims, 8, 4096L));
+ }
+
+ private static Map validClaims(long issuedAt, long notBefore, long expiresAt) {
+ Map claims = new LinkedHashMap<>();
+ claims.put("iss", ControlUiJwtProfileValidator.ISSUER);
+ claims.put("sub", "11111111-1111-4111-8111-111111111111");
+ claims.put("jti", "22222222-2222-4222-8222-222222222222");
+ claims.put("accountId", "11111111-1111-4111-8111-111111111111");
+ claims.put("aud", ControlUiJwtProfileValidator.AUDIENCE);
+ claims.put("iat", issuedAt);
+ claims.put("nbf", notBefore);
+ claims.put("exp", expiresAt);
+ claims.put("tokenGeneration", "1");
+ claims.put(
+ "authorityTuple",
+ Map.of(
+ "issuerAuthGeneration", "1",
+ "accountAuthorityGeneration", "1",
+ "tenantAuthorityGeneration", Map.of(),
+ "membershipAuthorityGeneration", Map.of(),
+ "privateRealmGrantVersions", java.util.List.of()));
+ claims.put("membershipVersion", Map.of());
+ claims.put("issuanceFence", "1");
+ claims.put("scopedRoles", Map.of());
+ return claims;
+ }
+
+ private static String token(
+ Map claims, String algorithm, String kid, String typ, KeyPair signer)
+ throws Exception {
+ String header =
+ "{\"alg\":\"" + algorithm + "\",\"kid\":\"" + kid + "\",\"typ\":\"" + typ + "\"}";
+ return rawToken(header, claimsJson(claims), signer);
+ }
+
+ private static String rawToken(String header, String payload, KeyPair signer) throws Exception {
+ Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
+ String headerSegment = encoder.encodeToString(header.getBytes(StandardCharsets.UTF_8));
+ String payloadSegment = encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8));
+ byte[] signingInput =
+ (headerSegment + "." + payloadSegment).getBytes(StandardCharsets.US_ASCII);
+ Signature signature = Signature.getInstance("SHA256withRSA");
+ signature.initSign(signer.getPrivate());
+ signature.update(signingInput);
+ return headerSegment + "." + payloadSegment + "." + encoder.encodeToString(signature.sign());
+ }
+
+ private static String corruptSignature(String token) {
+ int separator = token.lastIndexOf('.');
+ char replacement = token.charAt(separator + 1) == 'A' ? 'B' : 'A';
+ return token.substring(0, separator + 1) + replacement + token.substring(separator + 2);
+ }
+
+ private static String claimsJson(Map claims) {
+ // Build the canonical profile's bounded nested object explicitly so test tokens exercise the
+ // same normal JSON shapes without relying on an unrelated mapper configuration.
+ StringBuilder json = new StringBuilder("{");
+ boolean first = true;
+ for (Map.Entry entry : claims.entrySet()) {
+ if (!first) {
+ json.append(',');
+ }
+ first = false;
+ json.append('"').append(entry.getKey()).append("\":");
+ Object value = entry.getValue();
+ if (value instanceof String text) {
+ json.append('"').append(text).append('"');
+ } else if (value instanceof Number || value instanceof Boolean) {
+ json.append(value);
+ } else if (("membershipVersion".equals(entry.getKey())
+ || "scopedRoles".equals(entry.getKey()))) {
+ json.append("{}");
+ } else if ("authorityTuple".equals(entry.getKey())) {
+ json.append(
+ "{\"issuerAuthGeneration\":\"1\",\"accountAuthorityGeneration\":\"1\",\"tenantAuthorityGeneration\":{},\"membershipAuthorityGeneration\":{},\"privateRealmGrantVersions\":[]}");
+ } else {
+ throw new IllegalArgumentException("Unexpected test claim");
+ }
+ }
+ json.append('}');
+ return json.toString();
+ }
+
+ private static String jwks(String key) {
+ return "{\"keys\":[" + key + "]}";
+ }
+
+ private static String jwk(String kid, RSAPublicKey key) {
+ byte[] modulus = unsigned(key.getModulus().toByteArray());
+ byte[] exponent = unsigned(key.getPublicExponent().toByteArray());
+ return "{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\""
+ + kid
+ + "\",\"n\":\""
+ + Base64.getUrlEncoder().withoutPadding().encodeToString(modulus)
+ + "\",\"e\":\""
+ + Base64.getUrlEncoder().withoutPadding().encodeToString(exponent)
+ + "\"}";
+ }
+
+ private static byte[] unsigned(byte[] value) {
+ return value.length > 1 && value[0] == 0
+ ? java.util.Arrays.copyOfRange(value, 1, value.length)
+ : value;
+ }
+
+ private static KeyPair rsa3072() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(3072);
+ return generator.generateKeyPair();
+ }
+
+ private static final class MutableClock extends Clock {
+ private Instant current;
+
+ private MutableClock(Instant current) {
+ this.current = current;
+ }
+
+ void advance(Duration duration) {
+ current = current.plus(duration);
+ }
+
+ @Override
+ public ZoneId getZone() {
+ return ZoneId.of("UTC");
+ }
+
+ @Override
+ public Clock withZone(ZoneId zone) {
+ return this;
+ }
+
+ @Override
+ public Instant instant() {
+ return current;
+ }
+ }
+}
diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountJwtExactValuesTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountJwtExactValuesTest.java
new file mode 100644
index 0000000000..fcebbdbbc9
--- /dev/null
+++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountJwtExactValuesTest.java
@@ -0,0 +1,121 @@
+package net.firedevops.firemud.common.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.Test;
+
+class AccountJwtExactValuesTest {
+ @Test
+ void adjacentLargeCountersDifferThroughoutNestedMapsAndLists() {
+ BigInteger first = new BigInteger("9007199254740992");
+ BigInteger next = first.add(BigInteger.ONE);
+ Map left = Map.of("membershipVersion", Map.of("tenant", List.of(first)));
+ Map right = Map.of("membershipVersion", Map.of("tenant", List.of(next)));
+ assertThat(AccountJwtExactValues.sameJsonValue(left, right)).isFalse();
+ assertThat(
+ AccountJwtExactValues.sameJsonValue(
+ left,
+ Map.of("membershipVersion", Map.of("tenant", List.of(first.longValueExact())))))
+ .isTrue();
+ assertThat(
+ AccountJwtExactValues.sameJsonValue(
+ Map.of("identity", "1"), Map.of("identity", BigInteger.ONE)))
+ .isFalse();
+ assertThat(
+ AccountJwtExactValues.sameJsonValue(
+ List.of("account", "tenant"), List.of("tenant", "account")))
+ .isFalse();
+ assertThat(
+ AccountJwtExactValues.sameJsonValue(Map.of("account", first), Map.of("tenant", first)))
+ .isFalse();
+ }
+
+ @Test
+ void oversizedPositiveCountersAndVersionMapsRetainTheirExactValues() {
+ BigInteger value = BigInteger.TEN.pow(100).add(BigInteger.ONE);
+ assertThat(AccountJwtExactValues.positiveCounter(value)).isEqualTo(value);
+ assertThat(AccountJwtExactValues.positiveDecimalCounter(value.toString())).isEqualTo(value);
+ assertThat(
+ AccountJwtProfileClaimSupport.requireGenerationMap(
+ Map.of("11111111-1111-4111-8111-111111111111", value.toString()))
+ .values())
+ .containsExactly(value);
+ assertThat(
+ AccountJwtProfileClaimSupport.requireVersionMap(
+ Map.of("11111111-1111-4111-8111-111111111111", value.toString()))
+ .values())
+ .containsExactly(value);
+ }
+
+ @Test
+ void zeroNegativeFractionalAndMalformedCountersAreRejectedWithoutStringAliases() {
+ for (Object value :
+ List.of(
+ BigInteger.ZERO,
+ BigInteger.valueOf(-1L),
+ new BigDecimal("1.000000000000000000001"),
+ "1",
+ "bad",
+ 1.0d)) {
+ assertThatThrownBy(() -> AccountJwtExactValues.positiveCounter(value))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ for (Object value : List.of("0", "-1", "+1", "01", "1.0", "1e3", " 1", "1 ", "", "bad", 1L)) {
+ assertThatThrownBy(() -> AccountJwtExactValues.positiveDecimalCounter(value))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
+ @Test
+ void membershipVersionsPermitOnlyCanonicalZeroOrPositiveDecimalStrings() {
+ assertThat(AccountJwtExactValues.nonNegativeDecimalCounter("0")).isZero();
+ assertThat(
+ AccountJwtProfileClaimSupport.requireVersionMap(
+ Map.of("11111111-1111-4111-8111-111111111111", "0"))
+ .values())
+ .containsExactly(BigInteger.ZERO);
+ for (Object value : List.of("-0", "+0", "00", "-1", "01", "0.0", "0e0", " 0", "0 ", "", 0L)) {
+ assertThatThrownBy(() -> AccountJwtExactValues.nonNegativeDecimalCounter(value))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
+ @Test
+ void decimalStringGoldenVectorsSurviveCanonicalizationExactlyWithoutNumericAliases() {
+ for (String value :
+ List.of(
+ "9007199254740992", "9007199254740993", "9223372036854775808", "9223372036854775809")) {
+ assertThat(AccountJwtExactValues.positiveDecimalCounter(value))
+ .isEqualTo(new BigInteger(value));
+ assertThat(
+ new String(
+ AccountJwtExactValues.losslessCanonicalBytes(Map.of("tokenGeneration", value)),
+ StandardCharsets.UTF_8))
+ .isEqualTo("{\"tokenGeneration\":\"" + value + "\"}");
+ }
+ assertThat(
+ AccountJwtExactValues.sameJsonValue(
+ Map.of("membershipVersion", Map.of("tenant", "9007199254740992")),
+ Map.of("membershipVersion", Map.of("tenant", "9007199254740993"))))
+ .isFalse();
+ assertThat(AccountJwtExactValues.sameJsonValue("1", BigInteger.ONE)).isFalse();
+ }
+
+ @Test
+ void canonicalizationCannotRoundANumericCandidateAndAnExactLargeValueRemainsNumeric() {
+ assertThatThrownBy(
+ () ->
+ AccountJwtExactValues.losslessCanonicalBytes(
+ Map.of("counter", new BigInteger("9007199254740993"))))
+ .isInstanceOf(IllegalArgumentException.class);
+ byte[] bytes =
+ AccountJwtExactValues.losslessCanonicalBytes(Map.of("counter", BigInteger.TEN.pow(30)));
+ assertThat(new String(bytes, StandardCharsets.UTF_8)).isEqualTo("{\"counter\":1e+30}");
+ }
+}
diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java
new file mode 100644
index 0000000000..09fe25e73a
--- /dev/null
+++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java
@@ -0,0 +1,287 @@
+package net.firedevops.firemud.common.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.util.Base64;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.Test;
+
+class AccountPublicJwksCacheTest {
+ private static final Instant INITIAL = Instant.parse("2026-10-05T10:00:00Z");
+ private static final AccountPublicJwksCache.SourceIdentity PIN =
+ new AccountPublicJwksCache.SourceIdentity(
+ "prod",
+ "cluster-a",
+ "11111111-1111-4111-8111-111111111111",
+ "firemud-prod",
+ "22222222-2222-4222-8222-222222222222",
+ "33333333-3333-4333-8333-333333333333",
+ "binding-7",
+ "https://kubernetes.example:6443",
+ "a".repeat(64));
+
+ @Test
+ void parsesStrongPublicOnlyKeysAndRetainsBothKeysPresentInOneSnapshot() throws Exception {
+ KeyPair oldKey = rsa3072();
+ KeyPair newKey = rsa3072();
+ String jwks =
+ jwks(
+ jwk("old", (RSAPublicKey) oldKey.getPublic())
+ + ","
+ + jwk("new", (RSAPublicKey) newKey.getPublic()));
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache = cache(clock, () -> snapshot(jwks));
+
+ assertThat(cache.keyFor("old")).isEqualTo(oldKey.getPublic());
+ assertThat(cache.keyFor("new")).isEqualTo(newKey.getPublic());
+ assertThat(cache.sourceIdentity()).isEqualTo(PIN);
+ }
+
+ @Test
+ void unknownKidGetsOneForcedLoadThenCooldownPreventsRefreshStorm() throws Exception {
+ KeyPair key = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ return snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic())));
+ });
+
+ assertThatThrownBy(() -> cache.keyFor("unknown"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThatThrownBy(() -> cache.keyFor("unknown"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(loads).hasValue(1);
+
+ clock.advance(Duration.ofSeconds(1));
+ assertThatThrownBy(() -> cache.keyFor("unknown-two"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ assertThat(loads).hasValue(2);
+ }
+
+ @Test
+ void previousUnknownKidIsRetriedAfterCacheAgeAndCanResolveALaterPublishedKey() throws Exception {
+ KeyPair known = rsa3072();
+ KeyPair later = rsa3072();
+ AtomicInteger loads = new AtomicInteger();
+ AtomicReference currentJwks =
+ new AtomicReference<>(jwks(jwk("known", (RSAPublicKey) known.getPublic())));
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ loads.incrementAndGet();
+ return snapshot(currentJwks.get());
+ });
+ assertThat(cache.keyFor("known")).isEqualTo(known.getPublic());
+ assertThatThrownBy(() -> cache.keyFor("future"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+
+ currentJwks.set(
+ jwks(
+ jwk("known", (RSAPublicKey) known.getPublic())
+ + ","
+ + jwk("future", (RSAPublicKey) later.getPublic())));
+ clock.advance(Duration.ofSeconds(11));
+
+ assertThat(cache.keyFor("future")).isEqualTo(later.getPublic());
+ assertThat(loads).hasValue(3);
+ }
+
+ @Test
+ void knownKeyUsesOnlyStillFreshCacheDuringUnavailableSourceAndNeverExtendsAge() throws Exception {
+ KeyPair key = rsa3072();
+ AtomicReference unavailable = new AtomicReference<>(false);
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ if (unavailable.get()) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic())));
+ });
+
+ assertThat(cache.keyFor("known")).isEqualTo(key.getPublic());
+ unavailable.set(true);
+ clock.advance(Duration.ofSeconds(4));
+ assertThat(cache.keyFor("known")).isEqualTo(key.getPublic());
+ clock.advance(Duration.ofSeconds(7));
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ assertThatThrownBy(() -> cache.keyFor("known"))
+ .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class);
+ }
+
+ @Test
+ void changedSourceIdentityAndReusedKidMaterialAreRejected() throws Exception {
+ KeyPair first = rsa3072();
+ KeyPair replacement = rsa3072();
+ AtomicReference next =
+ new AtomicReference<>(snapshot(jwks(jwk("same", (RSAPublicKey) first.getPublic()))));
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache = cache(clock, next::get);
+ assertThat(cache.keyFor("same")).isEqualTo(first.getPublic());
+
+ next.set(snapshot(jwks(jwk("same", (RSAPublicKey) replacement.getPublic()))));
+ clock.advance(Duration.ofSeconds(11));
+ assertThatThrownBy(() -> cache.keyFor("same"))
+ .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class);
+
+ byte[] wrongSourceBytes =
+ jwks(jwk("x", (RSAPublicKey) first.getPublic()))
+ .getBytes(java.nio.charset.StandardCharsets.UTF_8);
+ AccountPublicJwksCache wrongSource =
+ cache(
+ clock,
+ () -> new AccountPublicJwksCache.PublicJwksSnapshot(otherPin(), wrongSourceBytes));
+ assertThatThrownBy(() -> wrongSource.keyFor("x"))
+ .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class);
+ }
+
+ @Test
+ void hardCutoverDenialOverridesFreshCacheAndUnavailableSource() throws Exception {
+ KeyPair key = rsa3072();
+ AtomicReference unavailable = new AtomicReference<>(false);
+ MutableClock clock = new MutableClock(INITIAL);
+ AccountPublicJwksCache cache =
+ cache(
+ clock,
+ () -> {
+ if (unavailable.get()) {
+ throw new AccountPublicJwksCache.SourceUnavailableException();
+ }
+ return snapshot(jwks(jwk("cut", (RSAPublicKey) key.getPublic())));
+ });
+ assertThat(cache.keyFor("cut")).isEqualTo(key.getPublic());
+ cache.invalidateKid("cut");
+ unavailable.set(true);
+
+ assertThatThrownBy(() -> cache.keyFor("cut"))
+ .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class);
+ }
+
+ @Test
+ void rejectsPrivateWeakDuplicateTrailingAndNonCanonicalJwks() throws Exception {
+ KeyPair strong = rsa3072();
+ String publicKey = jwk("valid", (RSAPublicKey) strong.getPublic());
+ MutableClock clock = new MutableClock(INITIAL);
+ for (String invalid :
+ new String[] {
+ jwks(publicKey.substring(0, publicKey.length() - 1) + ",\"d\":\"private\"}"),
+ jwks(jwk("weak", (RSAPublicKey) rsa2048().getPublic())),
+ "{\"keys\":[" + publicKey + "," + publicKey + "]}",
+ jwks(publicKey) + " {}",
+ jwks(publicKey.replace("\"key_ops\":[\"verify\"]", "\"key_ops\":[\"sign\"]"))
+ }) {
+ AccountPublicJwksCache cache = cache(clock, () -> snapshot(invalid));
+ assertThatThrownBy(() -> cache.keyFor("valid"))
+ .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class);
+ }
+ }
+
+ private static AccountPublicJwksCache cache(
+ MutableClock clock, AccountPublicJwksCache.TrustedPublicJwksSource source) {
+ return new AccountPublicJwksCache(source, PIN, clock, Duration.ofSeconds(10));
+ }
+
+ private static AccountPublicJwksCache.PublicJwksSnapshot snapshot(String json) {
+ return new AccountPublicJwksCache.PublicJwksSnapshot(
+ PIN, json.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ }
+
+ private static AccountPublicJwksCache.SourceIdentity otherPin() {
+ return new AccountPublicJwksCache.SourceIdentity(
+ "prod",
+ "cluster-b",
+ "11111111-1111-4111-8111-111111111111",
+ "firemud-prod",
+ "22222222-2222-4222-8222-222222222222",
+ "33333333-3333-4333-8333-333333333333",
+ "binding-7",
+ "https://kubernetes.example:6443",
+ "a".repeat(64));
+ }
+
+ private static KeyPair rsa3072() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(3072);
+ return generator.generateKeyPair();
+ }
+
+ private static KeyPair rsa2048() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ return generator.generateKeyPair();
+ }
+
+ private static String jwks(String keys) {
+ return "{\"keys\":[" + keys + "]}";
+ }
+
+ private static String jwk(String kid, RSAPublicKey key) {
+ String modulus =
+ Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(unsigned(key.getModulus().toByteArray()));
+ String exponent =
+ Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(unsigned(key.getPublicExponent().toByteArray()));
+ return "{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\""
+ + kid
+ + "\",\"n\":\""
+ + modulus
+ + "\",\"e\":\""
+ + exponent
+ + "\",\"key_ops\":[\"verify\"]}";
+ }
+
+ private static byte[] unsigned(byte[] value) {
+ if (value.length > 1 && value[0] == 0) {
+ return java.util.Arrays.copyOfRange(value, 1, value.length);
+ }
+ return value;
+ }
+
+ private static final class MutableClock extends Clock {
+ private Instant current;
+
+ private MutableClock(Instant current) {
+ this.current = current;
+ }
+
+ void advance(Duration duration) {
+ current = current.plus(duration);
+ }
+
+ @Override
+ public ZoneId getZone() {
+ return ZoneId.of("UTC");
+ }
+
+ @Override
+ public Clock withZone(ZoneId zone) {
+ return this;
+ }
+
+ @Override
+ public Instant instant() {
+ return current;
+ }
+ }
+}
diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java
new file mode 100644
index 0000000000..f9590125c6
--- /dev/null
+++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java
@@ -0,0 +1,357 @@
+package net.firedevops.firemud.common.security;
+
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import org.junit.jupiter.api.Test;
+
+class ControlUiJwtProfileValidatorTest {
+ private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111";
+ private static final String TENANT_A = "22222222-2222-4222-8222-222222222222";
+ private static final String TENANT_B = "33333333-3333-4333-8333-333333333333";
+
+ @Test
+ void oversizedExactAuthorityCountersKeepIndependentMapValuesWithoutLongParsing() {
+ java.math.BigInteger tenantCounter = java.math.BigInteger.TEN.pow(30);
+ java.math.BigInteger membershipCounter = java.math.BigInteger.TEN.pow(31);
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put("issuerAuthGeneration", java.math.BigInteger.TEN.pow(32).toString());
+ tuple.put("tenantAuthorityGeneration", Map.of(TENANT_A, tenantCounter.toString()));
+ tuple.put("membershipAuthorityGeneration", Map.of(TENANT_B, membershipCounter.toString()));
+ claims.put("authorityTuple", tuple);
+ claims.put("membershipVersion", Map.of(TENANT_B, java.math.BigInteger.TEN.pow(33).toString()));
+ assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1, 4096L))
+ .doesNotThrowAnyException();
+ }
+
+ @Test
+ void acceptsSeparateTargetAndMembershipApplicabilityAndOptionalGlobalRoles() {
+ Map claims = baseClaims();
+ claims.put(
+ "authorityTuple", authorityTuple(Map.of(TENANT_A, "2"), Map.of(TENANT_B, "3"), List.of()));
+ claims.put("membershipVersion", Map.of(TENANT_B, "8"));
+ claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin")));
+
+ assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1, 4096L))
+ .doesNotThrowAnyException();
+ claims.put("globalRoles", List.of());
+ assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1, 4096L))
+ .doesNotThrowAnyException();
+ }
+
+ @Test
+ void membershipVersionZeroIsStructurallyValidButGenerationZeroIsNot() {
+ Map claims = validClaims();
+ claims.put("membershipVersion", Map.of(TENANT_B, "0"));
+ assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1, 4096L))
+ .doesNotThrowAnyException();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put("membershipAuthorityGeneration", Map.of(TENANT_B, "0"));
+ claims.put("authorityTuple", tuple);
+ assertInvalid(claims);
+ }
+
+ @Test
+ void everyAuthorityCounterRejectsNumericAndNoncanonicalRepresentations() {
+ for (Object invalid : List.of(1L, "0", "-1", "+1", "01", " 1", "1 ", "1.0", "1e3", "", "bad")) {
+ for (String field : List.of("tokenGeneration", "issuanceFence")) {
+ Map claims = validClaims();
+ claims.put(field, invalid);
+ assertInvalid(claims);
+ }
+ for (String field : List.of("issuerAuthGeneration", "accountAuthorityGeneration")) {
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put(field, invalid);
+ claims.put("authorityTuple", tuple);
+ assertInvalid(claims);
+ }
+ for (String field : List.of("tenantAuthorityGeneration", "membershipAuthorityGeneration")) {
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put(field, Map.of(field.startsWith("tenant") ? TENANT_A : TENANT_B, invalid));
+ claims.put("authorityTuple", tuple);
+ assertInvalid(claims);
+ }
+ }
+ for (Object invalid : List.of(0L, "-0", "+0", "00", "-1", "01", " 1", "1.0", "1e3", "bad")) {
+ Map claims = validClaims();
+ claims.put("membershipVersion", Map.of(TENANT_B, invalid));
+ assertInvalid(claims);
+ }
+ }
+
+ @Test
+ void largeAccountCutoffCountersRemainExactAndPositiveWithIndependentCheckpoint() {
+ String generation = "9223372036854775808";
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put("accountAuthorityGeneration", generation);
+ tuple.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ generation,
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/" + ACCOUNT,
+ "outboxSequence",
+ "9007199254740993"));
+ claims.put("authorityTuple", tuple);
+ assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1, 4096L))
+ .doesNotThrowAnyException();
+ tuple.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ generation,
+ "outboxStreamKey",
+ "account:auth-authority:v1:account/" + ACCOUNT,
+ "outboxSequence",
+ "0"));
+ assertInvalid(claims);
+ }
+
+ @Test
+ void preservesProfileSpecificOptionalAccountCutoffOmission() {
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put("accountAuthorityGeneration", "2");
+ claims.put("authorityTuple", tuple);
+
+ assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1, 4096L))
+ .doesNotThrowAnyException();
+ }
+
+ @Test
+ void billingCutoffCountersAcceptExactDecimalStringsAndRejectNumericAliases() {
+ for (String field :
+ List.of("tenantAuthorityGeneration", "tenantBillingSequence", "outboxSequence")) {
+ for (Object value :
+ List.of("9223372036854775808", 1L, "0", "-1", "+1", "01", " 1", "1.0", "1e3")) {
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ Map cutoff =
+ new LinkedHashMap<>(
+ Map.of(
+ "tenantAuthorityGeneration", "2",
+ "tenantBillingSequence", "3",
+ "outboxStreamKey", "account:auth-authority:v1:tenant/" + TENANT_A,
+ "outboxSequence", "4"));
+ cutoff.put(field, value);
+ tuple.put("tenantBillingCutoff", Map.of(TENANT_A, cutoff));
+ claims.put("authorityTuple", tuple);
+ if ("9223372036854775808".equals(value)) {
+ assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1, 4096L))
+ .doesNotThrowAnyException();
+ } else {
+ assertInvalid(claims);
+ }
+ }
+ }
+ }
+
+ @Test
+ void controlUiCannotCarryPrivateGrantAuthorityInEitherCounterRepresentation() {
+ for (Object version : List.of("9223372036854775808", 1L)) {
+ Map claims = validClaims();
+ Map tuple = object(claims.get("authorityTuple"));
+ tuple.put(
+ "privateRealmGrantVersions",
+ List.of(
+ Map.of(
+ "tenantId",
+ TENANT_A,
+ "worldSlug",
+ "world",
+ "realmSlug",
+ "realm",
+ "playtestLifecycleId",
+ UUID.randomUUID().toString(),
+ "grantVersion",
+ version)));
+ claims.put("authorityTuple", tuple);
+ assertInvalid(claims);
+ }
+ }
+
+ @Test
+ void rejectsMismatchedMembershipPairMalformedScopeAndEmptyPresentOptionalObject() {
+ Map mismatch = validClaims();
+ mismatch.put("membershipVersion", Map.of(TENANT_A, "8"));
+ assertInvalid(mismatch);
+
+ Map badScope = validClaims();
+ badScope.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin")));
+ assertInvalid(badScope);
+
+ Map emptyBillingObject = validClaims();
+ Map tuple = object(emptyBillingObject.get("authorityTuple"));
+ tuple.put("tenantBillingCutoff", Map.of());
+ emptyBillingObject.put("authorityTuple", tuple);
+ assertInvalid(emptyBillingObject);
+
+ Map nullBillingObject = validClaims();
+ tuple = object(nullBillingObject.get("authorityTuple"));
+ tuple.put("tenantBillingCutoff", null);
+ nullBillingObject.put("authorityTuple", tuple);
+ assertInvalid(nullBillingObject);
+
+ Map