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 malformedRole = validClaims(); + malformedRole.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin", "tenantAdmin"))); + assertInvalid(malformedRole); + assertInvalid(Map.of("unexpected", true)); + } + + @Test + void sharedConfiguredScopeCapBoundsEveryControlUiApplicabilityMap() { + Map tooManyScopedRoles = validClaims(); + tooManyScopedRoles.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyScopedRoles, 1); + + Map tooManyTenantGenerations = validClaims(); + Map tenantTuple = object(tooManyTenantGenerations.get("authorityTuple")); + tenantTuple.put("tenantAuthorityGeneration", Map.of(TENANT_A, "2", TENANT_B, "3")); + tooManyTenantGenerations.put("authorityTuple", tenantTuple); + tooManyTenantGenerations.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyTenantGenerations, 1); + + Map tooManyMembershipGenerations = validClaims(); + Map membershipTuple = + object(tooManyMembershipGenerations.get("authorityTuple")); + membershipTuple.put("membershipAuthorityGeneration", Map.of(TENANT_A, "2", TENANT_B, "3")); + tooManyMembershipGenerations.put("authorityTuple", membershipTuple); + tooManyMembershipGenerations.put("membershipVersion", Map.of(TENANT_A, "7", TENANT_B, "8")); + tooManyMembershipGenerations.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + assertInvalidAtCap(tooManyMembershipGenerations, 1); + + Map tooManyBillingCutoffs = validClaims(); + Map billingTuple = object(tooManyBillingCutoffs.get("authorityTuple")); + Map cutoff = + Map.of( + "tenantAuthorityGeneration", "2", + "tenantBillingSequence", "3", + "outboxStreamKey", "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", "4"); + billingTuple.put("tenantBillingCutoff", Map.of(TENANT_A, cutoff, TENANT_B, cutoff)); + tooManyBillingCutoffs.put("authorityTuple", billingTuple); + tooManyBillingCutoffs.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyBillingCutoffs, 1); + } + + @Test + void eachControlUiApplicabilityMapAcceptsTheExactConfiguredCap() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put( + "tenantBillingCutoff", + Map.of( + TENANT_A, + Map.of( + "tenantAuthorityGeneration", + "2", + "tenantBillingSequence", + "3", + "outboxStreamKey", + "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", + "4"))); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1, 4096L)) + .doesNotThrowAnyException(); + } + + @Test + void nilAndAccountIdTenantKeysAreRejectedAsMalformedProfileKeys() { + Map nilAccount = validClaims(); + nilAccount.put("sub", "00000000-0000-0000-0000-000000000000"); + nilAccount.put("accountId", "00000000-0000-0000-0000-000000000000"); + assertInvalid(nilAccount); + + Map accountKey = validClaims(); + Map tuple = object(accountKey.get("authorityTuple")); + tuple.put("tenantAuthorityGeneration", Map.of(ACCOUNT, "2")); + accountKey.put("authorityTuple", tuple); + accountKey.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(accountKey); + } + + @Test + void canonicalAuthorityTupleByteCeilingIsEnforcedAfterTheFiniteCountCap() { + Map tenantGenerations = new LinkedHashMap<>(); + Map> scopedRoles = new LinkedHashMap<>(); + for (int index = 0; index < 100; index++) { + String tenantId = UUID.randomUUID().toString(); + tenantGenerations.put(tenantId, "1"); + scopedRoles.put(tenantId, List.of("reader")); + } + Map claims = baseClaims(); + claims.put("authorityTuple", authorityTuple(tenantGenerations, Map.of(), List.of())); + claims.put("membershipVersion", Map.of()); + claims.put("scopedRoles", scopedRoles); + + assertInvalidAtCap(claims, 128); + } + + private static Map validClaims() { + 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"))); + return claims; + } + + private static Map baseClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", ACCOUNT); + claims.put("accountId", ACCOUNT); + claims.put("jti", UUID.randomUUID().toString()); + claims.put("aud", ControlUiJwtProfileValidator.AUDIENCE); + claims.put("iat", 1L); + claims.put("nbf", 1L); + claims.put("exp", 300L); + claims.put("tokenGeneration", "1"); + claims.put("issuanceFence", "1"); + return claims; + } + + private static Map authorityTuple( + Map tenantGenerations, + Map membershipGenerations, + List privateGrants) { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", "1"); + tuple.put("accountAuthorityGeneration", "1"); + tuple.put("tenantAuthorityGeneration", tenantGenerations); + tuple.put("membershipAuthorityGeneration", membershipGenerations); + tuple.put("privateRealmGrantVersions", privateGrants); + return tuple; + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return new LinkedHashMap<>((Map) value); + } + + private static void assertInvalid(Map claims) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, 8, 4096L)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } + + private static void assertInvalidAtCap(Map claims, int cap) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, cap, 4096L)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java index 4425e3be94..9db49bbfdf 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java @@ -6,6 +6,8 @@ import java.util.UUID; import java.util.regex.Pattern; 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.entity.Game; import org.jooq.DSLContext; @@ -31,6 +33,8 @@ public class GameTenantCreationRepository { private static final Pattern DNS_LABEL = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); private static final Table OPERATION_TABLE = DSL.table(DSL.name("game_tenant_creation_operations")); + private static final Table CREATOR_QUALIFICATION_TABLE = + DSL.table(DSL.name("game_tenant_creation_creator_qualifications")); private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); private static final Field SCHEMA_VERSION_FIELD = DSL.field(DSL.name("schema_version"), Integer.class); @@ -53,6 +57,20 @@ public class GameTenantCreationRepository { DSL.field(DSL.name("provenance_kind"), String.class); private static final Field EVIDENCE_DIGEST = DSL.field(DSL.name("evidence_digest"), String.class); + private static final Field CREATOR_QUALIFICATION_REQUIRED = + DSL.field(DSL.name("creator_qualification_required"), Boolean.class); + private static final Field CREATOR_QUALIFICATION_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field CREATOR_QUALIFICATION_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field INITIATING_ACCOUNT_ID = + DSL.field(DSL.name("initiating_account_id"), UUID.class); + private static final Field ACCOUNT_AUTHORIZATION_OPERATION_ID = + DSL.field(DSL.name("account_authorization_operation_id"), UUID.class); + private static final Field ACCOUNT_AUTHORIZATION_DIGEST = + DSL.field(DSL.name("account_authorization_digest"), String.class); + private static final Field CREATOR_EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); private final DSLContext dsl; private final GameRepository gameRepository; @@ -76,8 +94,31 @@ public FreshTenantCreationEvidence createCandidate( String sourceGameTenantKey, String name, String description) { + return createCandidateInternal( + targetNamespace, creationRequestId, sourceGameTenantKey, name, description, false); + } + + /** + * Candidate-only storage producer for a distinct creator qualification. + * + *

The UUID and digest values are structurally validated but are not authenticated by this + * repository. A protected Account capture adapter must establish their authority before calling + * this method. The source operation and creator qualification are committed atomically. + */ + @Transactional(propagation = Propagation.MANDATORY) + public FreshTenantCreatorEvidence createCandidateWithCreator( + String targetNamespace, + UUID creationRequestId, + String sourceGameTenantKey, + String name, + String description, + UUID initiatingAccountId, + UUID accountAuthorizationOperationId, + String accountAuthorizationDigest) { requireActiveOwnerTransaction(); validateInput(targetNamespace, creationRequestId, sourceGameTenantKey, name, description); + validateCreatorBinding( + initiatingAccountId, accountAuthorizationOperationId, accountAuthorizationDigest); String requestDigest = GameTenantCreationDigest.requestDigest( @@ -94,6 +135,7 @@ public FreshTenantCreationEvidence createCandidate( .set(NAME, name) .set(DESCRIPTION, description) .set(STATUS, PENDING) + .set(CREATOR_QUALIFICATION_REQUIRED, true) .onConflictDoNothing() .execute(); @@ -113,6 +155,141 @@ public FreshTenantCreationEvidence createCandidate( throw new CreationRequestConflictException( "Fresh tenant creation request identity was reused with changed input"); } + FreshTenantCreationEvidence sourceEvidence = toReceipt(existing); + if (!Boolean.TRUE.equals(existing.get(CREATOR_QUALIFICATION_REQUIRED))) { + throw new CreationRequestConflictException( + "Creator qualification cannot be attached to an existing source-only operation"); + } + FreshTenantCreatorEvidence existingQualification = + readCreatorQualificationForOperation(sourceEvidence); + if (!existingQualification.initiatingAccountId().equals(initiatingAccountId) + || !existingQualification + .accountAuthorizationOperationId() + .equals(accountAuthorizationOperationId) + || !existingQualification + .accountAuthorizationDigest() + .equals(accountAuthorizationDigest)) { + throw new CreationRequestConflictException( + "Fresh tenant creator binding was reused with changed Account authority"); + } + return existingQualification; + } + + if (gameRepository.findByTenantId(sourceGameTenantKey) != null) { + throw new CreationRequestConflictException( + "Fresh tenant creation source key already belongs to a game row"); + } + + Game candidate = new Game(); + candidate.setTenantId(sourceGameTenantKey); + candidate.setName(name); + candidate.setDescription(description); + Game saved = gameRepository.save(candidate); + requireNewGameSource(saved, sourceGameTenantKey); + + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + creationRequestId, + operationId, + requestDigest, + saved.getCanonicalTenantId(), + saved.getId(), + sourceGameTenantKey, + NEW_GAME_ROW); + int completed = + dsl.update(OPERATION_TABLE) + .set(STATUS, COMPLETED) + .set(CANONICAL_TENANT_ID, saved.getCanonicalTenantId()) + .set(SOURCE_GAME_ROW_ID, saved.getId()) + .set(PROVENANCE_KIND, NEW_GAME_ROW) + .set(EVIDENCE_DIGEST, evidenceDigest) + .where(OPERATION_ID.eq(operationId).and(STATUS.eq(PENDING))) + .execute(); + if (completed != 1) { + throw new IllegalStateException("Fresh tenant creation operation claim was lost"); + } + + Record completedRecord = + dsl.selectFrom(OPERATION_TABLE).where(OPERATION_ID.eq(operationId)).fetchOne(); + if (completedRecord == null) { + throw new IllegalStateException("Completed fresh tenant creation operation is missing"); + } + FreshTenantCreationEvidence sourceEvidence = toReceipt(completedRecord); + String creatorEvidenceDigest = + FreshTenantCreatorDigest.evidenceDigest( + 1, + sourceEvidence, + initiatingAccountId, + accountAuthorizationOperationId, + accountAuthorizationDigest); + dsl.insertInto(CREATOR_QUALIFICATION_TABLE) + .set(CREATOR_QUALIFICATION_OPERATION_ID, operationId) + .set(CREATOR_QUALIFICATION_SCHEMA_VERSION, 1) + .set(INITIATING_ACCOUNT_ID, initiatingAccountId) + .set(ACCOUNT_AUTHORIZATION_OPERATION_ID, accountAuthorizationOperationId) + .set(ACCOUNT_AUTHORIZATION_DIGEST, accountAuthorizationDigest) + .set(CREATOR_EVIDENCE_DIGEST, creatorEvidenceDigest) + .execute(); + + return new FreshTenantCreatorEvidence( + 1, + sourceEvidence, + initiatingAccountId, + accountAuthorizationOperationId, + accountAuthorizationDigest, + creatorEvidenceDigest); + } + + private FreshTenantCreationEvidence createCandidateInternal( + String targetNamespace, + UUID creationRequestId, + String sourceGameTenantKey, + String name, + String description, + boolean creatorQualificationRequired) { + requireActiveOwnerTransaction(); + validateInput(targetNamespace, creationRequestId, sourceGameTenantKey, name, description); + + String requestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, creationRequestId, sourceGameTenantKey, name, description); + UUID operationId = newNonNilUuid(); + int inserted = + dsl.insertInto(OPERATION_TABLE) + .set(OPERATION_ID, operationId) + .set(SCHEMA_VERSION_FIELD, SCHEMA_VERSION) + .set(TARGET_NAMESPACE, targetNamespace) + .set(CREATION_REQUEST_ID, creationRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(SOURCE_GAME_TENANT_KEY, sourceGameTenantKey) + .set(NAME, name) + .set(DESCRIPTION, description) + .set(STATUS, PENDING) + .set(CREATOR_QUALIFICATION_REQUIRED, creatorQualificationRequired) + .onConflictDoNothing() + .execute(); + + if (inserted == 0) { + Record existing = + dsl.selectFrom(OPERATION_TABLE) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CREATION_REQUEST_ID.eq(creationRequestId))) + .fetchOne(); + if (existing == null) { + throw new CreationRequestConflictException( + "Fresh tenant creation source key is already claimed by another operation"); + } + if (!sameRequest(existing, sourceGameTenantKey, name, description, requestDigest)) { + throw new CreationRequestConflictException( + "Fresh tenant creation request identity was reused with changed input"); + } + if (Boolean.TRUE.equals(existing.get(CREATOR_QUALIFICATION_REQUIRED))) { + throw new CreationRequestConflictException( + "Qualified fresh tenant creation cannot be retried as source-only creation"); + } return toReceipt(existing); } @@ -176,6 +353,77 @@ public Optional read( return record == null ? Optional.empty() : Optional.of(toReceipt(record)); } + /** + * Reads the source operation and creator qualification separately after commit and compares the + * complete immutable request binding. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readCreatorQualification( + UUID creationRequestId, + String targetNamespace, + String expectedRequestDigest, + String expectedCreationEvidenceDigest, + UUID expectedInitiatingAccountId, + UUID expectedAccountAuthorizationOperationId, + String expectedAccountAuthorizationDigest, + String expectedCreatorEvidenceDigest) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Fresh tenant creator read requires a committed-outcome owner read"); + } + validateSelector(targetNamespace, creationRequestId); + if (!GameTenantCreationDigest.isDigest(expectedRequestDigest) + || !GameTenantCreationDigest.isDigest(expectedCreationEvidenceDigest) + || !GameTenantCreationDigest.isDigest(expectedCreatorEvidenceDigest)) { + throw new IllegalArgumentException("Canonical expected fresh tenant digests are required"); + } + validateCreatorBinding( + expectedInitiatingAccountId, + expectedAccountAuthorizationOperationId, + expectedAccountAuthorizationDigest); + + Optional sourceResult = read(creationRequestId, targetNamespace); + if (sourceResult.isEmpty()) { + return Optional.empty(); + } + FreshTenantCreationEvidence sourceEvidence = sourceResult.orElseThrow(); + if (!expectedRequestDigest.equals(sourceEvidence.requestDigest()) + || !expectedCreationEvidenceDigest.equals(sourceEvidence.evidenceDigest())) { + throw invalidEvidence("Fresh tenant creator read does not match the exact source evidence"); + } + + Record operationRecord = + dsl.selectFrom(OPERATION_TABLE) + .where(OPERATION_ID.eq(sourceEvidence.operationId())) + .fetchOne(); + if (operationRecord == null) { + throw invalidEvidence("Fresh tenant creator source operation disappeared during readback"); + } + + Record creatorRecord = + dsl.selectFrom(CREATOR_QUALIFICATION_TABLE) + .where(CREATOR_QUALIFICATION_OPERATION_ID.eq(sourceEvidence.operationId())) + .fetchOne(); + if (creatorRecord == null) { + if (Boolean.TRUE.equals(operationRecord.get(CREATOR_QUALIFICATION_REQUIRED))) { + throw invalidEvidence("Qualified fresh tenant operation has no creator evidence"); + } + return Optional.empty(); + } + if (!Boolean.TRUE.equals(operationRecord.get(CREATOR_QUALIFICATION_REQUIRED))) { + throw invalidEvidence("Creator qualification is attached to a source-only operation"); + } + FreshTenantCreatorEvidence qualification = toCreatorEvidence(creatorRecord, sourceEvidence); + if (!expectedInitiatingAccountId.equals(qualification.initiatingAccountId()) + || !expectedAccountAuthorizationOperationId.equals( + qualification.accountAuthorizationOperationId()) + || !expectedAccountAuthorizationDigest.equals(qualification.accountAuthorizationDigest()) + || !expectedCreatorEvidenceDigest.equals(qualification.evidenceDigest())) { + throw invalidEvidence("Fresh tenant creator qualification does not match the exact request"); + } + return Optional.of(qualification); + } + private void requireActiveOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( @@ -227,6 +475,66 @@ private void validateSelector(String targetNamespace, UUID creationRequestId) { } } + private void validateCreatorBinding( + UUID initiatingAccountId, + UUID accountAuthorizationOperationId, + String accountAuthorizationDigest) { + if (initiatingAccountId == null || initiatingAccountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("A canonical nonnil initiating Account UUID is required"); + } + if (accountAuthorizationOperationId == null + || accountAuthorizationOperationId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "A canonical nonnil Account authorization operation UUID is required"); + } + if (!GameTenantCreationDigest.isDigest(accountAuthorizationDigest)) { + throw new IllegalArgumentException("A canonical Account authorization digest is required"); + } + } + + private FreshTenantCreatorEvidence readCreatorQualificationForOperation( + FreshTenantCreationEvidence sourceEvidence) { + Record creatorRecord = + dsl.selectFrom(CREATOR_QUALIFICATION_TABLE) + .where(CREATOR_QUALIFICATION_OPERATION_ID.eq(sourceEvidence.operationId())) + .fetchOne(); + if (creatorRecord == null) { + throw invalidEvidence("Qualified fresh tenant operation has no creator evidence"); + } + return toCreatorEvidence(creatorRecord, sourceEvidence); + } + + private FreshTenantCreatorEvidence toCreatorEvidence( + Record record, FreshTenantCreationEvidence sourceEvidence) { + Integer schemaVersion = record.get(CREATOR_QUALIFICATION_SCHEMA_VERSION); + UUID initiatingAccountId = record.get(INITIATING_ACCOUNT_ID); + UUID accountAuthorizationOperationId = record.get(ACCOUNT_AUTHORIZATION_OPERATION_ID); + String accountAuthorizationDigest = record.get(ACCOUNT_AUTHORIZATION_DIGEST); + String evidenceDigest = record.get(CREATOR_EVIDENCE_DIGEST); + if (schemaVersion == null + || schemaVersion != 1 + || initiatingAccountId == null + || initiatingAccountId.equals(new UUID(0L, 0L)) + || accountAuthorizationOperationId == null + || accountAuthorizationOperationId.equals(new UUID(0L, 0L)) + || !GameTenantCreationDigest.isDigest(accountAuthorizationDigest) + || !GameTenantCreationDigest.isDigest(evidenceDigest)) { + throw invalidEvidence("Stored fresh tenant creator qualification is incomplete or malformed"); + } + try { + return new FreshTenantCreatorEvidence( + schemaVersion, + sourceEvidence, + initiatingAccountId, + accountAuthorizationOperationId, + accountAuthorizationDigest, + evidenceDigest); + } catch (IllegalArgumentException exception) { + throw invalidEvidence( + "Stored fresh tenant creator qualification digest does not match its tuple", exception); + } + } + private void requireNewGameSource(Game saved, String sourceGameTenantKey) { if (saved == null || saved.getId() == null diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index 2c0cfa4837..830932501e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; @@ -20,11 +21,14 @@ import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService.ApprovedAssociation; +import net.firedevops.firemud.gamedesign.v1.FreshTenantCreatorQualificationEvidence; import net.firedevops.firemud.gamedesign.v1.GameSessionTenantAssociationManifestEvidence; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; 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.ResolveLegacyAccountTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; @@ -334,6 +338,150 @@ && isCanonicalNonNilUuid(receipt.canonicalTenantId()) responseObserver.onCompleted(); } + @Override + public void resolveFreshTenantCreatorQualification( + ResolveFreshTenantCreatorQualificationRequest request, + StreamObserver responseObserver) { + if (SessionContext.hasAuthenticatedCallerContext() || !isAccountPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified Account workload identity without caller context is required") + .asRuntimeException()); + return; + } + + UUID readRequestId = parseCanonicalNonNilUuid(request.getReadRequestId()); + UUID creationRequestId = parseCanonicalNonNilUuid(request.getCreationRequestId()); + UUID initiatingAccountId = parseCanonicalNonNilUuid(request.getInitiatingAccountId()); + UUID authorizationOperationId = + parseCanonicalNonNilUuid(request.getAccountAuthorizationOperationId()); + String expectedRequestDigest = request.getExpectedRequestDigest(); + String expectedCreationEvidenceDigest = request.getExpectedEvidenceDigest(); + String expectedAuthorizationDigest = request.getAccountAuthorizationDigest(); + String expectedCreatorEvidenceDigest = request.getExpectedCreatorEvidenceDigest(); + if (readRequestId == null + || creationRequestId == null + || initiatingAccountId == null + || authorizationOperationId == null + || !isSha256Digest(expectedRequestDigest) + || !isSha256Digest(expectedCreationEvidenceDigest) + || !isSha256Digest(expectedAuthorizationDigest) + || !isSha256Digest(expectedCreatorEvidenceDigest) + || !request.getUnknownFields().asMap().isEmpty()) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical closed fresh tenant creator request is required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = + creationRepository.readCreatorQualification( + creationRequestId, + workloadNamespace, + expectedRequestDigest, + expectedCreationEvidenceDigest, + initiatingAccountId, + authorizationOperationId, + expectedAuthorizationDigest, + expectedCreatorEvidenceDigest); + } catch (GameTenantCreationRepository.InvalidCreationEvidenceException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Fresh tenant creator evidence is incomplete or inconsistent") + .asRuntimeException()); + return; + } catch (TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Fresh tenant creator evidence is ambiguous") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Fresh tenant creator evidence is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription("Fresh tenant creator evidence could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Fresh tenant creator evidence could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No qualified fresh tenant creator for the exact request") + .asRuntimeException()); + return; + } + + FreshTenantCreatorEvidence qualification = resolved.orElseThrow(); + FreshTenantCreationEvidence source = qualification.creationEvidence(); + boolean exactEvidence = + source.schemaVersion() == 1 + && workloadNamespace.equals(source.targetNamespace()) + && creationRequestId.equals(source.creationRequestId()) + && expectedRequestDigest.equals(source.requestDigest()) + && expectedCreationEvidenceDigest.equals(source.evidenceDigest()) + && initiatingAccountId.equals(qualification.initiatingAccountId()) + && authorizationOperationId.equals(qualification.accountAuthorizationOperationId()) + && expectedAuthorizationDigest.equals(qualification.accountAuthorizationDigest()) + && expectedCreatorEvidenceDigest.equals(qualification.evidenceDigest()); + if (!exactEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Fresh tenant creator readback does not match the exact request") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveFreshTenantCreatorQualificationResponse.newBuilder() + .setReadRequestId(readRequestId.toString()) + .setCreationEvidence(toCreationResponse(source)) + .setCreatorQualification( + FreshTenantCreatorQualificationEvidence.newBuilder() + .setSchemaVersion(qualification.schemaVersion()) + .setInitiatingAccountId(qualification.initiatingAccountId().toString()) + .setAccountAuthorizationOperationId( + qualification.accountAuthorizationOperationId().toString()) + .setAccountAuthorizationDigest(qualification.accountAuthorizationDigest()) + .setEvidenceDigest(qualification.evidenceDigest()) + .build()) + .build()); + responseObserver.onCompleted(); + } + + private ResolveFreshTenantCreationResponse toCreationResponse( + FreshTenantCreationEvidence evidence) { + return ResolveFreshTenantCreationResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setCreationRequestId(evidence.creationRequestId().toString()) + .setOperationId(evidence.operationId().toString()) + .setRequestDigest(evidence.requestDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setEvidenceDigest(evidence.evidenceDigest()) + .build(); + } + @Override public void resolveRuntimeTenantIdentity( ResolveRuntimeTenantIdentityRequest request, diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index ea9ca1244b..dc71c367cf 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -52,6 +52,7 @@ firemud: public-methods: - gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreatorQualification - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index bd2d7ea02f..2f2aa07b17 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -84,6 +84,7 @@ firemud: public-methods: - gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreatorQualification - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation diff --git a/services/game-design-service/src/main/resources/db/migration/V46__game_tenant_creation_initiator_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V46__game_tenant_creation_initiator_evidence.sql new file mode 100644 index 0000000000..b3bac2a54c --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V46__game_tenant_creation_initiator_evidence.sql @@ -0,0 +1,165 @@ +ALTER TABLE game_tenant_creation_operations + ADD COLUMN creator_qualification_required BOOLEAN NOT NULL DEFAULT FALSE; + +CREATE TABLE game_tenant_creation_creator_qualifications ( + operation_id UUID PRIMARY KEY + REFERENCES game_tenant_creation_operations(operation_id), + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + initiating_account_id UUID NOT NULL, + account_authorization_operation_id UUID NOT NULL, + account_authorization_digest VARCHAR(71) NOT NULL, + evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT chk_game_tenant_creator_initiator_non_nil + CHECK (initiating_account_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_game_tenant_creator_authorization_operation_non_nil + CHECK ( + account_authorization_operation_id + <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_game_tenant_creator_authorization_digest + CHECK (account_authorization_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_game_tenant_creator_evidence_digest + CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION enforce_game_tenant_creation_operation() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game tenant creation operation evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING' + OR NEW.canonical_tenant_id IS NOT NULL + OR NEW.source_game_row_id IS NOT NULL + OR NEW.provenance_kind IS NOT NULL + OR NEW.evidence_digest IS NOT NULL THEN + RAISE EXCEPTION 'Game tenant creation operations must begin pending' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.status <> 'PENDING' OR NEW.status <> 'COMPLETED' + OR NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.schema_version IS DISTINCT FROM OLD.schema_version + OR NEW.target_namespace IS DISTINCT FROM OLD.target_namespace + OR NEW.creation_request_id IS DISTINCT FROM OLD.creation_request_id + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.name IS DISTINCT FROM OLD.name + OR NEW.description IS DISTINCT FROM OLD.description + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR NEW.creator_qualification_required IS DISTINCT FROM OLD.creator_qualification_required + OR OLD.canonical_tenant_id IS NOT NULL + OR OLD.source_game_row_id IS NOT NULL + OR OLD.provenance_kind IS NOT NULL + OR OLD.evidence_digest IS NOT NULL THEN + RAISE EXCEPTION 'Game tenant creation operation evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = 'NEW_GAME_ROW' + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game tenant creation source evidence does not match a new game row' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION enforce_game_tenant_creation_creator_qualification() RETURNS trigger AS $$ +DECLARE + owner_requires_qualification BOOLEAN; + owner_status VARCHAR(16); +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game tenant creator qualification evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game tenant creator qualification evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT creator_qualification_required, status + INTO owner_requires_qualification, owner_status + FROM game_tenant_creation_operations + WHERE operation_id = NEW.operation_id; + + IF owner_requires_qualification IS DISTINCT FROM TRUE OR owner_status <> 'COMPLETED' THEN + RAISE EXCEPTION 'Creator qualification cannot attach to source-only or incomplete creation' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_tenant_creation_creator_qualification_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_tenant_creation_creator_qualifications + FOR EACH ROW EXECUTE FUNCTION enforce_game_tenant_creation_creator_qualification(); + +CREATE FUNCTION reject_game_tenant_creation_creator_qualification_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game tenant creator qualification evidence cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_tenant_creation_creator_qualification_no_truncate + BEFORE TRUNCATE ON game_tenant_creation_creator_qualifications + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_tenant_creation_creator_qualification_truncate(); + +CREATE FUNCTION require_game_tenant_creation_creator_qualification() RETURNS trigger AS $$ +DECLARE + current_required BOOLEAN; + current_status VARCHAR(16); + qualification_exists BOOLEAN; +BEGIN + SELECT creator_qualification_required, status + INTO current_required, current_status + FROM game_tenant_creation_operations + WHERE operation_id = NEW.operation_id; + + IF current_status IS DISTINCT FROM 'COMPLETED' THEN + RAISE EXCEPTION 'Game tenant creation operation cannot commit while pending' + USING ERRCODE = 'check_violation'; + END IF; + + IF current_required THEN + SELECT EXISTS ( + SELECT 1 + FROM game_tenant_creation_creator_qualifications q + WHERE q.operation_id = NEW.operation_id + ) INTO qualification_exists; + IF NOT qualification_exists THEN + RAISE EXCEPTION 'Qualified game tenant creation cannot commit without creator evidence' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER game_tenant_creation_creator_qualification_must_complete + AFTER INSERT OR UPDATE ON game_tenant_creation_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_game_tenant_creation_creator_qualification(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java index 9a5200f9d2..b8edf758ac 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java @@ -16,6 +16,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; @@ -41,6 +42,8 @@ class GameTenantCreationRepositoryIntegrationTest { private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; private static final Table GAME = DSL.table(DSL.name("game")); private static final Table OPERATIONS = DSL.table(DSL.name("game_tenant_creation_operations")); + private static final Table CREATOR_QUALIFICATIONS = + DSL.table(DSL.name("game_tenant_creation_creator_qualifications")); private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); private static final org.jooq.Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); @@ -56,12 +59,33 @@ class GameTenantCreationRepositoryIntegrationTest { DSL.field(DSL.name("creation_request_id"), UUID.class); private static final org.jooq.Field REQUEST_DIGEST = DSL.field(DSL.name("request_digest"), String.class); + private static final org.jooq.Field OPERATION_EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); private static final org.jooq.Field SOURCE_GAME_TENANT_KEY = DSL.field(DSL.name("source_game_tenant_key"), String.class); private static final org.jooq.Field NAME = DSL.field(DSL.name("name"), String.class); private static final org.jooq.Field DESCRIPTION = DSL.field(DSL.name("description"), String.class); private static final org.jooq.Field STATUS = DSL.field(DSL.name("status"), String.class); + private static final org.jooq.Field CREATOR_QUALIFICATION_REQUIRED = + DSL.field(DSL.name("creator_qualification_required"), Boolean.class); + private static final org.jooq.Field CREATOR_QUALIFICATION_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field ACCOUNT_AUTHORIZATION_DIGEST = + DSL.field(DSL.name("account_authorization_digest"), String.class); + private static final org.jooq.Field CREATOR_QUALIFICATION_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final org.jooq.Field INITIATING_ACCOUNT_ID_FIELD = + DSL.field(DSL.name("initiating_account_id"), UUID.class); + private static final org.jooq.Field ACCOUNT_AUTHORIZATION_OPERATION_ID = + DSL.field(DSL.name("account_authorization_operation_id"), UUID.class); + private static final org.jooq.Field CREATOR_EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); + private static final UUID INITIATING_ACCOUNT_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); private static final String NAMESPACE = "fresh-tenant-test"; private static final String SOURCE_KEY = "new-game-tenant-01"; private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -92,6 +116,325 @@ void createCandidateExactRetryReturnsCommittedReceiptWithoutSecondGameWrite() th assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); } + @Test + void qualifiedCreationCommitsSourceAndCreatorEvidenceAtomicallyAndReadsBothBack() + throws Exception { + Fixture fixture = fixture(); + FreshTenantCreatorEvidence created = + fixture.inTransaction( + () -> + createQualified( + fixture, + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST)); + + FreshTenantCreationEvidence sourceEvidence = + fixture.repository.read(REQUEST_ID, NAMESPACE).orElseThrow(); + FreshTenantCreatorEvidence committedReadback = + fixture + .repository + .readCreatorQualification( + REQUEST_ID, + NAMESPACE, + sourceEvidence.requestDigest(), + sourceEvidence.evidenceDigest(), + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + created.evidenceDigest()) + .orElseThrow(); + + assertThat(committedReadback).isEqualTo(created); + assertThat(committedReadback.creationEvidence()).isEqualTo(sourceEvidence); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(CREATOR_QUALIFICATIONS)).isEqualTo(1); + assertThat( + fixture + .dsl + .select(REQUEST_DIGEST) + .from(OPERATIONS) + .where(CREATION_REQUEST_ID.eq(REQUEST_ID)) + .fetchOne(REQUEST_DIGEST)) + .isEqualTo(sourceEvidence.requestDigest()); + assertThat( + fixture + .dsl + .select(OPERATION_EVIDENCE_DIGEST) + .from(OPERATIONS) + .where(CREATION_REQUEST_ID.eq(REQUEST_ID)) + .fetchOne(OPERATION_EVIDENCE_DIGEST)) + .isEqualTo(sourceEvidence.evidenceDigest()); + } + + @Test + void qualifiedRetryWithChangedInitiatorOrAuthorizationConflictsBeforeMutation() throws Exception { + Fixture fixture = fixture(); + FreshTenantCreatorEvidence first = + fixture.inTransaction( + () -> + createQualified( + fixture, + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST)); + String originalGameXmin = gameXmin(fixture.dsl, SOURCE_KEY); + + assertThat( + fixture.inTransaction( + () -> + createQualified( + fixture, + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST))) + .isEqualTo(first); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + createQualified( + fixture, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST))) + .isInstanceOf(GameTenantCreationRepository.CreationRequestConflictException.class) + .hasMessageContaining("changed Account authority"); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + createQualified( + fixture, + INITIATING_ACCOUNT_ID, + UUID.fromString("88888888-8888-4888-8888-888888888888"), + AUTHORIZATION_DIGEST))) + .isInstanceOf(GameTenantCreationRepository.CreationRequestConflictException.class) + .hasMessageContaining("changed Account authority"); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + createQualified( + fixture, + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + "sha256:" + "b".repeat(64)))) + .isInstanceOf(GameTenantCreationRepository.CreationRequestConflictException.class) + .hasMessageContaining("changed Account authority"); + + assertThat(gameXmin(fixture.dsl, SOURCE_KEY)).isEqualTo(originalGameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(CREATOR_QUALIFICATIONS)).isEqualTo(1); + } + + @Test + void sourceOnlyOperationCannotReceiveCreatorQualificationRetroactively() throws Exception { + Fixture fixture = fixture(); + FreshTenantCreationEvidence sourceOnly = + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "The First World", "A description")); + String originalGameXmin = gameXmin(fixture.dsl, SOURCE_KEY); + + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + createQualified( + fixture, + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST))) + .isInstanceOf(GameTenantCreationRepository.CreationRequestConflictException.class) + .hasMessageContaining("cannot be attached to an existing source-only operation"); + assertThatThrownBy( + () -> + fixture + .dsl + .insertInto(CREATOR_QUALIFICATIONS) + .set(CREATOR_QUALIFICATION_OPERATION_ID, sourceOnly.operationId()) + .set(CREATOR_QUALIFICATION_SCHEMA_VERSION, 1) + .set(INITIATING_ACCOUNT_ID_FIELD, INITIATING_ACCOUNT_ID) + .set(ACCOUNT_AUTHORIZATION_OPERATION_ID, AUTHORIZATION_OPERATION_ID) + .set(ACCOUNT_AUTHORIZATION_DIGEST, AUTHORIZATION_DIGEST) + .set(CREATOR_EVIDENCE_DIGEST, "sha256:" + "b".repeat(64)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot attach to source-only"); + + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).contains(sourceOnly); + assertThat(gameXmin(fixture.dsl, SOURCE_KEY)).isEqualTo(originalGameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(CREATOR_QUALIFICATIONS)).isZero(); + } + + @Test + void creatorQualificationEvidenceCannotBeUpdatedDeletedOrTruncated() throws Exception { + Fixture fixture = fixture(); + FreshTenantCreatorEvidence created = + fixture.inTransaction( + () -> + createQualified( + fixture, + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST)); + + assertThatThrownBy( + () -> + fixture + .dsl + .update(CREATOR_QUALIFICATIONS) + .set(ACCOUNT_AUTHORIZATION_DIGEST, "sha256:" + "b".repeat(64)) + .where( + CREATOR_QUALIFICATION_OPERATION_ID.eq( + created.creationEvidence().operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl + .deleteFrom(CREATOR_QUALIFICATIONS) + .where( + CREATOR_QUALIFICATION_OPERATION_ID.eq( + created.creationEvidence().operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE TABLE game_tenant_creation_creator_qualifications")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot be truncated"); + + assertThat( + fixture.repository.readCreatorQualification( + REQUEST_ID, + NAMESPACE, + created.creationEvidence().requestDigest(), + created.creationEvidence().evidenceDigest(), + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + created.evidenceDigest())) + .contains(created); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(CREATOR_QUALIFICATIONS)).isEqualTo(1); + } + + @Test + void creatorQualificationRequiredOperationCannotCommitWithoutItsQualifier() throws Exception { + Fixture fixture = fixture(); + FreshTenantCreationEvidence sourceOnly = + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "The First World", "A description")); + + try (Connection connection = fixture.dataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute( + "ALTER TABLE game_tenant_creation_operations " + + "DISABLE TRIGGER game_tenant_creation_operation_immutable"); + try { + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> + fixture + .dsl + .update(OPERATIONS) + .set(CREATOR_QUALIFICATION_REQUIRED, true) + .where(OPERATION_ID.eq(sourceOnly.operationId())) + .execute())) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("without creator evidence"); + } finally { + statement.execute( + "ALTER TABLE game_tenant_creation_operations " + + "ENABLE TRIGGER game_tenant_creation_operation_immutable"); + } + } + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).contains(sourceOnly); + assertThat(fixture.dsl.fetchCount(CREATOR_QUALIFICATIONS)).isZero(); + } + + @Test + void concurrentQualifiedRetriesWithSameBindingConvergeOnOneSourceAndQualifier() throws Exception { + Fixture fixture = fixture(); + CountDownLatch firstOperationCreated = new CountDownLatch(1); + CountDownLatch allowFirstCommit = new CountDownLatch(1); + CountDownLatch secondOperationStarted = new CountDownLatch(1); + AtomicInteger firstBackendPid = new AtomicInteger(); + AtomicInteger secondBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + fixture.transactionTemplate.execute( + status -> { + FreshTenantCreatorEvidence evidence = + createQualified( + fixture, + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST); + firstBackendPid.set(currentBackendPid(fixture.dsl)); + firstOperationCreated.countDown(); + awaitLatch(allowFirstCommit); + return evidence; + })); + assertThat(firstOperationCreated.await(10, TimeUnit.SECONDS)).isTrue(); + Future second = + executor.submit( + () -> + fixture.transactionTemplate.execute( + status -> { + secondBackendPid.set(currentBackendPid(fixture.dsl)); + secondOperationStarted.countDown(); + return createQualified( + fixture, + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST); + })); + assertThat(secondOperationStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitDatabaseBlocking(fixture.dataSource, secondBackendPid.get(), firstBackendPid.get()); + allowFirstCommit.countDown(); + + FreshTenantCreatorEvidence firstEvidence = first.get(10, TimeUnit.SECONDS); + FreshTenantCreatorEvidence secondEvidence = second.get(10, TimeUnit.SECONDS); + assertThat(secondEvidence).isEqualTo(firstEvidence); + assertThat(secondEvidence.creationEvidence().canonicalTenantId()) + .isEqualTo(firstEvidence.creationEvidence().canonicalTenantId()); + assertThat( + fixture.repository.readCreatorQualification( + REQUEST_ID, + NAMESPACE, + firstEvidence.creationEvidence().requestDigest(), + firstEvidence.creationEvidence().evidenceDigest(), + INITIATING_ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + firstEvidence.evidenceDigest())) + .contains(firstEvidence); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(CREATOR_QUALIFICATIONS)).isEqualTo(1); + } finally { + allowFirstCommit.countDown(); + executor.shutdownNow(); + } + } + @Test void runtimeIdentityLookupReadsOnlyExactNewAndRetainedGameDesignRows() throws Exception { RetainedFixture retainedFixture = fixtureWithRetainedGame(); @@ -445,6 +788,22 @@ void concurrentDuplicateCreationRequestsConvergeOnOneUuidAndReceipt() throws Exc } } + private FreshTenantCreatorEvidence createQualified( + Fixture fixture, + UUID initiatingAccountId, + UUID authorizationOperationId, + String authorizationDigest) { + return fixture.repository.createCandidateWithCreator( + NAMESPACE, + REQUEST_ID, + SOURCE_KEY, + "The First World", + "A description", + initiatingAccountId, + authorizationOperationId, + authorizationDigest); + } + private Fixture fixture() { String schema = "game_design_creation_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java index 6a73e9c2cf..0ae2e85cb6 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java @@ -34,6 +34,8 @@ class TenantIdentityAuthConfigurationTest { "gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation"; private static final String FRESH_CREATION_METHOD = "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation"; + private static final String FRESH_CREATOR_QUALIFICATION_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreatorQualification"; private static final String RUNTIME_TENANT_METHOD = "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity"; private static final String AUTHORED_WORLD_SOURCE_METHOD = @@ -83,6 +85,7 @@ private void assertConfiguration(GrpcAuthProperties properties) { .containsExactlyInAnyOrder( ACCOUNT_ASSOCIATION_METHOD, FRESH_CREATION_METHOD, + FRESH_CREATOR_QUALIFICATION_METHOD, RUNTIME_TENANT_METHOD, AUTHORED_WORLD_SOURCE_METHOD, GAME_SESSION_ASSOCIATION_METHOD, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java index 95599935bc..3e86f8aa07 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java @@ -11,6 +11,7 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; class GameTenantCreationRepositoryTest { private static final String NAMESPACE = "test"; @@ -70,4 +71,56 @@ void readRejectsChangedStoredRequestDigestBeforeReadingGameOwner() throws Except verifyNoInteractions(gameRepository); } } + + @Test + void qualifiedCandidateRejectsMalformedAccountBindingBeforeOwnerAccess() { + DSLContext dsl = mock(DSLContext.class); + GameRepository gameRepository = mock(GameRepository.class); + GameTenantCreationRepository repository = new GameTenantCreationRepository(dsl, gameRepository); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + repository.createCandidateWithCreator( + NAMESPACE, + REQUEST_ID, + SOURCE_KEY, + NAME, + null, + new UUID(0L, 0L), + OPERATION_ID, + "sha256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("initiating Account UUID"); + assertThatThrownBy( + () -> + repository.createCandidateWithCreator( + NAMESPACE, + REQUEST_ID, + SOURCE_KEY, + NAME, + null, + TENANT_ID, + new UUID(0L, 0L), + "sha256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("authorization operation UUID"); + assertThatThrownBy( + () -> + repository.createCandidateWithCreator( + NAMESPACE, + REQUEST_ID, + SOURCE_KEY, + NAME, + null, + TENANT_ID, + OPERATION_ID, + "SHA256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("authorization digest"); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(dsl, gameRepository); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java index 12803d002a..4d252852d5 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java @@ -58,13 +58,20 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +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.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.v1.FreshTenantCreatorQualificationEvidence; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; 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.ResolveLegacyAccountTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; @@ -96,17 +103,19 @@ import org.springframework.core.io.FileSystemResource; /** - * Physical socket proof for Game Design's authored-world source read boundary. + * Physical socket proof for Game Design's authored-world source and creator-qualification reads. * *

The production gRPC service, peer-identity interceptor, JWT interceptor, and shared source - * client run over ephemeral mTLS sockets. The owner repository is mocked and returns a complete, - * digest-valid schema-v1 receipt; this suite does not prove source registration persistence, normal - * source creation, World intake, local association, publication, or runtime activation. + * client run over ephemeral mTLS sockets. Owner repositories are mocked and return complete, + * digest-valid evidence; this suite does not prove persistence, Account caller authorization or + * membership bootstrap, World intake, local association, publication, or runtime activation. */ class AuthoredWorldSourceMtlsTest { private static final String NAMESPACE = "test"; private static final String SOURCE_METHOD = "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource"; + private static final String CREATOR_QUALIFICATION_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreatorQualification"; private static final String AUTHORIZATION = "authorization"; private static final String JWT_SECRET = "test-secret-key-test-secret-key-32-bytes"; private static final UUID REGISTRATION_REQUEST_ID = @@ -121,10 +130,24 @@ class AuthoredWorldSourceMtlsTest { Set.of( "gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation", "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", + CREATOR_QUALIFICATION_METHOD, "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity", SOURCE_METHOD, "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation"); private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final UUID FRESH_CREATION_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666661"); + private static final UUID FRESH_CREATION_OPERATION_ID = + UUID.fromString("66666666-6666-4666-8666-666666666662"); + private static final UUID ACCOUNT_ID = UUID.fromString("66666666-6666-4666-8666-666666666663"); + private static final UUID ACCOUNT_AUTHORIZATION_OPERATION_ID = + UUID.fromString("66666666-6666-4666-8666-666666666664"); + private static final UUID CREATOR_READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666665"); + private static final String ACCOUNT_AUTHORIZATION_DIGEST = "sha256:" + "c".repeat(64); + private static final FreshTenantCreationEvidence FRESH_CREATION_EVIDENCE = + freshTenantCreationEvidence(); + private static final FreshTenantCreatorEvidence CREATOR_EVIDENCE = creatorEvidence(ACCOUNT_ID); private static final AuthoredWorldSourceGrpcCodec.ReadRequest READ_REQUEST = new AuthoredWorldSourceGrpcCodec.ReadRequest( NAMESPACE, READ_REQUEST_ID, SOURCE_OPERATION_ID, TENANT_ID, "harbor-world"); @@ -193,6 +216,12 @@ static void generateEphemeralPki() throws Exception { "cross-namespace-game-session-service", "spiffe://firemud/ns/other-test/sa/game-session-service", false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "cross-namespace-account-service", + "spiffe://firemud/ns/other-test/sa/account-service", + false), issueLeaf( caName, caKeyPair.getPrivate(), @@ -247,7 +276,7 @@ void exactWorldAndGameSessionReadersResolveCompleteSourceReceiptThroughSharedCli void wrongServiceNamespaceAndSharedCertificatesAreDeniedBeforeOwnerRead() throws Exception { for (TestCertificate clientCertificate : List.of( - pki.wrongServiceCertificate(), + pki.accountServiceCertificate(), pki.wrongNamespaceCertificate(), pki.noWorkloadUriCertificate())) { ManagedChannel channel = channel(server, clientCertificate, jwtToken()); @@ -424,6 +453,11 @@ void productionYamlAndSocketGuardsKeepWorldAccessLimitedToExactSourceMethod() th stub.resolveLegacyGameSessionTenantAssociation( ResolveLegacyGameSessionTenantAssociationRequest.getDefaultInstance()), Status.Code.PERMISSION_DENIED); + assertStatus( + () -> + stub.resolveFreshTenantCreatorQualification( + ResolveFreshTenantCreatorQualificationRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); } finally { stopChannel(channel); } @@ -436,6 +470,136 @@ void productionYamlAndSocketGuardsKeepWorldAccessLimitedToExactSourceMethod() th gameSessionAssociationRepository); } + @Test + void exactSameNamespaceAccountPeerReadsCreatorQualificationOverPhysicalMtls() throws Exception { + when(creationRepository.readCreatorQualification( + FRESH_CREATION_REQUEST_ID, + NAMESPACE, + FRESH_CREATION_EVIDENCE.requestDigest(), + FRESH_CREATION_EVIDENCE.evidenceDigest(), + ACCOUNT_ID, + ACCOUNT_AUTHORIZATION_OPERATION_ID, + ACCOUNT_AUTHORIZATION_DIGEST, + CREATOR_EVIDENCE.evidenceDigest())) + .thenReturn(Optional.of(CREATOR_EVIDENCE)); + + ManagedChannel channel = channel(server, pki.accountServiceCertificate(), null); + try { + var response = + creatorStub(channel).resolveFreshTenantCreatorQualification(creatorReadRequest()); + + assertThat(response.getReadRequestId()).isEqualTo(CREATOR_READ_REQUEST_ID.toString()); + assertThat(response.getCreationEvidence()) + .isEqualTo(toCreationResponse(FRESH_CREATION_EVIDENCE)); + assertThat(response.getCreatorQualification()) + .isEqualTo( + FreshTenantCreatorQualificationEvidence.newBuilder() + .setSchemaVersion(CREATOR_EVIDENCE.schemaVersion()) + .setInitiatingAccountId(ACCOUNT_ID.toString()) + .setAccountAuthorizationOperationId(ACCOUNT_AUTHORIZATION_OPERATION_ID.toString()) + .setAccountAuthorizationDigest(ACCOUNT_AUTHORIZATION_DIGEST) + .setEvidenceDigest(CREATOR_EVIDENCE.evidenceDigest()) + .build()); + } finally { + stopChannel(channel); + } + + verify(creationRepository) + .readCreatorQualification( + FRESH_CREATION_REQUEST_ID, + NAMESPACE, + FRESH_CREATION_EVIDENCE.requestDigest(), + FRESH_CREATION_EVIDENCE.evidenceDigest(), + ACCOUNT_ID, + ACCOUNT_AUTHORIZATION_OPERATION_ID, + ACCOUNT_AUTHORIZATION_DIGEST, + CREATOR_EVIDENCE.evidenceDigest()); + verifyNoInteractions( + gameRepository, + associationService, + authoredWorldRepository, + gameSessionAssociationRepository); + } + + @Test + void worldCrossNamespaceAndMissingPeersCannotReadCreatorQualification() throws Exception { + for (TestCertificate clientCertificate : + List.of(pki.worldManagementCertificate(), pki.crossNamespaceAccountCertificate())) { + ManagedChannel channel = channel(server, clientCertificate, null); + try { + assertStatus( + () -> creatorStub(channel).resolveFreshTenantCreatorQualification(creatorReadRequest()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + } + + ManagedChannel noPeerChannel = channel(server, null, null); + try { + assertTlsDenied( + () -> + creatorStub(noPeerChannel) + .resolveFreshTenantCreatorQualification(creatorReadRequest()), + CREATOR_QUALIFICATION_METHOD); + } finally { + stopChannel(noPeerChannel); + } + + verifyNoInteractions(creationRepository); + } + + @Test + void changedInitiatingAccountBindingFailsClosedAfterPhysicalAccountAuthentication() + throws Exception { + UUID changedAccountId = UUID.fromString("77777777-7777-4777-8777-777777777777"); + String changedExpectedCreatorDigest = + FreshTenantCreatorDigest.evidenceDigest( + 1, + FRESH_CREATION_EVIDENCE, + changedAccountId, + ACCOUNT_AUTHORIZATION_OPERATION_ID, + ACCOUNT_AUTHORIZATION_DIGEST); + when(creationRepository.readCreatorQualification( + FRESH_CREATION_REQUEST_ID, + NAMESPACE, + FRESH_CREATION_EVIDENCE.requestDigest(), + FRESH_CREATION_EVIDENCE.evidenceDigest(), + changedAccountId, + ACCOUNT_AUTHORIZATION_OPERATION_ID, + ACCOUNT_AUTHORIZATION_DIGEST, + changedExpectedCreatorDigest)) + .thenReturn(Optional.of(CREATOR_EVIDENCE)); + + ManagedChannel channel = channel(server, pki.accountServiceCertificate(), null); + try { + assertStatus( + () -> + creatorStub(channel) + .resolveFreshTenantCreatorQualification( + creatorReadRequest(changedAccountId, changedExpectedCreatorDigest)), + Status.Code.FAILED_PRECONDITION); + } finally { + stopChannel(channel); + } + + verify(creationRepository) + .readCreatorQualification( + FRESH_CREATION_REQUEST_ID, + NAMESPACE, + FRESH_CREATION_EVIDENCE.requestDigest(), + FRESH_CREATION_EVIDENCE.evidenceDigest(), + changedAccountId, + ACCOUNT_AUTHORIZATION_OPERATION_ID, + ACCOUNT_AUTHORIZATION_DIGEST, + changedExpectedCreatorDigest); + verifyNoInteractions( + gameRepository, + associationService, + authoredWorldRepository, + gameSessionAssociationRepository); + } + private Server startReceiver(TestCertificate serverCertificate) throws Exception { return startReceiver(serverCertificate, null); } @@ -531,6 +695,46 @@ private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub sourc .withDeadlineAfter(3, TimeUnit.SECONDS); } + private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub creatorStub( + ManagedChannel channel) { + return TenantIdentityServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private static ResolveFreshTenantCreatorQualificationRequest creatorReadRequest() { + return creatorReadRequest(ACCOUNT_ID, CREATOR_EVIDENCE.evidenceDigest()); + } + + private static ResolveFreshTenantCreatorQualificationRequest creatorReadRequest( + UUID initiatingAccountId, String expectedCreatorEvidenceDigest) { + return ResolveFreshTenantCreatorQualificationRequest.newBuilder() + .setReadRequestId(CREATOR_READ_REQUEST_ID.toString()) + .setCreationRequestId(FRESH_CREATION_REQUEST_ID.toString()) + .setExpectedRequestDigest(FRESH_CREATION_EVIDENCE.requestDigest()) + .setExpectedEvidenceDigest(FRESH_CREATION_EVIDENCE.evidenceDigest()) + .setInitiatingAccountId(initiatingAccountId.toString()) + .setAccountAuthorizationOperationId(ACCOUNT_AUTHORIZATION_OPERATION_ID.toString()) + .setAccountAuthorizationDigest(ACCOUNT_AUTHORIZATION_DIGEST) + .setExpectedCreatorEvidenceDigest(expectedCreatorEvidenceDigest) + .build(); + } + + private static ResolveFreshTenantCreationResponse toCreationResponse( + FreshTenantCreationEvidence evidence) { + return ResolveFreshTenantCreationResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setCreationRequestId(evidence.creationRequestId().toString()) + .setOperationId(evidence.operationId().toString()) + .setRequestDigest(evidence.requestDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setEvidenceDigest(evidence.evidenceDigest()) + .build(); + } + private static ResolveAuthoredWorldSourceRequest wireReadRequest() { return AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST); } @@ -728,6 +932,51 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { evidenceDigest); } + private static FreshTenantCreationEvidence freshTenantCreationEvidence() { + String sourceTenantKey = "fresh-game-tenant-17"; + String requestDigest = + GameTenantCreationDigest.requestDigest( + NAMESPACE, FRESH_CREATION_REQUEST_ID, sourceTenantKey, "Fresh World", "Description"); + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + FRESH_CREATION_REQUEST_ID, + FRESH_CREATION_OPERATION_ID, + requestDigest, + TENANT_ID, + 17L, + sourceTenantKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + FRESH_CREATION_REQUEST_ID, + FRESH_CREATION_OPERATION_ID, + requestDigest, + TENANT_ID, + 17L, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static FreshTenantCreatorEvidence creatorEvidence(UUID initiatingAccountId) { + String evidenceDigest = + FreshTenantCreatorDigest.evidenceDigest( + 1, + FRESH_CREATION_EVIDENCE, + initiatingAccountId, + ACCOUNT_AUTHORIZATION_OPERATION_ID, + ACCOUNT_AUTHORIZATION_DIGEST); + return new FreshTenantCreatorEvidence( + 1, + FRESH_CREATION_EVIDENCE, + initiatingAccountId, + ACCOUNT_AUTHORIZATION_OPERATION_ID, + ACCOUNT_AUTHORIZATION_DIGEST, + evidenceDigest); + } + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); return Files.writeString( @@ -867,7 +1116,8 @@ private record TestPki( TestCertificate wrongServerNamespaceCertificate, TestCertificate worldManagementCertificate, TestCertificate gameSessionCertificate, - TestCertificate wrongServiceCertificate, + TestCertificate accountServiceCertificate, TestCertificate wrongNamespaceCertificate, + TestCertificate crossNamespaceAccountCertificate, TestCertificate noWorkloadUriCertificate) {} } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index e898e86792..58e419751e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -26,6 +26,8 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; 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.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; @@ -37,6 +39,8 @@ import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; 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.ResolveLegacyAccountTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; @@ -73,6 +77,13 @@ class TenantIdentityGrpcServiceTest { UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID FRESH_CANONICAL_TENANT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID CREATOR_READ_REQUEST_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID CREATOR_INITIATING_ACCOUNT_ID = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID CREATOR_AUTHORIZATION_OPERATION_ID = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final String CREATOR_AUTHORIZATION_DIGEST = "sha256:" + "d".repeat(64); private static final UUID RUNTIME_REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); private static final UUID RUNTIME_TENANT_ID = @@ -630,6 +641,127 @@ void freshCreationReadMapsConnectionSqlStateToUnavailableOnly() { assertNull(syntaxFailure.value); } + @Test + void freshCreatorQualificationReadRequiresExactAccountPeerWithoutForwardedContext() { + for (String peer : + new String[] { + null, + WRONG_PEER, + WRONG_NAMESPACE_ACCOUNT_PEER, + ACCOUNT_MIGRATOR_PEER, + WRONG_NAMESPACE_MIGRATOR_PEER, + GAME_DESIGN_PEER + }) { + FreshCreatorObserver observer = freshCreatorCall(freshCreatorRequest(), peer, false); + assertEquals(Status.Code.PERMISSION_DENIED, freshCreatorStatus(observer)); + assertNull(observer.value); + } + FreshCreatorObserver forwardedContext = + freshCreatorCall(freshCreatorRequest(), ACCOUNT_PEER, true); + assertEquals(Status.Code.PERMISSION_DENIED, freshCreatorStatus(forwardedContext)); + assertNull(forwardedContext.value); + verifyNoInteractions(creationRepository); + } + + @Test + void freshCreatorQualificationReadRejectsMalformedIdsDigestsAndUnknownFieldsBeforeOwnerRead() { + ResolveFreshTenantCreatorQualificationRequest exact = freshCreatorRequest(); + UnknownFieldSet unknownFields = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (ResolveFreshTenantCreatorQualificationRequest request : + new ResolveFreshTenantCreatorQualificationRequest[] { + exact.toBuilder().setReadRequestId("bad").build(), + exact.toBuilder().setCreationRequestId("00000000-0000-0000-0000-000000000000").build(), + exact.toBuilder().setInitiatingAccountId("bad").build(), + exact.toBuilder().setAccountAuthorizationOperationId("bad").build(), + exact.toBuilder().setExpectedEvidenceDigest("bad").build(), + exact.toBuilder().setExpectedCreatorEvidenceDigest("SHA256:" + "d".repeat(64)).build(), + exact.toBuilder().setUnknownFields(unknownFields).build() + }) { + FreshCreatorObserver observer = freshCreatorCall(request, ACCOUNT_PEER, false); + assertEquals(Status.Code.INVALID_ARGUMENT, freshCreatorStatus(observer)); + assertNull(observer.value); + } + verifyNoInteractions(creationRepository); + } + + @Test + void exactAccountPeerReadsCreatorQualificationAndPreservesOriginalSourceEvidence() { + FreshTenantCreatorEvidence evidence = freshCreatorEvidence(freshCreationReceipt()); + when(creationRepository.readCreatorQualification( + FRESH_CREATION_REQUEST_ID, + "test", + evidence.creationEvidence().requestDigest(), + evidence.creationEvidence().evidenceDigest(), + CREATOR_INITIATING_ACCOUNT_ID, + CREATOR_AUTHORIZATION_OPERATION_ID, + CREATOR_AUTHORIZATION_DIGEST, + evidence.evidenceDigest())) + .thenReturn(Optional.of(evidence)); + + FreshCreatorObserver first = freshCreatorCall(freshCreatorRequest(), ACCOUNT_PEER, false); + FreshCreatorObserver retry = freshCreatorCall(freshCreatorRequest(), ACCOUNT_PEER, false); + + assertNull(first.errorCode); + assertTrue(first.completed); + assertEquals(CREATOR_READ_REQUEST_ID.toString(), first.value.getReadRequestId()); + assertEquals(freshCreationReceiptResponse(), first.value.getCreationEvidence()); + assertEquals(1, first.value.getCreatorQualification().getSchemaVersion()); + assertEquals( + CREATOR_INITIATING_ACCOUNT_ID.toString(), + first.value.getCreatorQualification().getInitiatingAccountId()); + assertEquals( + CREATOR_AUTHORIZATION_OPERATION_ID.toString(), + first.value.getCreatorQualification().getAccountAuthorizationOperationId()); + assertEquals( + CREATOR_AUTHORIZATION_DIGEST, + first.value.getCreatorQualification().getAccountAuthorizationDigest()); + assertEquals( + evidence.evidenceDigest(), first.value.getCreatorQualification().getEvidenceDigest()); + assertNull(retry.errorCode); + assertTrue(retry.completed); + assertEquals(first.value, retry.value); + verify(creationRepository, org.mockito.Mockito.times(2)) + .readCreatorQualification( + FRESH_CREATION_REQUEST_ID, + "test", + evidence.creationEvidence().requestDigest(), + evidence.creationEvidence().evidenceDigest(), + CREATOR_INITIATING_ACCOUNT_ID, + CREATOR_AUTHORIZATION_OPERATION_ID, + CREATOR_AUTHORIZATION_DIGEST, + evidence.evidenceDigest()); + verifyNoMoreInteractions(creationRepository); + } + + @Test + void creatorQualificationReadFailsClosedWhenMissingOrChanged() { + FreshTenantCreatorEvidence changed = + freshCreatorEvidence(freshCreationReceipt("other", FRESH_CREATION_REQUEST_ID)); + when(creationRepository.readCreatorQualification( + FRESH_CREATION_REQUEST_ID, + "test", + FRESH_REQUEST_DIGEST, + freshCreationReceipt().evidenceDigest(), + CREATOR_INITIATING_ACCOUNT_ID, + CREATOR_AUTHORIZATION_OPERATION_ID, + CREATOR_AUTHORIZATION_DIGEST, + freshCreatorEvidence(freshCreationReceipt()).evidenceDigest())) + .thenReturn(Optional.empty()) + .thenReturn(Optional.of(changed)); + + FreshCreatorObserver absent = freshCreatorCall(freshCreatorRequest(), ACCOUNT_PEER, false); + FreshCreatorObserver changedSource = + freshCreatorCall(freshCreatorRequest(), ACCOUNT_PEER, false); + + assertEquals(Status.Code.NOT_FOUND, freshCreatorStatus(absent)); + assertEquals(Status.Code.FAILED_PRECONDITION, freshCreatorStatus(changedSource)); + assertNull(absent.value); + assertNull(changedSource.value); + } + @Test void exactGameSessionPeerReadsNewAndRetainedIdentityAndRetryKeepsOwnerSource() { GameTenantIdentity newRowIdentity = @@ -894,6 +1026,83 @@ private FreshCreationObserver freshCreationCall( return observer; } + private ResolveFreshTenantCreatorQualificationRequest freshCreatorRequest() { + FreshTenantCreationEvidence source = freshCreationReceipt(); + String creatorDigest = + FreshTenantCreatorDigest.evidenceDigest( + 1, + source, + CREATOR_INITIATING_ACCOUNT_ID, + CREATOR_AUTHORIZATION_OPERATION_ID, + CREATOR_AUTHORIZATION_DIGEST); + return ResolveFreshTenantCreatorQualificationRequest.newBuilder() + .setReadRequestId(CREATOR_READ_REQUEST_ID.toString()) + .setCreationRequestId(source.creationRequestId().toString()) + .setExpectedRequestDigest(source.requestDigest()) + .setExpectedEvidenceDigest(source.evidenceDigest()) + .setInitiatingAccountId(CREATOR_INITIATING_ACCOUNT_ID.toString()) + .setAccountAuthorizationOperationId(CREATOR_AUTHORIZATION_OPERATION_ID.toString()) + .setAccountAuthorizationDigest(CREATOR_AUTHORIZATION_DIGEST) + .setExpectedCreatorEvidenceDigest(creatorDigest) + .build(); + } + + private FreshCreatorObserver freshCreatorCall( + ResolveFreshTenantCreatorQualificationRequest request, + String peerUri, + boolean authenticatedContext) { + FreshCreatorObserver observer = new FreshCreatorObserver(); + Context context = Context.current(); + if (peerUri != null) { + context = + context.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + } + if (authenticatedContext) { + SessionContext.setContext(FRESH_CANONICAL_TENANT_ID.toString(), List.of(), Map.of()); + } + try { + context.run(() -> service.resolveFreshTenantCreatorQualification(request, observer)); + } finally { + if (authenticatedContext) { + SessionContext.clear(); + } + } + return observer; + } + + private FreshTenantCreatorEvidence freshCreatorEvidence( + FreshTenantCreationEvidence sourceEvidence) { + return new FreshTenantCreatorEvidence( + 1, + sourceEvidence, + CREATOR_INITIATING_ACCOUNT_ID, + CREATOR_AUTHORIZATION_OPERATION_ID, + CREATOR_AUTHORIZATION_DIGEST, + FreshTenantCreatorDigest.evidenceDigest( + 1, + sourceEvidence, + CREATOR_INITIATING_ACCOUNT_ID, + CREATOR_AUTHORIZATION_OPERATION_ID, + CREATOR_AUTHORIZATION_DIGEST)); + } + + private ResolveFreshTenantCreationResponse freshCreationReceiptResponse() { + FreshTenantCreationEvidence evidence = freshCreationReceipt(); + return ResolveFreshTenantCreationResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setCreationRequestId(evidence.creationRequestId().toString()) + .setOperationId(evidence.operationId().toString()) + .setRequestDigest(evidence.requestDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setEvidenceDigest(evidence.evidenceDigest()) + .build(); + } + private RuntimeIdentityObserver runtimeIdentityCall( String canonicalTenantId, String requestId, String peerUri) { RuntimeIdentityObserver observer = new RuntimeIdentityObserver(); @@ -972,6 +1181,11 @@ private static Status.Code freshCreationStatus(FreshCreationObserver observer) { return observer.errorCode; } + private static Status.Code freshCreatorStatus(FreshCreatorObserver observer) { + assertNotNull(observer.errorCode); + return observer.errorCode; + } + private static Status.Code runtimeIdentityStatus(RuntimeIdentityObserver observer) { assertNotNull(observer.errorCode); return observer.errorCode; @@ -1048,6 +1262,28 @@ public void onCompleted() { } } + private static final class FreshCreatorObserver + implements StreamObserver { + private ResolveFreshTenantCreatorQualificationResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ResolveFreshTenantCreatorQualificationResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + private static final class AuthoredSourceObserver implements StreamObserver { private ResolveAuthoredWorldSourceResponse value; diff --git a/services/game-logic-service/build.gradle.kts b/services/game-logic-service/build.gradle.kts index dbd48d7512..f9a822a51b 100644 --- a/services/game-logic-service/build.gradle.kts +++ b/services/game-logic-service/build.gradle.kts @@ -4,6 +4,11 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { id("net.firedevops.firemud.service-conventions") id("net.firedevops.firemud.openapi-conventions") + id("net.firedevops.firemud.jooq-conventions") +} + +firemudJooq { + packageName.set("net.firedevops.firemud.gamelogic.jooq") } dependencies { diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicEmptyRuleInputManifestService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicEmptyRuleInputManifestService.java new file mode 100644 index 0000000000..44cf2f9bad --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicEmptyRuleInputManifestService.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.gamelogic.authoring; + +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, default-denied Game Logic owner operation for a fresh empty rule manifest. + * + *

No production verifier is supplied. A future integration must validate the exact current Game + * Design source and Version proof plus Account commit authority for this complete binding, then + * continuously hold that authority through the owner transaction. This class has no RPC and is + * deliberately not a Spring component. + */ +public final class GameLogicEmptyRuleInputManifestService { + private final GameLogicRuleInputManifestRepository repository; + private final CommitAuthorityVerifier verifier; + + /** Constructs the production-safe default: all owner applications fail closed. */ + public GameLogicEmptyRuleInputManifestService(GameLogicRuleInputManifestRepository repository) { + this(repository, GameLogicEmptyRuleInputManifestService::denyByDefault); + } + + /** Constructor for an explicitly supplied exact-source/Account authority verifier. */ + public GameLogicEmptyRuleInputManifestService( + GameLogicRuleInputManifestRepository repository, CommitAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Applies the one exact empty-manifest intent and returns only a committed, independently + * verified immutable owner row. The public digest handler is not wired to this storage path. + */ + public GameLogicRuleInputManifest apply(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Logic rule manifest application must verify outside an ambient transaction"); + } + GameLogicRuleInputManifest input = GameLogicRuleInputManifest.fromExplicitEmptyIntent(binding); + HeldCommitAuthority held = + Objects.requireNonNull( + verifier.verifyAndHold(binding), + "Game Logic verifier returned no held Account/source authority"); + try (held) { + held.requireHeld(); + repository.apply(input, held); + // TransactionTemplate has committed before this final held-state check. + held.requireHeld(); + return repository + .read(input.tenantId(), input.versionId()) + .orElseThrow( + () -> + new GameLogicRuleInputManifestRepository.InvalidStoredManifestException( + "Committed Game Logic manifest has no exact owner readback")); + } + } + + private static HeldCommitAuthority denyByDefault(DraftCommitBinding binding) { + throw new ApplicationDeniedException( + "Game Logic has no authenticated current-source and Account commit-authority verifier"); + } + + /** Validates the complete current-source binding and holds Account authority through commit. */ + @FunctionalInterface + public interface CommitAuthorityVerifier { + HeldCommitAuthority verifyAndHold(DraftCommitBinding binding); + } + + /** + * A verifier-owned continuously effective authorization/fence handle. Implementations must assert + * local held state without issuing RPC while Game Logic holds database locks. + */ + public interface HeldCommitAuthority extends AutoCloseable { + void requireHeld(); + + @Override + void close(); + } + + public static final class ApplicationDeniedException extends IllegalStateException { + public ApplicationDeniedException(String message) { + super(message); + } + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifest.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifest.java new file mode 100644 index 0000000000..8032a763ca --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifest.java @@ -0,0 +1,243 @@ +package net.firedevops.firemud.gamelogic.authoring; + +import static net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.ObjectMapper; + +/** + * Exact Game Logic owner input for the only currently supported rule-manifest application. + * + *

The empty arrays are an explicit versioned owner revision, not an inference from missing rows. + * The complete cross-owner binding and its Game Design source proof remain unchanged and are + * retained as provenance; neither is mixed into the semantic content digest. + */ +public record GameLogicRuleInputManifest( + DraftCommitBinding binding, + UUID revisionId, + String sourceProofJson, + String ownerIntentJson, + String manifestJson, + int digestSchemaVersion, + String contentDigest, + int abilitySchemaVersion, + String abilitySchemaJson, + String abilitySchemaDigest, + String ownerResultJson, + String ownerResultDigest) { + public static final String AGGREGATE_TYPE = "VERSION_RULE_MANIFEST"; + public static final String SCOPE_TYPE = "VERSION"; + public static final String EMPTY_INTENT_KIND = "EMPTY_RULE_INPUT_MANIFEST/v1"; + public static final int DIGEST_SCHEMA_VERSION = 1; + public static final int ABILITY_SCHEMA_VERSION = 1; + public static final long INITIAL_EPOCH = 0L; + public static final long APPLIED_EPOCH = 1L; + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ABILITY_DIGEST_DOMAIN = "firemud.game-logic.ability-schema/v1"; + + public GameLogicRuleInputManifest { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(revisionId, "revisionId"); + Objects.requireNonNull(sourceProofJson, "sourceProofJson"); + Objects.requireNonNull(ownerIntentJson, "ownerIntentJson"); + Objects.requireNonNull(manifestJson, "manifestJson"); + Objects.requireNonNull(contentDigest, "contentDigest"); + Objects.requireNonNull(abilitySchemaJson, "abilitySchemaJson"); + Objects.requireNonNull(abilitySchemaDigest, "abilitySchemaDigest"); + Objects.requireNonNull(ownerResultJson, "ownerResultJson"); + Objects.requireNonNull(ownerResultDigest, "ownerResultDigest"); + } + + /** + * Validates the complete Game Design binding and derives the closed empty owner manifest. Future + * non-empty or configured rule/ability input remains explicitly unsupported. + */ + public static GameLogicRuleInputManifest fromExplicitEmptyIntent(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + if (!binding.requiredOwners().equals(Arrays.asList(Owner.values()))) { + throw new InvalidRuleManifestIntentException( + "A full Draft binding must retain all five required publication owners"); + } + + TargetProof target = binding.target(); + String versionId = target.canonicalVersionId().toString(); + List ownerUnits = binding.affectedUnits(Owner.GAME_LOGIC); + if (ownerUnits.size() != 1) { + throw new InvalidRuleManifestIntentException( + "The Game Logic owner must declare exactly one VERSION_RULE_MANIFEST unit"); + } + AffectedUnit unit = ownerUnits.getFirst(); + if (!AGGREGATE_TYPE.equals(unit.aggregateType()) + || !versionId.equals(unit.aggregateId()) + || !SCOPE_TYPE.equals(unit.scopeType()) + || !versionId.equals(unit.scopeId()) + || !Long.toString(INITIAL_EPOCH).equals(unit.expectedEpoch())) { + throw new InvalidRuleManifestIntentException( + "The Game Logic owner unit must bind this canonical Version at initial epoch zero"); + } + + List ownerRevisions = + binding.revisions().stream() + .filter(revision -> revision.owner() == Owner.GAME_LOGIC) + .toList(); + if (ownerRevisions.size() != 1) { + throw new InvalidRuleManifestIntentException( + "The Game Logic owner must declare exactly one explicit empty-manifest revision"); + } + RevisionPayload revision = ownerRevisions.getFirst(); + String ownerIntentJson = emptyIntentJson(); + if (!ownerIntentJson.equals(revision.payload())) { + throw new InvalidRuleManifestIntentException( + "Game Logic currently accepts only an explicit EMPTY_RULE_INPUT_MANIFEST/v1 intent"); + } + + String manifestJson = canonicalJson(emptyManifestObject()); + String contentPreimageJson = canonicalJson(contentDigestObject()); + String abilitySchemaJson = canonicalJson(abilitySchemaDigestObject()); + String contentDigest = sha256Hex(contentPreimageJson.getBytes(StandardCharsets.UTF_8)); + String abilitySchemaDigest = sha256Hex(abilitySchemaJson.getBytes(StandardCharsets.UTF_8)); + String sourceProofJson = canonicalJson(sourceProofObject(target)); + String ownerResultJson = + canonicalJson( + ownerResultObject(binding, revision.revisionId(), contentDigest, abilitySchemaDigest)); + + return new GameLogicRuleInputManifest( + binding, + revision.revisionId(), + sourceProofJson, + ownerIntentJson, + manifestJson, + DIGEST_SCHEMA_VERSION, + contentDigest, + ABILITY_SCHEMA_VERSION, + abilitySchemaJson, + abilitySchemaDigest, + ownerResultJson, + sha256Prefixed(ownerResultJson.getBytes(StandardCharsets.UTF_8))); + } + + /** Canonical owner payload that must be carried by one Game Logic revision in the binding. */ + public static String emptyIntentJson() { + Map intent = new LinkedHashMap<>(); + intent.put("intentKind", EMPTY_INTENT_KIND); + intent.put("manifest", emptyManifestObject()); + return canonicalJson(intent); + } + + public UUID tenantId() { + return binding.target().canonicalTenantId(); + } + + public UUID versionId() { + return binding.target().canonicalVersionId(); + } + + public UUID requestId() { + return binding.requestId(); + } + + public UUID commitId() { + return binding.commitId(); + } + + public String baseCommitId() { + return binding.baseCommitId(); + } + + private static Map emptyManifestObject() { + Map manifest = new LinkedHashMap<>(); + manifest.put("abilitySchemas", List.of()); + manifest.put("ruleInputs", List.of()); + manifest.put("schemaVersion", 1); + return manifest; + } + + private static Map contentDigestObject() { + Map input = new LinkedHashMap<>(); + input.put("abilitySchemas", List.of()); + input.put("digestSchemaVersion", DIGEST_SCHEMA_VERSION); + input.put("ruleInputs", List.of()); + return input; + } + + private static Map abilitySchemaDigestObject() { + Map input = new LinkedHashMap<>(); + input.put("abilitySchemaDigestDomain", ABILITY_DIGEST_DOMAIN); + input.put("abilitySchemaVersion", ABILITY_SCHEMA_VERSION); + input.put("abilitySchemas", List.of()); + return input; + } + + private static Map sourceProofObject(TargetProof target) { + Map source = new LinkedHashMap<>(); + source.put("canonicalTenantId", target.canonicalTenantId().toString()); + source.put("canonicalVersionId", target.canonicalVersionId().toString()); + source.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + source.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + source.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + source.put("sourceGameTenantKey", target.sourceGameTenantKey()); + source.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return source; + } + + private static Map ownerResultObject( + DraftCommitBinding binding, + UUID revisionId, + String contentDigest, + String abilitySchemaDigest) { + Map result = new LinkedHashMap<>(); + result.put("abilitySchemaDigest", abilitySchemaDigest); + result.put("appliedCommitId", binding.commitId().toString()); + result.put("contentDigest", contentDigest); + result.put("digestSchemaVersion", DIGEST_SCHEMA_VERSION); + result.put("owner", Owner.GAME_LOGIC.name()); + result.put("ownerAggregateEpochAfter", Long.toString(APPLIED_EPOCH)); + result.put("ownerScopeEpochAfter", Long.toString(APPLIED_EPOCH)); + result.put("revisionId", revisionId.toString()); + result.put("status", "APPLIED"); + return result; + } + + private static String canonicalJson(Object value) { + try { + String json = JSON.writeValueAsString(value); + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalStateException( + "Game Logic manifest JSON could not be canonicalized", exception); + } + } + + private static String sha256Hex(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String sha256Prefixed(byte[] bytes) { + return "sha256:" + sha256Hex(bytes); + } + + public static final class InvalidRuleManifestIntentException extends IllegalArgumentException { + public InvalidRuleManifestIntentException(String message) { + super(message); + } + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestRepository.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestRepository.java new file mode 100644 index 0000000000..b57f3e1987 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestRepository.java @@ -0,0 +1,217 @@ +package net.firedevops.firemud.gamelogic.authoring; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Game Logic owner-local insert-only persistence and exact committed readback. + * + *

This repository is intentionally not a Spring component. Its one-row-per-Version insert is the + * epoch-zero compare-and-swap; the row retains the incremented aggregate and scope epochs, + * immutable manifest, complete binding, source proof, and exact local owner result atomically. + */ +public final class GameLogicRuleInputManifestRepository { + private static final String TABLE = "game_logic_version_rule_input_manifest"; + private static final String INSERT_SQL = + "INSERT INTO " + + TABLE + + " (canonical_tenant_id, canonical_version_id, source_proof_json, " + + "game_design_version_row_id, game_design_version_tenant_key, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, request_id, commit_id, base_commit_id, " + + "revision_id, binding_json, binding_digest, owner_intent_json, manifest_json, " + + "digest_schema_version, content_digest, ability_schema_version, ability_schema_json, " + + "ability_schema_digest, aggregate_type, aggregate_id, scope_type, scope_id, " + + "expected_epoch, aggregate_epoch_after, scope_epoch_after, owner_result_json, " + + "owner_result_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; + private static final String BY_VERSION_SQL = + "SELECT * FROM " + + TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE"; + private static final String READ_SQL = + "SELECT * FROM " + TABLE + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?"; + + private final DSLContext dsl; + private final TransactionTemplate transaction; + + public GameLogicRuleInputManifestRepository( + DSLContext dsl, PlatformTransactionManager transactionManager) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + transaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Claims epoch zero once, or validates an exact retry against the immutable original row. The + * authority handle must remain valid until the transaction manager has committed. + */ + public void apply( + GameLogicRuleInputManifest input, + GameLogicEmptyRuleInputManifestService.HeldCommitAuthority authority) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(authority, "authority"); + requireNoActiveTransaction("Game Logic rule manifest apply"); + + transaction.executeWithoutResult( + status -> { + authority.requireHeld(); + int inserted = + dsl.execute( + INSERT_SQL, + input.tenantId(), + input.versionId(), + input.sourceProofJson(), + input.binding().target().gameDesignVersionRowId(), + input.binding().target().gameDesignVersionTenantKey(), + input.binding().target().sourceGameRowId(), + input.binding().target().sourceGameTenantKey(), + input.binding().target().sourceProvenanceKind(), + input.requestId(), + input.commitId(), + input.baseCommitId(), + input.revisionId(), + input.binding().canonicalJson(), + input.binding().digest(), + input.ownerIntentJson(), + input.manifestJson(), + input.digestSchemaVersion(), + input.contentDigest(), + input.abilitySchemaVersion(), + input.abilitySchemaJson(), + input.abilitySchemaDigest(), + GameLogicRuleInputManifest.AGGREGATE_TYPE, + input.versionId().toString(), + GameLogicRuleInputManifest.SCOPE_TYPE, + input.versionId().toString(), + GameLogicRuleInputManifest.INITIAL_EPOCH, + GameLogicRuleInputManifest.APPLIED_EPOCH, + GameLogicRuleInputManifest.APPLIED_EPOCH, + input.ownerResultJson(), + input.ownerResultDigest()); + if (inserted == 0) { + Record existing = dsl.fetchOne(BY_VERSION_SQL, input.tenantId(), input.versionId()); + if (existing == null || !input.equals(decodeAndVerify(existing))) { + throw new ManifestConflictException( + "Game Logic Version manifest identity is already bound to different input"); + } + } + authority.requireHeld(); + }); + + // TransactionTemplate returns only after commit. Readback is deliberately outside that + // transaction and does not imply that the protected publication RPC is enabled. + authority.requireHeld(); + GameLogicRuleInputManifest committed = + read(input.tenantId(), input.versionId()) + .orElseThrow( + () -> + new InvalidStoredManifestException( + "Committed Game Logic manifest has no exact owner readback")); + if (!input.equals(committed)) { + throw new InvalidStoredManifestException( + "Committed Game Logic manifest readback differs from its exact input"); + } + } + + /** Internal exact manifest/digest readback for future owner composition. */ + public Optional read(UUID tenantId, UUID versionId) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(versionId, "versionId"); + requireNoActiveTransaction("Game Logic rule manifest readback"); + Record row = dsl.fetchOne(READ_SQL, tenantId, versionId); + return row == null ? Optional.empty() : Optional.of(decodeAndVerify(row)); + } + + private GameLogicRuleInputManifest decodeAndVerify(Record row) { + String bindingJson = required(row, "binding_json", String.class); + String bindingDigest = required(row, "binding_digest", String.class); + DraftCommitBinding binding = DraftCommitBinding.fromStored(bindingJson, bindingDigest); + GameLogicRuleInputManifest expected = + GameLogicRuleInputManifest.fromExplicitEmptyIntent(binding); + + requireEqual(row, "canonical_tenant_id", UUID.class, expected.tenantId()); + requireEqual(row, "canonical_version_id", UUID.class, expected.versionId()); + requireEqual(row, "source_proof_json", String.class, expected.sourceProofJson()); + requireEqual( + row, "game_design_version_row_id", Long.class, binding.target().gameDesignVersionRowId()); + requireEqual( + row, + "game_design_version_tenant_key", + String.class, + binding.target().gameDesignVersionTenantKey()); + requireEqual(row, "source_game_row_id", Long.class, binding.target().sourceGameRowId()); + requireEqual( + row, "source_game_tenant_key", String.class, binding.target().sourceGameTenantKey()); + requireEqual( + row, "source_provenance_kind", String.class, binding.target().sourceProvenanceKind()); + requireEqual(row, "request_id", UUID.class, expected.requestId()); + requireEqual(row, "commit_id", UUID.class, expected.commitId()); + requireEqual(row, "base_commit_id", String.class, expected.baseCommitId()); + requireEqual(row, "revision_id", UUID.class, expected.revisionId()); + requireEqual(row, "owner_intent_json", String.class, expected.ownerIntentJson()); + requireEqual(row, "manifest_json", String.class, expected.manifestJson()); + requireEqual(row, "digest_schema_version", Integer.class, expected.digestSchemaVersion()); + requireEqual(row, "content_digest", String.class, expected.contentDigest()); + requireEqual(row, "ability_schema_version", Integer.class, expected.abilitySchemaVersion()); + requireEqual(row, "ability_schema_json", String.class, expected.abilitySchemaJson()); + requireEqual(row, "ability_schema_digest", String.class, expected.abilitySchemaDigest()); + requireEqual(row, "aggregate_type", String.class, GameLogicRuleInputManifest.AGGREGATE_TYPE); + requireEqual(row, "aggregate_id", String.class, expected.versionId().toString()); + requireEqual(row, "scope_type", String.class, GameLogicRuleInputManifest.SCOPE_TYPE); + requireEqual(row, "scope_id", String.class, expected.versionId().toString()); + requireEqual(row, "expected_epoch", Long.class, GameLogicRuleInputManifest.INITIAL_EPOCH); + requireEqual( + row, "aggregate_epoch_after", Long.class, GameLogicRuleInputManifest.APPLIED_EPOCH); + requireEqual(row, "scope_epoch_after", Long.class, GameLogicRuleInputManifest.APPLIED_EPOCH); + requireEqual(row, "owner_result_json", String.class, expected.ownerResultJson()); + requireEqual(row, "owner_result_digest", String.class, expected.ownerResultDigest()); + return expected; + } + + private static T required(Record row, String name, Class type) { + T value = row.get(name, type); + if (value == null) { + throw new InvalidStoredManifestException("Stored Game Logic manifest is missing " + name); + } + return value; + } + + private static void requireEqual(Record row, String name, Class type, T expected) { + if (!Objects.equals(required(row, name, type), expected)) { + throw new InvalidStoredManifestException( + "Stored Game Logic manifest has inconsistent " + name); + } + } + + private static void requireNoActiveTransaction(String operation) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(operation + " must use an independent committed boundary"); + } + } + + public static final class ManifestConflictException extends IllegalStateException { + public ManifestConflictException(String message) { + super(message); + } + } + + public static final class InvalidStoredManifestException extends IllegalStateException { + public InvalidStoredManifestException(String message) { + super(message); + } + + public InvalidStoredManifestException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-logic-service/src/main/resources/db/migration/V2__game_logic_version_rule_input_manifest.sql b/services/game-logic-service/src/main/resources/db/migration/V2__game_logic_version_rule_input_manifest.sql new file mode 100644 index 0000000000..27af37c28a --- /dev/null +++ b/services/game-logic-service/src/main/resources/db/migration/V2__game_logic_version_rule_input_manifest.sql @@ -0,0 +1,98 @@ +CREATE TABLE game_logic_version_rule_input_manifest ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + source_proof_json TEXT NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + game_design_version_tenant_key VARCHAR(36) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + base_commit_id VARCHAR(256) NOT NULL, + revision_id UUID NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL, + owner_intent_json TEXT NOT NULL, + manifest_json TEXT NOT NULL, + digest_schema_version INTEGER NOT NULL, + content_digest VARCHAR(64) NOT NULL, + ability_schema_version INTEGER NOT NULL, + ability_schema_json TEXT NOT NULL, + ability_schema_digest VARCHAR(64) NOT NULL, + aggregate_type VARCHAR(64) NOT NULL, + aggregate_id VARCHAR(64) NOT NULL, + scope_type VARCHAR(32) NOT NULL, + scope_id VARCHAR(64) NOT NULL, + expected_epoch BIGINT NOT NULL, + aggregate_epoch_after BIGINT NOT NULL, + scope_epoch_after BIGINT NOT NULL, + owner_result_json TEXT NOT NULL, + owner_result_digest VARCHAR(71) NOT NULL, + applied_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_game_logic_version_rule_input_manifest + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + CONSTRAINT uq_game_logic_rule_manifest_request + UNIQUE (canonical_tenant_id, request_id), + CONSTRAINT uq_game_logic_rule_manifest_commit + UNIQUE (canonical_tenant_id, commit_id), + CONSTRAINT ck_game_logic_rule_manifest_identity CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND revision_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_game_logic_rule_manifest_source CHECK ( + game_design_version_row_id > 0 + AND source_game_row_id > 0 + AND length(game_design_version_tenant_key) BETWEEN 1 AND 36 + AND length(source_game_tenant_key) BETWEEN 1 AND 36 + AND game_design_version_tenant_key = source_game_tenant_key + AND source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') + ), + CONSTRAINT ck_game_logic_rule_manifest_binding CHECK ( + length(base_commit_id) BETWEEN 1 AND 256 + AND length(binding_json) > 0 + AND binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND length(source_proof_json) > 0 + AND length(owner_intent_json) > 0 + AND length(manifest_json) > 0 + ), + CONSTRAINT ck_game_logic_rule_manifest_digest CHECK ( + digest_schema_version = 1 + AND ability_schema_version = 1 + AND content_digest ~ '^[0-9a-f]{64}$' + AND ability_schema_digest ~ '^[0-9a-f]{64}$' + AND length(ability_schema_json) > 0 + ), + CONSTRAINT ck_game_logic_rule_manifest_epoch CHECK ( + aggregate_type = 'VERSION_RULE_MANIFEST' + AND aggregate_id = canonical_version_id::TEXT + AND scope_type = 'VERSION' + AND scope_id = canonical_version_id::TEXT + AND expected_epoch = 0 + AND aggregate_epoch_after = 1 + AND scope_epoch_after = 1 + ), + CONSTRAINT ck_game_logic_rule_manifest_result CHECK ( + length(owner_result_json) > 0 + AND owner_result_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION game_logic_reject_rule_manifest_rewrite() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Logic Version rule manifests are immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER game_logic_version_rule_input_manifest_immutable + BEFORE UPDATE OR DELETE ON game_logic_version_rule_input_manifest + FOR EACH ROW EXECUTE FUNCTION game_logic_reject_rule_manifest_rewrite(); +-- [jooq ignore stop] diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestPostgresIntegrationTest.java new file mode 100644 index 0000000000..c64c0889d0 --- /dev/null +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestPostgresIntegrationTest.java @@ -0,0 +1,470 @@ +package net.firedevops.firemud.gamelogic.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; +import net.firedevops.firemud.gamelogic.service.impl.GameLogicDraftDesignDigestServiceImpl; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.postgresql.ds.PGSimpleDataSource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL owner-storage proof. The full binding's other owner entries and the held authorization + * are explicitly synthetic storage-test fixtures; they do not authenticate a producer or enable + * publication. + */ +@Testcontainers(disabledWithoutDocker = true) +class GameLogicRuleInputManifestPostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static DSLContext dsl; + private static PlatformTransactionManager transactionManager; + private static GameLogicRuleInputManifestRepository repository; + + @BeforeAll + static void initializeMigratedOwnerStorage() { + PGSimpleDataSource dataSource = new PGSimpleDataSource(); + dataSource.setURL(POSTGRES.getJdbcUrl()); + dataSource.setUser(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + Flyway.configure().dataSource(dataSource).locations("classpath:db/migration").load().migrate(); + transactionManager = new DataSourceTransactionManager(dataSource); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + repository = new GameLogicRuleInputManifestRepository(dsl, transactionManager); + } + + @Test + void persistsExplicitEmptyManifestAndReadsBackExactBindingAndOwnerResult() { + DraftCommitBinding binding = + binding(randomTarget(), UUID.randomUUID(), UUID.randomUUID(), "root", "0"); + GameLogicRuleInputManifest expected = + GameLogicRuleInputManifest.fromExplicitEmptyIntent(binding); + + GameLogicRuleInputManifest actual = serviceWithSyntheticStorageAuthority(-1).apply(binding); + + assertThat(actual).isEqualTo(expected); + assertThat(actual.contentDigest()) + .isEqualTo("71b4da6a96f68a6f85d48731f5b4e448d05d21241ca75016ef0c9a0000c14f74"); + assertThat(actual.abilitySchemaDigest()) + .isEqualTo("a6c1b6d52654bce002ddb64de2d84853061aa87cb15407547038cc3d4e7cfbd4"); + assertThat(repository.read(expected.tenantId(), expected.versionId())).contains(expected); + assertThat(countFor(expected.tenantId(), expected.versionId())).isEqualTo(1L); + Record epochRecord = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT expected_epoch, aggregate_epoch_after, scope_epoch_after " + + "FROM game_logic_version_rule_input_manifest " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + expected.tenantId(), + expected.versionId()), + "inserted manifest epoch row must be readable"); + assertThat(epochRecord.get("aggregate_epoch_after", Long.class)).isEqualTo(1L); + } + + @Test + void exactRetryReturnsTheOriginalImmutableOwnerRow() { + DraftCommitBinding binding = + binding(randomTarget(), UUID.randomUUID(), UUID.randomUUID(), "root", "0"); + GameLogicRuleInputManifest first = serviceWithSyntheticStorageAuthority(-1).apply(binding); + GameLogicRuleInputManifest replay = serviceWithSyntheticStorageAuthority(-1).apply(binding); + + assertThat(replay).isEqualTo(first); + assertThat(countFor(first.tenantId(), first.versionId())).isEqualTo(1L); + } + + @Test + void changedBindingSourceOrRequestCannotReplaceTheOriginalVersionRow() { + TargetProof originalTarget = randomTarget(); + UUID requestId = UUID.randomUUID(); + DraftCommitBinding original = + binding(originalTarget, requestId, UUID.randomUUID(), "root", "0"); + GameLogicRuleInputManifest first = serviceWithSyntheticStorageAuthority(-1).apply(original); + + TargetProof substitutedSource = + new TargetProof( + originalTarget.canonicalTenantId(), + originalTarget.canonicalVersionId(), + originalTarget.gameDesignVersionRowId() + 1, + originalTarget.gameDesignVersionTenantKey(), + originalTarget.sourceGameRowId(), + originalTarget.sourceGameTenantKey(), + originalTarget.sourceProvenanceKind()); + DraftCommitBinding changed = + binding(substitutedSource, requestId, UUID.randomUUID(), "different-base", "0"); + + assertThatThrownBy(() -> serviceWithSyntheticStorageAuthority(-1).apply(changed)) + .isInstanceOf(GameLogicRuleInputManifestRepository.ManifestConflictException.class); + assertThat(repository.read(first.tenantId(), first.versionId())).contains(first); + assertThat(countFor(first.tenantId(), first.versionId())).isEqualTo(1L); + } + + @Test + void absentOwnerEvidenceRemainsAbsentAndProtectedDigestHandlerStaysDenied() { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + + assertThat(repository.read(tenantId, versionId)).isEmpty(); + assertThatThrownBy( + () -> + new GameLogicDraftDesignDigestServiceImpl() + .getDraftDesignDigest(tenantId.toString(), versionId.toString())) + .isInstanceOf(GameLogicDraftDesignDigestService.UnsupportedDigestScopeException.class); + assertThat(countFor(tenantId, versionId)).isZero(); + } + + @Test + void defaultApplyServiceDeniesWithoutAuthenticatedCurrentSourceAndAccountVerifier() { + DraftCommitBinding binding = + binding(randomTarget(), UUID.randomUUID(), UUID.randomUUID(), "root", "0"); + GameLogicEmptyRuleInputManifestService service = + new GameLogicEmptyRuleInputManifestService(repository); + + assertThatThrownBy(() -> service.apply(binding)) + .isInstanceOf(GameLogicEmptyRuleInputManifestService.ApplicationDeniedException.class); + assertThat( + repository.read( + binding.target().canonicalTenantId(), binding.target().canonicalVersionId())) + .isEmpty(); + } + + @Test + void rollbackAfterInsertLeavesNoManifestOrEpochAdvance() { + DraftCommitBinding binding = + binding(randomTarget(), UUID.randomUUID(), UUID.randomUUID(), "root", "0"); + UUID tenantId = binding.target().canonicalTenantId(); + UUID versionId = binding.target().canonicalVersionId(); + + assertThatThrownBy(() -> serviceWithSyntheticStorageAuthority(3).apply(binding)) + .isInstanceOf(SyntheticAuthorityLostException.class); + + assertThat(repository.read(tenantId, versionId)).isEmpty(); + assertThat(countFor(tenantId, versionId)).isZero(); + } + + @Test + void concurrentFirstClaimsAtEpochZeroRetainOneOriginalResult() throws Exception { + DraftCommitBinding binding = + binding(randomTarget(), UUID.randomUUID(), UUID.randomUUID(), "root", "0"); + GameLogicRuleInputManifest expected = + GameLogicRuleInputManifest.fromExplicitEmptyIntent(binding); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent claim start timed out"); + } + return serviceWithSyntheticStorageAuthority(-1).apply(binding); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent claim start timed out"); + } + return serviceWithSyntheticStorageAuthority(-1).apply(binding); + }); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat(first.get(15, TimeUnit.SECONDS)).isEqualTo(expected); + assertThat(second.get(15, TimeUnit.SECONDS)).isEqualTo(expected); + } finally { + executor.shutdownNow(); + } + assertThat(countFor(expected.tenantId(), expected.versionId())).isEqualTo(1L); + } + + @Test + void nonEmptyIntentExtraGameLogicUnitsAndNonzeroEpochAreRejected() { + TargetProof target = randomTarget(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + + DraftCommitBinding nonEmpty = + binding( + target, + requestId, + commitId, + "root", + "0", + GameLogicRuleInputManifest.emptyIntentJson() + .replace("\"ruleInputs\":[]", "\"ruleInputs\":[{}]"), + 1, + 1); + assertThatThrownBy(() -> serviceWithSyntheticStorageAuthority(-1).apply(nonEmpty)) + .isInstanceOf(GameLogicRuleInputManifest.InvalidRuleManifestIntentException.class); + + DraftCommitBinding extraOwnerUnit = + binding(target, UUID.randomUUID(), UUID.randomUUID(), "root", "0", 1, 2); + assertThatThrownBy(() -> serviceWithSyntheticStorageAuthority(-1).apply(extraOwnerUnit)) + .isInstanceOf(GameLogicRuleInputManifest.InvalidRuleManifestIntentException.class); + + DraftCommitBinding extraOwnerRevision = + binding(target, UUID.randomUUID(), UUID.randomUUID(), "root", "0", 2, 1); + assertThatThrownBy(() -> serviceWithSyntheticStorageAuthority(-1).apply(extraOwnerRevision)) + .isInstanceOf(GameLogicRuleInputManifest.InvalidRuleManifestIntentException.class); + + DraftCommitBinding staleEpoch = + binding(target, UUID.randomUUID(), UUID.randomUUID(), "root", "1"); + assertThatThrownBy(() -> serviceWithSyntheticStorageAuthority(-1).apply(staleEpoch)) + .isInstanceOf(GameLogicRuleInputManifest.InvalidRuleManifestIntentException.class); + assertThat(repository.read(target.canonicalTenantId(), target.canonicalVersionId())).isEmpty(); + } + + @Test + void fullDraftBindingCannotOmitTheGameLogicOwner() { + TargetProof target = randomTarget(); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + int order = 0; + for (Owner owner : Owner.values()) { + if (owner != Owner.GAME_LOGIC) { + revisions.add( + new RevisionPayload( + Integer.toString(order++), + UUID.randomUUID(), + owner, + "{\"syntheticStorageTestParticipant\":\"" + owner.name() + "\"}")); + units.add( + new AffectedUnit( + owner, + "SYNTHETIC_TEST_OWNER", + target.canonicalVersionId().toString(), + "VERSION", + target.canonicalVersionId().toString(), + "0")); + } + } + + DraftCommitBinding omittedGameLogic = + DraftCommitBinding.create( + target, UUID.randomUUID(), UUID.randomUUID(), "root", revisions, units); + assertThatThrownBy(() -> serviceWithSyntheticStorageAuthority(-1).apply(omittedGameLogic)) + .isInstanceOf(GameLogicRuleInputManifest.InvalidRuleManifestIntentException.class); + + List gameLogicRevisionWithoutUnit = new ArrayList<>(revisions); + gameLogicRevisionWithoutUnit.add( + new RevisionPayload( + Integer.toString(order), + UUID.randomUUID(), + Owner.GAME_LOGIC, + GameLogicRuleInputManifest.emptyIntentJson())); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "root", + gameLogicRevisionWithoutUnit, + units)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Required owner set must exactly match"); + + List gameLogicUnitWithoutRevision = new ArrayList<>(units); + gameLogicUnitWithoutRevision.add( + new AffectedUnit( + Owner.GAME_LOGIC, + "VERSION_RULE_MANIFEST", + target.canonicalVersionId().toString(), + "VERSION", + target.canonicalVersionId().toString(), + "0")); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "root", + revisions, + gameLogicUnitWithoutRevision)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Required owner set must exactly match"); + } + + @Test + void databaseRejectsMutationOfAnAppliedManifest() { + DraftCommitBinding binding = + binding(randomTarget(), UUID.randomUUID(), UUID.randomUUID(), "root", "0"); + GameLogicRuleInputManifest applied = serviceWithSyntheticStorageAuthority(-1).apply(binding); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_logic_version_rule_input_manifest SET owner_result_json = '{}' " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + applied.tenantId(), + applied.versionId())) + .hasMessageContaining("Game Logic Version rule manifests are immutable"); + } + + private static GameLogicEmptyRuleInputManifestService serviceWithSyntheticStorageAuthority( + int failOnRequireHeldCall) { + return new GameLogicEmptyRuleInputManifestService( + repository, ignoredBinding -> new SyntheticTestAuthority(failOnRequireHeldCall)); + } + + private static DraftCommitBinding binding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + String expectedEpoch) { + return binding( + target, + requestId, + commitId, + baseCommitId, + expectedEpoch, + GameLogicRuleInputManifest.emptyIntentJson(), + 1, + 1); + } + + private static DraftCommitBinding binding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + String expectedEpoch, + int gameLogicRevisionCount, + int gameLogicUnitCount) { + return binding( + target, + requestId, + commitId, + baseCommitId, + expectedEpoch, + GameLogicRuleInputManifest.emptyIntentJson(), + gameLogicRevisionCount, + gameLogicUnitCount); + } + + private static DraftCommitBinding binding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + String expectedEpoch, + String gameLogicIntent, + int gameLogicRevisionCount, + int gameLogicUnitCount) { + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + int order = 0; + for (Owner owner : Owner.values()) { + int count = owner == Owner.GAME_LOGIC ? gameLogicRevisionCount : 1; + for (int index = 0; index < count; index++) { + String payload = + owner == Owner.GAME_LOGIC + ? gameLogicIntent + : "{\"syntheticStorageTestParticipant\":\"" + owner.name() + "\"}"; + revisions.add( + new RevisionPayload(Integer.toString(order++), UUID.randomUUID(), owner, payload)); + } + + count = owner == Owner.GAME_LOGIC ? gameLogicUnitCount : 1; + for (int index = 0; index < count; index++) { + String scopeId = + owner == Owner.GAME_LOGIC && index > 0 + ? target.canonicalVersionId() + "-extra" + : target.canonicalVersionId().toString(); + units.add( + new AffectedUnit( + owner, + owner == Owner.GAME_LOGIC ? "VERSION_RULE_MANIFEST" : "SYNTHETIC_TEST_OWNER", + target.canonicalVersionId().toString(), + "VERSION", + scopeId, + owner == Owner.GAME_LOGIC ? expectedEpoch : "0")); + } + } + return DraftCommitBinding.create(target, requestId, commitId, baseCommitId, revisions, units); + } + + private static TargetProof randomTarget() { + String privateTenantKey = UUID.randomUUID().toString(); + return new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 101L, + privateTenantKey, + 202L, + privateTenantKey, + "NEW_GAME_ROW"); + } + + private static long countFor(UUID tenantId, UUID versionId) { + Record countRecord = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS row_count FROM game_logic_version_rule_input_manifest " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + tenantId, + versionId), + "count query must return one row"); + return Objects.requireNonNull( + countRecord.get("row_count", Long.class), "count query must return a value"); + } + + private static final class SyntheticTestAuthority + implements GameLogicEmptyRuleInputManifestService.HeldCommitAuthority { + private final int failOnRequireHeldCall; + private final AtomicInteger requireHeldCalls = new AtomicInteger(); + + private SyntheticTestAuthority(int failOnRequireHeldCall) { + this.failOnRequireHeldCall = failOnRequireHeldCall; + } + + @Override + public void requireHeld() { + if (requireHeldCalls.incrementAndGet() == failOnRequireHeldCall) { + throw new SyntheticAuthorityLostException(); + } + } + + @Override + public void close() {} + } + + private static final class SyntheticAuthorityLostException extends IllegalStateException { + private SyntheticAuthorityLostException() { + super("Synthetic storage-test authority was withdrawn"); + } + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestFixtures.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestFixtures.java new file mode 100644 index 0000000000..fcb69d7946 --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestFixtures.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.gamelogic.authoring; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; + +/** Test-only builder for complete five-owner bindings with explicitly synthetic peer payloads. */ +final class GameLogicRuleInputManifestFixtures { + private GameLogicRuleInputManifestFixtures() {} + + static DraftCommitBinding fullBinding() { + TargetProof target = target(); + return fullBinding( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit", + GameLogicRuleInputManifest.emptyIntentJson(), + 1, + List.of(gameLogicUnit(target))); + } + + static DraftCommitBinding fullBinding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + String gameLogicPayload, + int gameLogicRevisionCount, + List gameLogicUnits) { + List revisions = new ArrayList<>(); + List affectedUnits = new ArrayList<>(); + int revisionOrder = 0; + String versionId = target.canonicalVersionId().toString(); + for (Owner owner : Owner.values()) { + int ownerRevisionCount = owner == Owner.GAME_LOGIC ? gameLogicRevisionCount : 1; + for (int index = 0; index < ownerRevisionCount; index++) { + String payload = + owner == Owner.GAME_LOGIC + ? gameLogicPayload + : "{\"syntheticStorageTestParticipant\":\"" + owner.name() + "\"}"; + revisions.add( + new RevisionPayload( + Integer.toString(revisionOrder++), UUID.randomUUID(), owner, payload)); + } + if (owner != Owner.GAME_LOGIC) { + affectedUnits.add( + new AffectedUnit(owner, "SYNTHETIC_TEST_OWNER", versionId, "VERSION", versionId, "0")); + } + } + affectedUnits.addAll(gameLogicUnits); + return DraftCommitBinding.create( + target, requestId, commitId, baseCommitId, revisions, affectedUnits); + } + + static TargetProof target() { + String privateTenantKey = UUID.randomUUID().toString(); + return new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 101L, + privateTenantKey, + 202L, + privateTenantKey, + "NEW_GAME_ROW"); + } + + static TargetProof targetWithSameCanonicalVersionAndDifferentSource(TargetProof original) { + String privateTenantKey = UUID.randomUUID().toString(); + return new TargetProof( + original.canonicalTenantId(), + original.canonicalVersionId(), + original.gameDesignVersionRowId() + 1L, + privateTenantKey, + original.sourceGameRowId() + 1L, + privateTenantKey, + "RETAINED_GAME_V30"); + } + + static AffectedUnit gameLogicUnit(TargetProof target) { + String versionId = target.canonicalVersionId().toString(); + return new AffectedUnit( + Owner.GAME_LOGIC, + GameLogicRuleInputManifest.AGGREGATE_TYPE, + versionId, + GameLogicRuleInputManifest.SCOPE_TYPE, + versionId, + "0"); + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestTest.java new file mode 100644 index 0000000000..5e3754a12b --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestTest.java @@ -0,0 +1,392 @@ +package net.firedevops.firemud.gamelogic.authoring; + +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.verifyNoInteractions; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; +import net.firedevops.firemud.gamelogic.service.impl.GameLogicDraftDesignDigestServiceImpl; +import org.junit.jupiter.api.Test; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameLogicRuleInputManifestTest { + private static final String EMPTY_INTENT_JSON = + "{\"intentKind\":\"EMPTY_RULE_INPUT_MANIFEST/v1\"," + + "\"manifest\":{\"abilitySchemas\":[],\"ruleInputs\":[],\"schemaVersion\":1}}"; + private static final String CONTENT_DIGEST_PREIMAGE = + "{\"abilitySchemas\":[],\"digestSchemaVersion\":1,\"ruleInputs\":[]}"; + private static final String CONTENT_DIGEST_VECTOR = + "71b4da6a96f68a6f85d48731f5b4e448d05d21241ca75016ef0c9a0000c14f74"; + private static final String ABILITY_SCHEMA_DIGEST_PREIMAGE = + "{\"abilitySchemaDigestDomain\":\"firemud.game-logic.ability-schema/v1\"," + + "\"abilitySchemaVersion\":1,\"abilitySchemas\":[]}"; + private static final String ABILITY_SCHEMA_DIGEST_VECTOR = + "a6c1b6d52654bce002ddb64de2d84853061aa87cb15407547038cc3d4e7cfbd4"; + + @Test + void canonicalEmptyIntentAndBothDigestPreimagesMatchTheirGoldenVectors() { + GameLogicRuleInputManifest manifest = + GameLogicRuleInputManifest.fromExplicitEmptyIntent( + GameLogicRuleInputManifestFixtures.fullBinding()); + + assertThat(manifest.ownerIntentJson()).isEqualTo(EMPTY_INTENT_JSON); + assertThat(manifest.manifestJson()) + .isEqualTo("{\"abilitySchemas\":[],\"ruleInputs\":[],\"schemaVersion\":1}"); + assertThat(sha256Hex(CONTENT_DIGEST_PREIMAGE)).isEqualTo(CONTENT_DIGEST_VECTOR); + assertThat(manifest.contentDigest()).isEqualTo(CONTENT_DIGEST_VECTOR); + assertThat(manifest.abilitySchemaJson()).isEqualTo(ABILITY_SCHEMA_DIGEST_PREIMAGE); + assertThat(sha256Hex(ABILITY_SCHEMA_DIGEST_PREIMAGE)).isEqualTo(ABILITY_SCHEMA_DIGEST_VECTOR); + assertThat(manifest.abilitySchemaDigest()).isEqualTo(ABILITY_SCHEMA_DIGEST_VECTOR); + assertThat(manifest.digestSchemaVersion()).isEqualTo(1); + assertThat(manifest.abilitySchemaVersion()).isEqualTo(1); + } + + @Test + void retainsTheOriginalCompleteFiveOwnerBindingAndItsExactGameLogicRevision() { + DraftCommitBinding binding = GameLogicRuleInputManifestFixtures.fullBinding(); + GameLogicRuleInputManifest manifest = + GameLogicRuleInputManifest.fromExplicitEmptyIntent(binding); + + assertThat(binding.requiredOwners()).containsExactly(Owner.values()); + assertThat(manifest.binding()).isSameAs(binding); + assertThat(manifest.binding().canonicalJson()).isEqualTo(binding.canonicalJson()); + assertThat(manifest.binding().digest()).isEqualTo(binding.digest()); + assertThat(manifest.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); + assertThat(manifest.binding().revisions()).containsExactlyElementsOf(binding.revisions()); + assertThat(manifest.binding().affectedUnits()) + .containsExactlyElementsOf(binding.affectedUnits()); + + var gameLogicRevision = + binding.revisions().stream() + .filter(revision -> revision.owner() == Owner.GAME_LOGIC) + .findFirst() + .orElseThrow(); + assertThat(manifest.revisionId()).isEqualTo(gameLogicRevision.revisionId()); + assertThat(gameLogicRevision.payload()).isEqualTo(EMPTY_INTENT_JSON); + assertThat(manifest.tenantId()).isEqualTo(binding.target().canonicalTenantId()); + assertThat(manifest.versionId()).isEqualTo(binding.target().canonicalVersionId()); + assertThat(manifest.sourceProofJson()).isEqualTo(sourceProofJson(binding.target())); + assertThat(manifest.requestId()).isEqualTo(binding.requestId()); + assertThat(manifest.commitId()).isEqualTo(binding.commitId()); + assertThat(manifest.baseCommitId()).isEqualTo(binding.baseCommitId()); + } + + @Test + void semanticDigestsStayStableWhenSourceAndCommitProvenanceChanges() { + TargetProof originalTarget = GameLogicRuleInputManifestFixtures.target(); + DraftCommitBinding originalBinding = + GameLogicRuleInputManifestFixtures.fullBinding( + originalTarget, + UUID.randomUUID(), + UUID.randomUUID(), + "base-original", + EMPTY_INTENT_JSON, + 1, + List.of(GameLogicRuleInputManifestFixtures.gameLogicUnit(originalTarget))); + TargetProof changedTarget = + GameLogicRuleInputManifestFixtures.targetWithSameCanonicalVersionAndDifferentSource( + originalTarget); + DraftCommitBinding changedBinding = + GameLogicRuleInputManifestFixtures.fullBinding( + changedTarget, + UUID.randomUUID(), + UUID.randomUUID(), + "base-changed", + EMPTY_INTENT_JSON, + 1, + List.of(GameLogicRuleInputManifestFixtures.gameLogicUnit(changedTarget))); + + GameLogicRuleInputManifest original = + GameLogicRuleInputManifest.fromExplicitEmptyIntent(originalBinding); + GameLogicRuleInputManifest changed = + GameLogicRuleInputManifest.fromExplicitEmptyIntent(changedBinding); + + assertThat(changed.contentDigest()).isEqualTo(original.contentDigest()); + assertThat(changed.abilitySchemaDigest()).isEqualTo(original.abilitySchemaDigest()); + assertThat(changed.sourceProofJson()).isNotEqualTo(original.sourceProofJson()); + assertThat(changed.binding().canonicalJson()).isNotEqualTo(original.binding().canonicalJson()); + assertThat(changed.binding().digest()).isNotEqualTo(original.binding().digest()); + assertThat(changed.requestId()).isNotEqualTo(original.requestId()); + assertThat(changed.commitId()).isNotEqualTo(original.commitId()); + assertThat(changed.baseCommitId()).isNotEqualTo(original.baseCommitId()); + assertThat(changed).isNotEqualTo(original); + // The migrated repository's same-Version changed-binding conflict is covered by its PostgreSQL + // test; equal semantic hashes do not relax that full-provenance storage comparison. + } + + @Test + void rejectsNonemptyOrUnknownRevisionIntent() { + TargetProof target = GameLogicRuleInputManifestFixtures.target(); + List unsupportedPayloads = + List.of( + EMPTY_INTENT_JSON.replace("\"ruleInputs\":[]", "\"ruleInputs\":[{}]"), + EMPTY_INTENT_JSON.replace("\"abilitySchemas\":[]", "\"abilitySchemas\":[{}]"), + "{\"intentKind\":\"EMPTY_RULE_INPUT_MANIFEST/v2\"," + + "\"manifest\":{\"abilitySchemas\":[],\"ruleInputs\":[],\"schemaVersion\":1}}", + "{\"intentKind\":\"EMPTY_RULE_INPUT_MANIFEST/v1\"," + + "\"manifest\":{\"abilitySchemas\":[],\"ruleInputs\":[]}}"); + + for (String payload : unsupportedPayloads) { + DraftCommitBinding binding = + fullBinding( + target, + payload, + 1, + List.of(GameLogicRuleInputManifestFixtures.gameLogicUnit(target))); + assertInvalid(binding); + } + } + + @Test + void rejectsExtraOrMissingGameLogicRevisionDeclarations() { + TargetProof target = GameLogicRuleInputManifestFixtures.target(); + AffectedUnit gameLogicUnit = GameLogicRuleInputManifestFixtures.gameLogicUnit(target); + + assertInvalid(fullBinding(target, EMPTY_INTENT_JSON, 2, List.of(gameLogicUnit))); + assertInvalid(fullBinding(target, EMPTY_INTENT_JSON, 0, List.of())); + + assertThatThrownBy(() -> fullBinding(target, EMPTY_INTENT_JSON, 1, List.of())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Required owner set must exactly match"); + assertThatThrownBy(() -> fullBinding(target, EMPTY_INTENT_JSON, 0, List.of(gameLogicUnit))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Required owner set must exactly match"); + } + + @Test + void rejectsExtraOrWrongTypedGameLogicAffectedUnits() { + TargetProof target = GameLogicRuleInputManifestFixtures.target(); + String versionId = target.canonicalVersionId().toString(); + AffectedUnit correct = GameLogicRuleInputManifestFixtures.gameLogicUnit(target); + List extra = + List.of( + correct, + new AffectedUnit( + Owner.GAME_LOGIC, + GameLogicRuleInputManifest.AGGREGATE_TYPE, + versionId, + GameLogicRuleInputManifest.SCOPE_TYPE, + versionId + "-extra", + "0")); + assertInvalid(fullBinding(target, EMPTY_INTENT_JSON, 1, extra)); + + assertInvalid( + fullBinding( + target, + EMPTY_INTENT_JSON, + 1, + List.of(unit(target, "OTHER_AGGREGATE", versionId, "VERSION", versionId, "0")))); + assertInvalid( + fullBinding( + target, + EMPTY_INTENT_JSON, + 1, + List.of( + unit( + target, + GameLogicRuleInputManifest.AGGREGATE_TYPE, + "different-version", + "VERSION", + versionId, + "0")))); + assertInvalid( + fullBinding( + target, + EMPTY_INTENT_JSON, + 1, + List.of( + unit( + target, + GameLogicRuleInputManifest.AGGREGATE_TYPE, + versionId, + "TENANT", + versionId, + "0")))); + assertInvalid( + fullBinding( + target, + EMPTY_INTENT_JSON, + 1, + List.of( + unit( + target, + GameLogicRuleInputManifest.AGGREGATE_TYPE, + versionId, + "VERSION", + "different-version", + "0")))); + assertInvalid( + fullBinding( + target, + EMPTY_INTENT_JSON, + 1, + List.of( + unit( + target, + GameLogicRuleInputManifest.AGGREGATE_TYPE, + versionId, + "VERSION", + versionId, + "1")))); + + AffectedUnit wrongOwner = + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + GameLogicRuleInputManifest.AGGREGATE_TYPE, + versionId, + GameLogicRuleInputManifest.SCOPE_TYPE, + versionId, + "0"); + assertThatThrownBy(() -> fullBinding(target, EMPTY_INTENT_JSON, 1, List.of(wrongOwner))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Required owner set must exactly match"); + } + + @Test + void rejectsNonzeroInitialEpoch() { + TargetProof target = GameLogicRuleInputManifestFixtures.target(); + AffectedUnit stale = + new AffectedUnit( + Owner.GAME_LOGIC, + GameLogicRuleInputManifest.AGGREGATE_TYPE, + target.canonicalVersionId().toString(), + GameLogicRuleInputManifest.SCOPE_TYPE, + target.canonicalVersionId().toString(), + "2"); + + assertInvalid(fullBinding(target, EMPTY_INTENT_JSON, 1, List.of(stale))); + } + + @Test + void defaultServiceDeniesBeforeRepositoryMutation() { + GameLogicRuleInputManifestRepository repository = + mock(GameLogicRuleInputManifestRepository.class); + GameLogicEmptyRuleInputManifestService service = + new GameLogicEmptyRuleInputManifestService(repository); + DraftCommitBinding binding = GameLogicRuleInputManifestFixtures.fullBinding(); + + assertThatThrownBy(() -> service.apply(binding)) + .isInstanceOf(GameLogicEmptyRuleInputManifestService.ApplicationDeniedException.class); + verifyNoInteractions(repository); + } + + @Test + void ambientOwnerTransactionIsRejectedBeforeVerifierOrRepository() { + GameLogicRuleInputManifestRepository repository = + mock(GameLogicRuleInputManifestRepository.class); + GameLogicEmptyRuleInputManifestService service = + new GameLogicEmptyRuleInputManifestService( + repository, + ignored -> { + throw new AssertionError("Verifier must not run inside an ambient transaction"); + }); + DraftCommitBinding binding = GameLogicRuleInputManifestFixtures.fullBinding(); + boolean wasTransactionActive = TransactionSynchronizationManager.isActualTransactionActive(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> service.apply(binding)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(wasTransactionActive); + } + verifyNoInteractions(repository); + } + + @Test + void ownerStorageAndApplyRemainUnregisteredAndCannotEnablePublicDigest() { + assertThat(GameLogicEmptyRuleInputManifestService.class.isAnnotationPresent(Component.class)) + .isFalse(); + assertThat(GameLogicEmptyRuleInputManifestService.class.isAnnotationPresent(Service.class)) + .isFalse(); + assertThat(GameLogicRuleInputManifestRepository.class.isAnnotationPresent(Component.class)) + .isFalse(); + assertThat(GameLogicRuleInputManifestRepository.class.isAnnotationPresent(Repository.class)) + .isFalse(); + + DraftCommitBinding binding = GameLogicRuleInputManifestFixtures.fullBinding(); + GameLogicRuleInputManifest syntheticStorageResult = + GameLogicRuleInputManifest.fromExplicitEmptyIntent(binding); + assertThat(syntheticStorageResult.ownerResultJson()).contains("\"status\":\"APPLIED\""); + assertThatThrownBy( + () -> + new GameLogicDraftDesignDigestServiceImpl() + .getDraftDesignDigest( + binding.target().canonicalTenantId().toString(), + binding.target().canonicalVersionId().toString())) + .isInstanceOf(GameLogicDraftDesignDigestService.UnsupportedDigestScopeException.class); + } + + private static DraftCommitBinding fullBinding( + TargetProof target, + String gameLogicPayload, + int gameLogicRevisionCount, + List units) { + return GameLogicRuleInputManifestFixtures.fullBinding( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit", + gameLogicPayload, + gameLogicRevisionCount, + units); + } + + private static AffectedUnit unit( + TargetProof target, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + return new AffectedUnit( + Owner.GAME_LOGIC, aggregateType, aggregateId, scopeType, scopeId, expectedEpoch); + } + + private static void assertInvalid(DraftCommitBinding binding) { + assertThatThrownBy(() -> GameLogicRuleInputManifest.fromExplicitEmptyIntent(binding)) + .isInstanceOf(GameLogicRuleInputManifest.InvalidRuleManifestIntentException.class); + } + + private static String sourceProofJson(TargetProof target) { + return "{\"canonicalTenantId\":\"" + + target.canonicalTenantId() + + "\",\"canonicalVersionId\":\"" + + target.canonicalVersionId() + + "\",\"gameDesignVersionRowId\":\"" + + target.gameDesignVersionRowId() + + "\",\"gameDesignVersionTenantKey\":\"" + + target.gameDesignVersionTenantKey() + + "\",\"sourceGameRowId\":\"" + + target.sourceGameRowId() + + "\",\"sourceGameTenantKey\":\"" + + target.sourceGameTenantKey() + + "\",\"sourceProvenanceKind\":\"" + + target.sourceProvenanceKind() + + "\"}"; + } + + private static String sha256Hex(String value) { + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} From da34cc80bad22e60083a43c871d21e853b44cdf4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 14:19:48 +1300 Subject: [PATCH 2/3] Define closed Account security evidence and exact control-ui envelopes --- .../account-service/api-contracts.md | 10 +- .../system-architecture-authentication.md | 8 + .../player-access-and-session.md | 4 + ...ootstrap-account-response-envelope-ring.py | 35 +- ...erialize-account-response-envelope-ring.py | 2 +- ...est_account_response_envelope_bootstrap.py | 67 +- ..._account_response_envelope_materializer.py | 11 +- ...countControlUiResponseEnvelopeBinding.java | 178 +++++ .../security/AccountEnvelopeCrypto.java | 116 +++- .../security/AccountEnvelopePurpose.java | 3 +- .../AccountAuthoritySourceEventReadback.java | 59 +- .../service/AccountGenerationProjection.java | 64 +- ...ntControlUiResponseEnvelopeCryptoTest.java | 636 ++++++++++++++++++ ...countAuthoritySourceEventReadbackTest.java | 186 +++++ .../AccountGenerationProjectionTest.java | 133 +++- ...sAccountGenerationProjectionStoreTest.java | 88 +++ ...untSecurityStateAuthorityEventV1Codec.java | 391 +++++++++++ ...ecurityStateAuthorityEventV1CodecTest.java | 327 +++++++++ 18 files changed, 2253 insertions(+), 65 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountControlUiResponseEnvelopeBinding.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountControlUiResponseEnvelopeCryptoTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3bc93fe82c..40c5e68fe9 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -220,10 +220,18 @@ The stored receipt and event must be read back exactly before success, including ### Account-Owned Account Source Readback -Account's owner-local source readback selects one exact canonical Account UUID, locks its persisted identity/credential row and Account source generation/issuance-fence rows in producer order, and holds those locks through the complete current and selected historical read. It does not enroll missing authority. The current snapshot binds the exact Account source scope, positive generation/source version, actual local issuance fence, derived stream and latest checkpoint/event. Sequence zero requires the original positive 1/1 source baseline and proved absence of committed stream history; event identity, digest and payload are absent at zero. A positive checkpoint must match the exact latest closed [password-reset](../../system-architecture-authentication.md#account-password-reset-source-event) or [logout-all](../../system-architecture-authentication.md#account-logout-all-source-event) event and its immutable operation receipt. Unsupported event types or contradictory source, receipt or checkpoint content fail closed. +Account's owner-local source readback selects one exact canonical Account UUID, locks its persisted identity/credential row and Account source generation/issuance-fence rows in producer order, and holds those locks through the complete current and selected historical read. It does not enroll missing authority. The current snapshot binds the exact Account source scope, positive generation/source version, actual local issuance fence, derived stream and latest checkpoint/event. Sequence zero requires the original positive 1/1 source baseline and proved absence of committed stream history; event identity, digest and payload are absent at zero. A positive checkpoint must match the exact latest closed [password-reset](../../system-architecture-authentication.md#account-password-reset-source-event), [logout-all](../../system-architecture-authentication.md#account-logout-all-source-event), or [security-state](../../system-architecture-authentication.md#account-security-state-source-event) event and its immutable operation receipt. Security-state producer, receipt storage and current/historical reader integration remain unimplemented prerequisites; declaring its schema does not enable that path. Unsupported event types or contradictory source, receipt or checkpoint content fail closed. A historical selector is a positive outbox sequence in that exact Account stream. Readback returns the unchanged requested event together with the current source snapshot, validates its complete canonical payload/digest and immutable receipt binding, and rejects missing, cross-scope or ahead-of-current evidence. A later password reset does not erase the prior reset source event or make its old verifier current authority: historical source validation proves the original receipt, while password-reset operation recovery still requires its original current-password postcondition and deadline. Source readback cannot recover a superseded password-reset result, return credentials, supply recipient authorization, or substitute for the complete Account evidence bundle. The source snapshot carries no password verifier or private operation receipt. Authentication, transport, event delivery, projection consumption and live activation are separate proof obligations; an owner-local reader alone enables none of them. +### Account-Owned Security-State Operation and Readback + +The closed source payload and digest are owned by [Authentication's Account security-state source event](../../system-architecture-authentication.md#account-security-state-source-event). This is an Account-owned operation contract, not a new public mutation route or a permission grant. Its producer remains unimplemented at this boundary. Account claims a stable original operation UUID before changing state and retains the exact authenticated caller/workload binding, canonical Account UUID and independently verified numeric association, request-digest version and digest, expected source state, and complete credential-free before/after images in immutable operation evidence. A retry must reuse that original identity; a newly generated repository-save identity cannot recover an ambiguous earlier commit. Global roles must be read from the actual Account-owned grant/source under [ADR 0185](../../decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md), not inferred from `accounts.role`. The existing fresh-empty source reader proves only qualifying fresh empty authority; unsupported retained or mutated global-role sources remain denied until their owning source readback exists. + +Under the existing Account owner transaction and lock order, the producer compares the exact before/after images and requires the event's changed-family set to equal every supported changed family, with no omissions, additions or duplicates. One operation changing several supported families still advances the Account generation/source version and applicable local issuance fence once and appends one source event/checkpoint. It commits the row/source changes, immutable request/result receipt and outbox evidence together; a failed claim, source comparison, counter overflow, append or readback rolls them all back. A password change must use the unchanged password-reset owner operation, event and receipt; generic password-hash comparison does not authorize or synthesize it. Unsupported mixed-password mutations are denied until that real owner operation is composed. Logout-all retains its separate operation and exact lifecycle retry semantics. + +The immutable committed receipt binds the original operation/caller/request digest, exact Account association, credential-free before/after images and detected family set to the committed event ID, complete canonical event bytes/digest, exact stream/sequence, generation/source version and actual private local fence result. SQL uniqueness and immutability protect the original operation identity and stream checkpoint. Before success, owner readback independently compares the complete claimed request/result and receipt, request-indexed and sequence-indexed outbox event, committed source/checkpoint and current owner state. Exact retry first reads and verifies the original receipt/event without another state update, generation/fence advance or append; changed caller, target, digest, state or family bindings conflict. A later owner advance preserves the original committed result and bytes. Historical validation proves the unchanged receipt/event and rejects history ahead of the current source; it does not demand that historical post-state remain current, return credentials, authorize the current caller or replace the separate complete Account evidence bundle. Current source readback must bind the latest supported event and receipt to the current same-snapshot owner state. Missing, contradictory or unsupported evidence fails closed. Codec vectors alone establish neither operation persistence nor producer, projection, authenticated handoff or runtime activation proof. + ### Account-Owned Issuer Authority Advance and Readback An issuer authority operation binds the exact configured Account `issuerId`, a caller-retained canonical non-nil UUID `requestId`, and the expected positive persisted generation and source version. Its operation identity is the exact `{issuerId, requestId}` pair; requests for another issuer are rejected, not redirected or normalized. One successful operation compare-and-advances both counters by one and commits the [issuer generation source event](../../system-architecture-authentication.md#issuer-generation-source-event) and outbox checkpoint atomically. Its stable event ID is `account-issuer-authority-event-v1:`; its complete immutable event binds the resulting counters, exact issuer scope and sequence. There is no individual Account selector or issuance fence. Missing, contradictory, stale or overflowed source evidence fails closed before reporting success; this operation does not enroll missing authority or rotate JWT keys. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index b6a5b177c9..449f27760f 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -32,6 +32,14 @@ The digest preimage is the entire declared event object excluding **only** `even The event digest binds the entire declared object excluding only `eventDigest`, using RFC 8785 canonical JSON UTF-8 and `sha256:` followed by 64 lowercase hexadecimal SHA-256 digits. Receivers reject duplicate/unknown/missing fields, noncanonical identities or counters, mismatched cutoff evidence and changed fields with the original digest. This event does not replace the password-reset schema or authorize another mutation. Account's immutable logout operation separately binds the original request digest, operation kind and exact presented-token identity for [ADR 0036's lifecycle-only retry](./decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md#lifecycle-only-logout-retry-exception); that evidence is not copied into a scope-wide source event. Account commits the authorized account-generation/source-version and local issuance-fence advance, exact outbox checkpoint, event and immutable lifecycle result atomically. The source event alone cannot authorize a recipient; the separate same-snapshot Account readback remains necessary. [Account API Contracts](./microservices/account-service/api-contracts.md) owns initial authorization and exact lifecycle-result recovery. Shared producer/consumer vectors cover every changed field and counters beyond signed 64-bit range; SQL source counters still fail closed on overflow. +#### Account Security-State Source Event + +`account-auth-account-security-state-event/v1` is the closed source schema for one Account-owned non-password security-state mutation. Its required preimage fields are exactly `schemaVersion` (that discriminator), `eventType` (exactly `ACCOUNT_SECURITY_STATE_CHANGED`), `eventId`, `requestId`, `accountId`, `sourceScope`, `outboxStreamKey`, `outboxSequence`, `accountAuthorityGeneration`, `sourceVersion`, `accountSecurityCutoff`, `mutationKinds`, and `accountState`; the wire adds only `eventDigest`. `requestId` is the canonical lowercase non-nil UUID of the original immutable Account operation, `eventId` is exactly `account-security-state-event-v1:`, and `accountId` is a canonical lowercase non-nil Account UUID. `sourceScope` is exactly `account/` and `outboxStreamKey` is exactly `account:auth-authority:v1:`. All counters are canonical positive decimal strings matching `[1-9][0-9]*`, parsed with arbitrary precision. `accountSecurityCutoff` has exactly `accountAuthorityGeneration`, `outboxStreamKey`, and `outboxSequence`, equal to the outer event fields. + +`mutationKinds` is a sorted, unique, nonempty array containing only `EMAIL_LOGIN_ELIGIBILITY_CHANGED`, `GLOBAL_ROLE_CHANGED`, `LIFECYCLE_STATE_CHANGED`, and `LOGIN_AUTH_MODES_CHANGED`. `accountState` has exactly `emailVerified` (a boolean), `loginAuthModes` (a sorted, unique, nonempty array drawn only from `EMAIL_OTP` and `PASSWORD`), `globalRoles` (a sorted, unique array drawn only from `billingAdmin`, `platformAdmin`, and `support`, including the exact empty array for proved no-global-role authority), and `lifecycleState` (exactly `ACTIVE`, `SECURITY_LOCKED`, `DEACTIVATED_PENDING_DELETE`, or `DELETED`). Global-role state comes from the Account-owned grant/source under [ADR 0185](./decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md); the legacy `accounts.role` scalar never supplies or establishes it. Every property is required; nulls, optional fields, recipient tuples, issuance fences, credentials and password verifiers are absent. The only arrays are the three declared arrays above; other array representations are invalid. + +The digest binds the entire declared preimage excluding only `eventDigest`, serialized as RFC 8785 canonical JSON UTF-8. `eventDigest` is `sha256:` followed by 64 lowercase hexadecimal SHA-256 digits. Reject duplicate, unknown or missing fields, unsupported or incorrectly ordered array values, noncanonical identities/counters, mismatched cutoff evidence, and changed payloads paired with an original digest. Several supported state families may change in one owner operation: its exact changed-family set and complete credential-free post-state are committed with one source generation/version advance, one applicable Account-local fence advance, one event and one checkpoint in the same Account transaction. The actual issuance fence remains separate private operation and same-snapshot recipient evidence, never a source-event field. This schema does not represent password reset or logout-all, change their closed events or immutable receipts, authorize a caller, grant roles, or enable admission. Unsupported mixed-password work remains denied until its real password-reset owner operation is composed. [Account API Contracts](./microservices/account-service/api-contracts.md#account-owned-security-state-operation-and-readback) owns the local operation, retry and receipt consequences. + #### Issuer Generation Source Event `account-auth-issuer-generation-event/v1` is the closed source schema for one Account-committed issuer-generation advance. Its required preimage fields are `schemaVersion` (exactly `account-auth-issuer-generation-event/v1`), `eventType` (exactly `ISSUER_GENERATION_ADVANCED`), `eventId`, `requestId`, `issuerId`, `sourceScope`, `outboxStreamKey`, `outboxSequence`, `issuerAuthGeneration`, and `sourceVersion`; its sole additional wire field is `eventDigest`. `issuerId` is the exact configured Account JWT issuer identity, not an Account or tenant selector, and is never normalized or inferred. `sourceScope` is exactly `issuer/` and `outboxStreamKey` is exactly `account:auth-authority:v1:`. Request and event identities are nonempty immutable strings. The sequence, generation and source version are canonical positive decimal strings; consumers parse arbitrary precision. There are no optional fields, arrays, recipient tuples, recipient issuance fences, account/tenant IDs, cutoff objects or `null` placeholders. 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 c0f4619f80..b931e8dd51 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,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The closed Account security-state codec and canonical generation-projection consumer now preserve the existing reset/logout schemas while validating the complete new payload and exact duplicate identity. Structural snapshot construction accepts that closed schema, but authenticated current/historical source readers still reject it without a real immutable operation receipt; no producer or permission is implied. The control-ui response envelope adds a distinct purpose/key and targetless original-operation, response, authority-capture, fence and expiry binding. Local combined checks/JAR/analyzers/docs pass with 249 common-platform and 1000 Account unit outcomes, including eleven new codec vectors and six control-ui crypto cases; all 404 Account integration cases skip without Docker. Eighty offline ring bootstrap/materializer cases pass. Stable authenticated source operations, receipt persistence/readback, actual ordinary control-ui issuance/registry/recovery and protected custody/live readiness remain required; no runtime activation follows. + +At exact published `9c9f01be79bc1696bd2ca5a2e707068603916602`, [CI37395254176](https://github.com/benhook1013/FireMUD/actions/runs/37395254176) executes all seven pending-reset source-change and seventeen logout-all PostgreSQL methods cleanly without skips. Verified merge `3a54423ebe6c956a05691c8eae37e223f7134d38` has exact source/parent and a source-identical tree. This closes the corrected schema-name and V59-to-V60 fixture execution gaps below. Account's separate V58-to-V59 retained-image fixture fails because it migrates past its named target into V61; the bounded correction pins V59 without dropping retained-row assertions. World separately fails six of ten association methods on immutable frozen-plan readback, while its one reserved-tenant preparation method passes. Aggregate CI is red, and the owning corrections still require corrected-state PostgreSQL execution. These storage results do not establish authenticated creator, release or lifecycle activation. + 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. diff --git a/dev-tools/deploy/bootstrap-account-response-envelope-ring.py b/dev-tools/deploy/bootstrap-account-response-envelope-ring.py index ba84684034..6d22e12c44 100644 --- a/dev-tools/deploy/bootstrap-account-response-envelope-ring.py +++ b/dev-tools/deploy/bootstrap-account-response-envelope-ring.py @@ -30,6 +30,7 @@ SOURCE_RECORD_VERSION = 1 KEY_BYTES = 32 +RING_PURPOSES = ("bare-login", "connect-token", "pending-reset", "control-ui-response") OWNER_DIRECTORY_MODE = 0o700 OWNER_FILE_MODE = 0o600 KEY_ID_PATTERN = re.compile(r"[A-Za-z0-9_-]{1,64}\Z") @@ -111,22 +112,20 @@ def _random_identifier(byte_count: int) -> str: def _manifest() -> bytes: key_id = _random_identifier(16) - bare_login_key = secrets.token_bytes(KEY_BYTES) - connect_token_key = secrets.token_bytes(KEY_BYTES) - pending_reset_key = secrets.token_bytes(KEY_BYTES) - while connect_token_key == bare_login_key or connect_token_key == pending_reset_key: - connect_token_key = secrets.token_bytes(KEY_BYTES) - while pending_reset_key in (bare_login_key, connect_token_key): - pending_reset_key = secrets.token_bytes(KEY_BYTES) - bare_login_encoded = base64.urlsafe_b64encode(bare_login_key).rstrip(b"=").decode("ascii") - connect_token_encoded = base64.urlsafe_b64encode(connect_token_key).rstrip(b"=").decode("ascii") - pending_reset_encoded = base64.urlsafe_b64encode(pending_reset_key).rstrip(b"=").decode("ascii") - return ( - f"version=1\nactiveKeyId={key_id}\n" - f"key:{key_id}:bare-login={bare_login_encoded}\n" - f"key:{key_id}:connect-token={connect_token_encoded}\n" - f"key:{key_id}:pending-reset={pending_reset_encoded}\n" - ).encode("ascii") + used_material: set[bytes] = set() + active_keys: dict[str, bytes] = {} + for purpose in RING_PURPOSES: + while True: + candidate = secrets.token_bytes(KEY_BYTES) + if candidate not in used_material: + used_material.add(candidate) + active_keys[purpose] = candidate + break + lines = ["version=1", f"activeKeyId={key_id}"] + for purpose, key_material in active_keys.items(): + encoded = base64.urlsafe_b64encode(key_material).rstrip(b"=").decode("ascii") + lines.append(f"key:{key_id}:{purpose}={encoded}") + return ("\n".join(lines) + "\n").encode("ascii") def _source_record_bytes( @@ -265,11 +264,11 @@ def fresh_key() -> bytes: return candidate active_keys: dict[str, bytes] = {} - for purpose in ("bare-login", "connect-token", "pending-reset"): + for purpose in RING_PURPOSES: active_keys[purpose] = fresh_key() lines = ["version=1", f"activeKeyId={active_key_id}"] for key_id, purposes in previous.keys.items(): - for purpose in ("bare-login", "connect-token", "pending-reset"): + for purpose in RING_PURPOSES: if purpose not in purposes: continue encoded = base64.urlsafe_b64encode(purposes[purpose]).rstrip(b"=").decode("ascii") diff --git a/dev-tools/deploy/materialize-account-response-envelope-ring.py b/dev-tools/deploy/materialize-account-response-envelope-ring.py index b22010a57b..e8b4d01e0f 100644 --- a/dev-tools/deploy/materialize-account-response-envelope-ring.py +++ b/dev-tools/deploy/materialize-account-response-envelope-ring.py @@ -433,7 +433,7 @@ def parse_manifest(manifest: bytes) -> ParsedManifest: keys: dict[str, dict[str, bytes]] = {} seen_material: set[bytes] = set() required_purposes = {"bare-login", "connect-token"} - allowed_purposes = required_purposes | {"pending-reset"} + allowed_purposes = required_purposes | {"pending-reset", "control-ui-response"} for line in lines[2:]: if line.count("=") != 1: raise MaterializationError("source manifest contains a malformed key line") diff --git a/dev-tools/tests/test_account_response_envelope_bootstrap.py b/dev-tools/tests/test_account_response_envelope_bootstrap.py index 4ee8892f8d..a15c5243bc 100644 --- a/dev-tools/tests/test_account_response_envelope_bootstrap.py +++ b/dev-tools/tests/test_account_response_envelope_bootstrap.py @@ -118,7 +118,7 @@ def test_output_is_materializer_compatible_with_valid_timestamps_and_null_predec manifest = MATERIALIZER.parse_manifest(source.manifest_bytes) self.assertEqual(manifest.active_key_id, next(iter(manifest.keys))) self.assertEqual( - {"bare-login", "connect-token", "pending-reset"}, + {"bare-login", "connect-token", "pending-reset", "control-ui-response"}, set(manifest.keys[manifest.active_key_id]), ) @@ -131,25 +131,31 @@ def test_purpose_keys_are_distinct_random_32_byte_values(self) -> None: self.assertEqual(32, len(keys["bare-login"])) self.assertEqual(32, len(keys["connect-token"])) self.assertEqual(32, len(keys["pending-reset"])) - self.assertEqual(3, len(set(keys.values()))) + self.assertEqual(32, len(keys["control-ui-response"])) + self.assertEqual(4, len(set(keys.values()))) self.assertNotEqual("key-id", manifest.active_key_id) self.assertNotEqual("source-generation", source.source_generation) - def test_pending_key_redraw_cannot_collide_with_another_purpose(self) -> None: - first_key, second_key, third_key = (bytes([number]) * 32 for number in (1, 2, 3)) + def test_control_ui_response_key_redraw_cannot_collide_with_another_purpose(self) -> None: + first_key, second_key, third_key, fourth_key = (bytes([number]) * 32 for number in (1, 2, 3, 4)) with ( patch.object(BOOTSTRAP, "_random_identifier", return_value="k1"), patch.object( BOOTSTRAP.secrets, "token_bytes", - side_effect=[first_key, second_key, first_key, second_key, third_key], + side_effect=[first_key, second_key, third_key, first_key, second_key, third_key, fourth_key], ), ): manifest_bytes = BOOTSTRAP._manifest() manifest = MATERIALIZER.parse_manifest(manifest_bytes) self.assertEqual( - {"bare-login": first_key, "connect-token": second_key, "pending-reset": third_key}, + { + "bare-login": first_key, + "connect-token": second_key, + "pending-reset": third_key, + "control-ui-response": fourth_key, + }, manifest.keys["k1"], ) @@ -181,7 +187,7 @@ def test_rotation_is_parser_and_materializer_compatible_and_retains_old_keys(sel for key_id, purposes in previous_manifest.keys.items(): self.assertEqual(purposes, rotated_manifest.keys[key_id]) self.assertEqual( - {"bare-login", "connect-token", "pending-reset"}, + {"bare-login", "connect-token", "pending-reset", "control-ui-response"}, set(rotated_manifest.keys[rotated_manifest.active_key_id]), ) self.assertEqual( @@ -204,7 +210,7 @@ def test_rotation_is_parser_and_materializer_compatible_and_retains_old_keys(sel for key_id, purposes in rotated_manifest.keys.items(): self.assertEqual(purposes, third_manifest.keys[key_id]) self.assertEqual( - {"bare-login", "connect-token", "pending-reset"}, + {"bare-login", "connect-token", "pending-reset", "control-ui-response"}, set(third_manifest.keys[third_manifest.active_key_id]), ) @@ -271,7 +277,7 @@ def test_rotation_upgrades_a_two_purpose_ring_without_inventing_old_pending_keys self.assertEqual(old_keys["bare-login"], upgraded_manifest.keys[old_id]["bare-login"]) self.assertEqual(old_keys["connect-token"], upgraded_manifest.keys[old_id]["connect-token"]) self.assertEqual( - {"bare-login", "connect-token", "pending-reset"}, + {"bare-login", "connect-token", "pending-reset", "control-ui-response"}, set(upgraded_manifest.keys[upgraded_manifest.active_key_id]), ) @@ -301,6 +307,49 @@ def test_rotation_upgrades_a_two_purpose_ring_without_inventing_old_pending_keys ) ) + def test_rotation_upgrades_a_three_purpose_ring_without_inventing_old_control_ui_key(self) -> None: + self.create() + original = MATERIALIZER.read_source_record(self.output) + original_manifest = MATERIALIZER.parse_manifest(original.manifest_bytes) + old_id = original_manifest.active_key_id + old_keys = original_manifest.keys[old_id] + retained_purposes = ("bare-login", "connect-token", "pending-reset") + legacy_manifest = ( + f"version=1\nactiveKeyId={old_id}\n" + + "".join( + f"key:{old_id}:{purpose}={base64.urlsafe_b64encode(old_keys[purpose]).rstrip(b'=').decode('ascii')}\n" + for purpose in retained_purposes + ) + ).encode("ascii") + legacy_record = json.loads(self.output.read_text(encoding="utf-8")) + legacy_record["manifestBase64"] = base64.b64encode(legacy_manifest).decode("ascii") + legacy_output = self.custody_directory / "legacy-three-purpose-source-record.json" + legacy_output.write_text( + json.dumps(legacy_record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n", + encoding="utf-8", + ) + os.chmod(legacy_output, 0o600) + + rotated_output = self.custody_directory / "upgraded-three-purpose-source-record.json" + BOOTSTRAP.create_rotated_source_record( + output=rotated_output, + previous_source_record=legacy_output, + environment_id=ENVIRONMENT_ID, + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=NOW + dt.timedelta(minutes=10), + ) + + upgraded = MATERIALIZER.read_source_record(rotated_output) + upgraded_manifest = MATERIALIZER.parse_manifest(upgraded.manifest_bytes) + self.assertEqual(set(retained_purposes), set(upgraded_manifest.keys[old_id])) + for purpose in retained_purposes: + self.assertEqual(old_keys[purpose], upgraded_manifest.keys[old_id][purpose]) + self.assertEqual( + {"bare-login", "connect-token", "pending-reset", "control-ui-response"}, + set(upgraded_manifest.keys[upgraded_manifest.active_key_id]), + ) + def test_rotation_rejects_wrong_environment_or_namespace_without_output(self) -> None: self.create() wrong_environment_output = self.custody_directory / "wrong-environment.json" diff --git a/dev-tools/tests/test_account_response_envelope_materializer.py b/dev-tools/tests/test_account_response_envelope_materializer.py index e3a27f5c99..40f7e623f4 100644 --- a/dev-tools/tests/test_account_response_envelope_materializer.py +++ b/dev-tools/tests/test_account_response_envelope_materializer.py @@ -255,18 +255,21 @@ def run_materializer( now=now, ) - def test_manifest_parser_accepts_optional_pending_reset_purpose(self) -> None: + def test_manifest_parser_accepts_optional_pending_reset_and_control_ui_purposes(self) -> None: manifest = manifest_for( active="k2", ids=("k1", "k2"), - purposes_by_id={"k2": ("bare-login", "connect-token", "pending-reset")}, + purposes_by_id={"k2": ("bare-login", "connect-token", "pending-reset", "control-ui-response")}, ) parsed = MATERIALIZER.parse_manifest(manifest) self.assertEqual({"bare-login", "connect-token"}, set(parsed.keys["k1"])) - self.assertEqual({"bare-login", "connect-token", "pending-reset"}, set(parsed.keys["k2"])) - self.assertEqual(5, len({key for values in parsed.keys.values() for key in values.values()})) + self.assertEqual( + {"bare-login", "connect-token", "pending-reset", "control-ui-response"}, + set(parsed.keys["k2"]), + ) + self.assertEqual(6, len({key for values in parsed.keys.values() for key in values.values()})) def test_manifest_parser_rejects_missing_original_purpose(self) -> None: manifest = manifest_for( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountControlUiResponseEnvelopeBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountControlUiResponseEnvelopeBinding.java new file mode 100644 index 0000000000..7d68ece4b5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountControlUiResponseEnvelopeBinding.java @@ -0,0 +1,178 @@ +package net.firedevops.firemud.accountservice.security; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Immutable targetless binding for the exact original control-UI issuance response. The authority + * capture and issuance fence digests identify complete retained evidence; neither digest alone + * grants authority or proves currentness. + */ +public final class AccountControlUiResponseEnvelopeBinding { + public static final String CONTROL_UI_PROFILE = "control-ui"; + public static final String CONTROL_UI_AUDIENCE = "control-ui"; + + private static final int DIGEST_LENGTH_BYTES = 32; + private static final Pattern TOKEN_HASH_PATTERN = Pattern.compile("[0-9a-f]{64}"); + + private final String accountId; + private final String operationId; + private final String requestId; + private final byte[] requestDigest; + private final String tokenHash; + private final byte[] responseDigest; + private final byte[] authorityCaptureDigest; + private final byte[] issuanceFenceDigest; + private final Instant issuedAt; + private final Instant expiresAt; + + public AccountControlUiResponseEnvelopeBinding( + String accountId, + String operationId, + String requestId, + byte[] requestDigest, + String tokenHash, + byte[] responseDigest, + byte[] authorityCaptureDigest, + byte[] issuanceFenceDigest, + Instant issuedAt, + Instant expiresAt) { + this.accountId = canonicalNonNilUuid(accountId, "accountId"); + this.operationId = canonicalNonNilUuid(operationId, "operationId"); + this.requestId = canonicalNonNilUuid(requestId, "requestId"); + this.requestDigest = copyDigest(requestDigest, "requestDigest"); + this.tokenHash = requireTokenHash(tokenHash); + this.responseDigest = copyDigest(responseDigest, "responseDigest"); + this.authorityCaptureDigest = copyDigest(authorityCaptureDigest, "authorityCaptureDigest"); + this.issuanceFenceDigest = copyDigest(issuanceFenceDigest, "issuanceFenceDigest"); + this.issuedAt = requirePositiveEpochSecond(issuedAt, "issuedAt"); + this.expiresAt = requirePositiveEpochSecond(expiresAt, "expiresAt"); + if (!this.issuedAt.isBefore(this.expiresAt)) { + throw new IllegalArgumentException("expiresAt must follow issuedAt"); + } + } + + public String accountId() { + return accountId; + } + + public String operationId() { + return operationId; + } + + public String requestId() { + return requestId; + } + + public String profile() { + return CONTROL_UI_PROFILE; + } + + public String audience() { + return CONTROL_UI_AUDIENCE; + } + + public byte[] requestDigest() { + return requestDigest.clone(); + } + + public String tokenHash() { + return tokenHash; + } + + public byte[] responseDigest() { + return responseDigest.clone(); + } + + public byte[] authorityCaptureDigest() { + return authorityCaptureDigest.clone(); + } + + public byte[] issuanceFenceDigest() { + return issuanceFenceDigest.clone(); + } + + public Instant issuedAt() { + return issuedAt; + } + + public Instant expiresAt() { + return expiresAt; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AccountControlUiResponseEnvelopeBinding that)) { + return false; + } + return accountId.equals(that.accountId) + && operationId.equals(that.operationId) + && requestId.equals(that.requestId) + && Arrays.equals(requestDigest, that.requestDigest) + && tokenHash.equals(that.tokenHash) + && Arrays.equals(responseDigest, that.responseDigest) + && Arrays.equals(authorityCaptureDigest, that.authorityCaptureDigest) + && Arrays.equals(issuanceFenceDigest, that.issuanceFenceDigest) + && issuedAt.equals(that.issuedAt) + && expiresAt.equals(that.expiresAt); + } + + @Override + public int hashCode() { + int result = Objects.hash(accountId, operationId, requestId, tokenHash, issuedAt, expiresAt); + result = 31 * result + Arrays.hashCode(requestDigest); + result = 31 * result + Arrays.hashCode(responseDigest); + result = 31 * result + Arrays.hashCode(authorityCaptureDigest); + result = 31 * result + Arrays.hashCode(issuanceFenceDigest); + return result; + } + + @Override + public String toString() { + return "AccountControlUiResponseEnvelopeBinding{evidence=}"; + } + + private static String canonicalNonNilUuid(String value, String fieldName) { + Objects.requireNonNull(value, fieldName); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || (parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L)) { + throw new IllegalArgumentException("Invalid " + fieldName); + } + return value; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Invalid " + fieldName, exception); + } + } + + private static byte[] copyDigest(byte[] value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException("Invalid " + fieldName); + } + return value.clone(); + } + + private static String requireTokenHash(String value) { + Objects.requireNonNull(value, "tokenHash"); + if (!TOKEN_HASH_PATTERN.matcher(value).matches()) { + throw new IllegalArgumentException("Invalid tokenHash"); + } + return value; + } + + private static Instant requirePositiveEpochSecond(Instant value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.getEpochSecond() <= 0L || value.getNano() != 0) { + throw new IllegalArgumentException("Invalid " + fieldName); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java index d80e93cddd..f017e7311f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java @@ -25,10 +25,11 @@ import javax.crypto.spec.SecretKeySpec; /** - * Account-local AES-256-GCM for bounded credential-bearing response and pending-reset envelopes. - * The mounted manifest is read for every operation so atomic rotation and key removal take effect - * immediately. Callers must provide an Account-only mounted path and must read back the exact - * durable operation/envelope before using a decrypt method for recovery. + * Account-local AES-256-GCM for bounded credential-bearing response, pending-reset, and targetless + * control-UI response envelopes. The mounted manifest is read for every operation so atomic + * rotation and key removal take effect immediately. Callers must provide an Account-only mounted + * path and must read back the exact durable operation/envelope before using a decrypt method for + * recovery. * *

Manifest v1 is strict ASCII (an ASCII subset of UTF-8), terminated by one LF: * @@ -37,15 +38,17 @@ * activeKeyId=k2 * key:k1:bare-login=<43-character-unpadded-base64url> * key:k1:connect-token=<43-character-unpadded-base64url> + * key:k1:control-ui-response=<43-character-unpadded-base64url> * key:k2:bare-login=<43-character-unpadded-base64url> * key:k2:connect-token=<43-character-unpadded-base64url> * key:k2:pending-reset=<43-character-unpadded-base64url> + * key:k2:control-ui-response=<43-character-unpadded-base64url> * * - * Every key ID must have independent 32-byte connect-token and bare-LOGIN keys. A pending-reset key - * is optional for retained IDs and is required only for pending-reset operations. The active ID is - * used for new writes; retained older IDs are decrypt-only. No default key or classpath fallback - * exists. + * Every key ID must have independent 32-byte connect-token and bare-LOGIN keys. Pending-reset and + * control-UI response keys are optional for retained IDs and unavailable purposes fail closed. The + * active ID is used for new writes; retained older IDs are decrypt-only. No default key or + * classpath fallback exists. */ public final class AccountEnvelopeCrypto { public static final String KEY_RING_PATH_ENVIRONMENT_VARIABLE = @@ -65,6 +68,8 @@ public final class AccountEnvelopeCrypto { "firemud-account-response-envelope/v1".getBytes(StandardCharsets.US_ASCII); private static final byte[] PENDING_RESET_AAD_DOMAIN = "firemud-account-pending-reset-envelope/v1".getBytes(StandardCharsets.US_ASCII); + private static final byte[] CONTROL_UI_RESPONSE_AAD_DOMAIN = + "firemud-account-control-ui-response-envelope/v1".getBytes(StandardCharsets.US_ASCII); private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private final Path manifestPath; @@ -133,6 +138,26 @@ public AccountEncryptedEnvelope encryptPendingReset( pendingResetAssociatedData(formatVersion, keyId, purpose, binding)); } + /** Encrypts the exact response for the targetless control-UI issuance recovery binding. */ + public AccountEncryptedEnvelope encryptControlUiResponse( + AccountControlUiResponseEnvelopeBinding binding, byte[] responseBytes) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(responseBytes, "responseBytes"); + if (responseBytes.length == 0 + || responseBytes.length > AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + if (!matchesControlUiResponseDigest(responseBytes, binding)) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + + return encryptWithAssociatedData( + AccountEnvelopePurpose.CONTROL_UI_RESPONSE, + responseBytes, + (formatVersion, keyId, purpose) -> + controlUiResponseAssociatedData(formatVersion, keyId, purpose, binding)); + } + private AccountEncryptedEnvelope encryptWithAssociatedData( AccountEnvelopePurpose purpose, byte[] plaintext, @@ -200,6 +225,27 @@ public byte[] decryptPendingReset( return encodedArgon2Verifier; } + /** Decrypts only under the exact original targetless control-UI issuance binding. */ + public byte[] decryptControlUiResponse( + AccountEncryptedEnvelope envelope, AccountControlUiResponseEnvelopeBinding binding) { + Objects.requireNonNull(envelope, "envelope"); + Objects.requireNonNull(binding, "binding"); + if (envelope.purpose() != AccountEnvelopePurpose.CONTROL_UI_RESPONSE) { + throw failure(AccountEnvelopeCryptoException.Failure.PURPOSE_MISMATCH); + } + + byte[] responseBytes = + decryptWithAssociatedData( + envelope, + (formatVersion, keyId, purpose) -> + controlUiResponseAssociatedData(formatVersion, keyId, purpose, binding)); + if (!matchesControlUiResponseDigest(responseBytes, binding)) { + Arrays.fill(responseBytes, (byte) 0); + throw failure(AccountEnvelopeCryptoException.Failure.AUTHENTICATION_FAILED); + } + return responseBytes; + } + private byte[] decryptWithAssociatedData( AccountEncryptedEnvelope envelope, AssociatedDataFactory associatedDataFactory) { @@ -460,6 +506,60 @@ private static byte[] pendingResetAssociatedData( } } + private static byte[] controlUiResponseAssociatedData( + int formatVersion, + String keyId, + AccountEnvelopePurpose purpose, + AccountControlUiResponseEnvelopeBinding binding) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream output = new DataOutputStream(bytes); + writeFrame(output, CONTROL_UI_RESPONSE_AAD_DOMAIN); + output.writeInt(formatVersion); + writeFrame(output, utf8(keyId)); + writeFrame(output, utf8(purpose.manifestName())); + writeFrame(output, utf8(binding.accountId())); + writeFrame(output, utf8(binding.operationId())); + writeFrame(output, utf8(binding.requestId())); + writeFrame(output, utf8(binding.profile())); + writeFrame(output, utf8(binding.audience())); + writeFrame(output, binding.requestDigest()); + writeFrame(output, utf8(binding.tokenHash())); + writeFrame(output, binding.responseDigest()); + writeFrame(output, binding.authorityCaptureDigest()); + writeFrame(output, binding.issuanceFenceDigest()); + writeFrame(output, utf8(Long.toString(binding.issuedAt().getEpochSecond()))); + writeFrame(output, utf8(Long.toString(binding.expiresAt().getEpochSecond()))); + output.flush(); + if (bytes.size() > MAX_AAD_FIELD_LENGTH_BYTES * 8) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + return bytes.toByteArray(); + } catch (IOException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.CRYPTO_OPERATION_FAILED); + } + } + + private static boolean matchesControlUiResponseDigest( + byte[] responseBytes, AccountControlUiResponseEnvelopeBinding binding) { + byte[] calculatedDigest = null; + byte[] expectedDigest = null; + try { + calculatedDigest = MessageDigest.getInstance("SHA-256").digest(responseBytes); + expectedDigest = binding.responseDigest(); + return MessageDigest.isEqual(calculatedDigest, expectedDigest); + } catch (GeneralSecurityException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.CRYPTO_OPERATION_FAILED); + } finally { + if (calculatedDigest != null) { + Arrays.fill(calculatedDigest, (byte) 0); + } + if (expectedDigest != null) { + Arrays.fill(expectedDigest, (byte) 0); + } + } + } + private static boolean matchesTargetVerifierDigest( byte[] encodedArgon2Verifier, AccountPendingResetEnvelopeBinding binding) { byte[] calculatedDigest = null; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java index 2b00e66c22..82006bd51c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java @@ -4,7 +4,8 @@ public enum AccountEnvelopePurpose { CONNECT_TOKEN_RESPONSE("connect-token"), BARE_LOGIN_RESPONSE("bare-login"), - PENDING_PASSWORD_RESET("pending-reset"); + PENDING_PASSWORD_RESET("pending-reset"), + CONTROL_UI_RESPONSE("control-ui-response"); private final String manifestName; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java index 9a8464b1a1..48e3d68de8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java @@ -1,5 +1,11 @@ package net.firedevops.firemud.accountservice.service; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -24,6 +30,7 @@ import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; @@ -32,6 +39,10 @@ * It does not authenticate a caller or turn source evidence into recipient authority. */ public final class AccountAuthoritySourceEventReadback { + private static final ObjectMapper SNAPSHOT_JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; private static final String PASSWORD_RESET_REQUEST_ID_PREFIX = "account-password-reset-request-v1:"; @@ -349,7 +360,10 @@ private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) { } } - /** Reuses the closed schema validator for immutable source-result constructor invariants. */ + /** + * Checks structural source-result invariants, without proving an immutable operation receipt. + * Security-state evidence remains unsupported by the owner current/historical receipt readers. + */ static void requireEventMatchesSnapshot( Event event, UUID accountUuid, ScopeState current, boolean mustBeCurrentLatest) { if (accountUuid == null @@ -359,7 +373,7 @@ static void requireEventMatchesSnapshot( || current.sourceVersion() <= 0L) { throw new IllegalStateException("Account source snapshot scope or counters are invalid"); } - VerifiedSourceEvent verified = verifyEvent(event, accountUuid); + SnapshotCounters verified = verifySnapshotEvent(event, accountUuid); BigInteger eventGeneration = new BigInteger(verified.accountAuthorityGeneration()); BigInteger eventSourceVersion = new BigInteger(verified.sourceVersion()); BigInteger currentGeneration = BigInteger.valueOf(current.generation()); @@ -376,6 +390,47 @@ static void requireEventMatchesSnapshot( } } + private static SnapshotCounters verifySnapshotEvent(Event event, UUID accountUuid) { + if (event == null) { + throw new IllegalStateException("Account source event is missing"); + } + String payload = new String(event.payload(), StandardCharsets.UTF_8); + final JsonNode tree; + try { + tree = SNAPSHOT_JSON.readTree(payload); + } catch (IOException exception) { + throw new IllegalStateException("Account source event snapshot JSON is malformed", exception); + } + if (tree == null || !tree.isObject() || !tree.path("schemaVersion").isTextual()) { + throw new IllegalStateException("Account source event snapshot schema is missing"); + } + if (!AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION.equals( + tree.path("schemaVersion").textValue())) { + VerifiedSourceEvent original = verifyEvent(event, accountUuid); + return new SnapshotCounters(original.accountAuthorityGeneration(), original.sourceVersion()); + } + final AccountSecurityStateAuthorityEventV1Codec.AccountSecurityStateAuthorityEvent security; + try { + security = AccountSecurityStateAuthorityEventV1Codec.verify(payload); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Account security-state snapshot event is invalid", exception); + } + if (!MessageDigest.isEqual(event.payload(), security.canonicalJsonUtf8()) + || !event.outboxStreamKey().equals(security.outboxStreamKey()) + || !event.requestId().equals(security.requestId()) + || !event.eventId().equals(security.eventId()) + || !event.eventDigest().equals(security.eventDigest()) + || !accountUuid.toString().equals(security.accountId()) + || !Long.toString(event.outboxSequence()).equals(security.outboxSequence())) { + throw new IllegalStateException( + "Account security-state snapshot event readback is inconsistent"); + } + return new SnapshotCounters(security.accountAuthorityGeneration(), security.sourceVersion()); + } + + private record SnapshotCounters(String accountAuthorityGeneration, String sourceVersion) {} + private void requireReceiptNotAhead( long generation, long sourceVersion, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java index 18844f4f3b..3dcf25d099 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; @@ -227,23 +228,33 @@ private static void validateSourceEvent( String sourceVersion, String streamKey, String sequence) { - String canonicalEvent; + final JsonNode root; try { - PasswordResetAuthorityEvent reset = PasswordResetAuthorityEventV1Codec.verify(eventJson); - canonicalEvent = new String(reset.canonicalJsonUtf8(), StandardCharsets.UTF_8); - requireEventBinding( - accountId, - generation, - sourceVersion, - streamKey, - sequence, - reset.accountId(), - reset.accountAuthorityGeneration(), - reset.sourceVersion(), - reset.outboxStreamKey(), - reset.outboxSequence()); - } catch (IllegalArgumentException resetFailure) { - try { + root = JSON.readTree(eventJson); + } catch (IOException exception) { + throw new IllegalArgumentException("Account source event JSON is malformed", exception); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Account source event must be a JSON object"); + } + String canonicalEvent; + switch (requireText(object, "schemaVersion")) { + case PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION -> { + PasswordResetAuthorityEvent reset = PasswordResetAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = new String(reset.canonicalJsonUtf8(), StandardCharsets.UTF_8); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + reset.accountId(), + reset.accountAuthorityGeneration(), + reset.sourceVersion(), + reset.outboxStreamKey(), + reset.outboxSequence()); + } + case AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION -> { AccountLogoutAllAuthorityEvent logout = AccountLogoutAllAuthorityEventV1Codec.verify(eventJson); canonicalEvent = new String(logout.canonicalJsonUtf8(), StandardCharsets.UTF_8); @@ -258,10 +269,25 @@ private static void validateSourceEvent( logout.sourceVersion(), logout.outboxStreamKey(), logout.outboxSequence()); - } catch (IllegalArgumentException logoutFailure) { - logoutFailure.addSuppressed(resetFailure); + } + case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> { + var security = AccountSecurityStateAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = security.canonicalJson(); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + security.accountId(), + security.accountAuthorityGeneration(), + security.sourceVersion(), + security.outboxStreamKey(), + security.outboxSequence()); + } + default -> { throw new IllegalArgumentException( - "Account source event is not one of the declared closed schemas", logoutFailure); + "Account source event is not one of the declared closed schemas"); } } if (!canonicalEvent.equals(eventJson)) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountControlUiResponseEnvelopeCryptoTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountControlUiResponseEnvelopeCryptoTest.java new file mode 100644 index 0000000000..a95d69e613 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountControlUiResponseEnvelopeCryptoTest.java @@ -0,0 +1,636 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import net.firedevops.firemud.accountservice.security.AccountControlUiResponseEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountControlUiResponseEnvelopeCryptoTest { + private static final String ACCOUNT_ID = "b61a90bc-cdb4-42ac-9067-08667de2ac84"; + private static final String OPERATION_ID = "5d2421a0-dca2-4f74-90db-f29345302029"; + private static final String REQUEST_ID = "0418d715-8b6f-47cf-8625-85229f481419"; + private static final String TOKEN_HASH = "12".repeat(32); + private static final Instant ISSUED_AT = Instant.parse("2030-05-06T07:08:09Z"); + private static final Instant EXPIRES_AT = Instant.parse("2030-05-06T08:08:09Z"); + + @TempDir private Path temporaryDirectory; + + private Path manifestPath; + + @BeforeEach + void setUp() { + manifestPath = temporaryDirectory.resolve("manifest.v1"); + } + + @Test + void exactResponseDecryptsAfterCryptoObjectRecreationAndChecksItsDigest() throws Exception { + writeManifest(true); + AccountControlUiResponseEnvelopeBinding binding = binding(); + byte[] exactResponse = + "the exact original control-ui response".getBytes(StandardCharsets.UTF_8); + AccountEnvelopeCrypto writer = new AccountEnvelopeCrypto(manifestPath); + + AccountEncryptedEnvelope envelope = writer.encryptControlUiResponse(binding, exactResponse); + byte[] recovered = + new AccountEnvelopeCrypto(manifestPath).decryptControlUiResponse(envelope, binding); + + assertEquals("k1", envelope.keyId()); + assertEquals(AccountEnvelopePurpose.CONTROL_UI_RESPONSE, envelope.purpose()); + assertArrayEquals(exactResponse, recovered); + assertEquals("control-ui", binding.profile()); + assertEquals("control-ui", binding.audience()); + assertFailure( + Failure.INVALID_ENVELOPE, + () -> + writer.encryptControlUiResponse( + binding, "changed response".getBytes(StandardCharsets.UTF_8))); + } + + @Test + void rotationKeepsTheOriginalEnvelopeBytesDecryptableUntilEvidenceBasedRemoval() + throws Exception { + writeManifest(true); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountControlUiResponseEnvelopeBinding binding = binding(); + byte[] exactResponse = + "the exact original control-ui response".getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope originalEnvelope = + crypto.encryptControlUiResponse(binding, exactResponse); + byte[] originalNonce = originalEnvelope.nonce(); + byte[] originalCiphertext = originalEnvelope.ciphertext(); + + writeRotatedManifest(true); + AccountEnvelopeCrypto restartedReader = new AccountEnvelopeCrypto(manifestPath); + assertEquals("k2", restartedReader.encryptControlUiResponse(binding(), exactResponse).keyId()); + assertArrayEquals(originalNonce, originalEnvelope.nonce()); + assertArrayEquals(originalCiphertext, originalEnvelope.ciphertext()); + assertArrayEquals( + exactResponse, restartedReader.decryptControlUiResponse(originalEnvelope, binding)); + + writeRotatedManifest(false); + assertFailure( + Failure.KEY_UNAVAILABLE, + () -> restartedReader.decryptControlUiResponse(originalEnvelope, binding)); + } + + @Test + void everyVariableBindingFieldIsAuthenticated() throws Exception { + writeManifest(true); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + byte[] response = "response body".getBytes(StandardCharsets.UTF_8); + AccountControlUiResponseEnvelopeBinding binding = + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT); + AccountEncryptedEnvelope envelope = crypto.encryptControlUiResponse(binding, response); + + assertAuthenticationFailure( + crypto, + envelope, + binding( + "08cd8f48-7040-450a-a3de-ece2bb90dc20", + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + "27acd7d4-4d1c-44e6-baea-0c902f5f039e", + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + OPERATION_ID, + "853745a3-6cf9-4962-a4e4-6d668b022c2f", + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(11), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + "34".repeat(32), + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digest(12), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(13), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(14), + ISSUED_AT, + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT.plusSeconds(1), + EXPIRES_AT)); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT.plusSeconds(1))); + } + + @Test + void wrongPurposeRelabelingAndMissingPurposeFailClosedWithoutFallback() throws Exception { + writeManifest(true); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + byte[] response = "response body".getBytes(StandardCharsets.UTF_8); + AccountControlUiResponseEnvelopeBinding binding = + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT); + AccountEncryptedEnvelope envelope = crypto.encryptControlUiResponse(binding, response); + + AccountEncryptedEnvelope relabeled = + new AccountEncryptedEnvelope( + envelope.formatVersion(), + envelope.keyId(), + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + envelope.nonce(), + envelope.ciphertext()); + assertFailure( + Failure.PURPOSE_MISMATCH, () -> crypto.decryptControlUiResponse(relabeled, binding)); + assertFailure( + Failure.AUTHENTICATION_FAILED, + () -> + crypto.decrypt( + relabeled, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, connectBinding())); + + writeManifest(false); + assertFailure( + Failure.KEY_UNAVAILABLE, () -> crypto.encryptControlUiResponse(binding, response)); + AccountEnvelopeBinding oldPurposeBinding = connectBinding(); + AccountEncryptedEnvelope oldPurposeEnvelope = + crypto.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + oldPurposeBinding, + "old purpose still works".getBytes(StandardCharsets.UTF_8)); + assertEquals(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, oldPurposeEnvelope.purpose()); + } + + @Test + void bindingCopiesDigestBytesComparesByValueAndRedactsItsRepresentation() throws Exception { + byte[] requestDigest = digest(1); + byte[] responseDigest = digest(2); + byte[] captureDigest = digest(3); + byte[] fenceDigest = digest(4); + AccountControlUiResponseEnvelopeBinding binding = + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + requestDigest, + TOKEN_HASH, + responseDigest, + captureDigest, + fenceDigest, + ISSUED_AT, + EXPIRES_AT); + Arrays.fill(requestDigest, (byte) 0); + Arrays.fill(responseDigest, (byte) 0); + Arrays.fill(captureDigest, (byte) 0); + Arrays.fill(fenceDigest, (byte) 0); + + AccountControlUiResponseEnvelopeBinding equalBinding = + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digest(2), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT); + byte[] exposedRequestDigest = binding.requestDigest(); + byte[] exposedResponseDigest = binding.responseDigest(); + byte[] exposedCaptureDigest = binding.authorityCaptureDigest(); + byte[] exposedFenceDigest = binding.issuanceFenceDigest(); + Arrays.fill(exposedRequestDigest, (byte) 0); + Arrays.fill(exposedResponseDigest, (byte) 0); + Arrays.fill(exposedCaptureDigest, (byte) 0); + Arrays.fill(exposedFenceDigest, (byte) 0); + + assertEquals(equalBinding, binding); + assertEquals(equalBinding.hashCode(), binding.hashCode()); + assertArrayEquals(digest(1), binding.requestDigest()); + assertArrayEquals(digest(2), binding.responseDigest()); + assertArrayEquals(digest(3), binding.authorityCaptureDigest()); + assertArrayEquals(digest(4), binding.issuanceFenceDigest()); + assertFalse(binding.toString().contains(ACCOUNT_ID)); + assertFalse(binding.toString().contains(TOKEN_HASH)); + assertFalse(binding.toString().contains("12".repeat(32))); + assertNotEquals( + binding, + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digest(2), + digest(3), + digest(5), + ISSUED_AT, + EXPIRES_AT)); + } + + @Test + void malformedIdentifiersDigestsHashesAndInstantsAreRejected() throws Exception { + byte[] responseDigest = digest(2); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + "B61A90BC-CDB4-42AC-9067-08667DE2AC84", + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + responseDigest, + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + "00000000-0000-0000-0000-000000000000", + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + responseDigest, + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + ACCOUNT_ID, + "not-a-uuid", + REQUEST_ID, + digest(1), + TOKEN_HASH, + responseDigest, + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + ACCOUNT_ID, + OPERATION_ID, + "not-a-uuid", + digest(1), + TOKEN_HASH, + responseDigest, + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + new byte[31], + TOKEN_HASH, + responseDigest, + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + "AB".repeat(32), + responseDigest, + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + responseDigest, + new byte[31], + digest(4), + ISSUED_AT, + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + responseDigest, + digest(3), + digest(4), + ISSUED_AT.plusNanos(1), + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + responseDigest, + digest(3), + digest(4), + Instant.ofEpochSecond(0), + EXPIRES_AT)); + assertThrows( + IllegalArgumentException.class, + () -> + binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + responseDigest, + digest(3), + digest(4), + EXPIRES_AT, + ISSUED_AT)); + } + + private void writeManifest(boolean includeControlUiPurpose) throws Exception { + List lines = new ArrayList<>(); + lines.add("version=1"); + lines.add("activeKeyId=k1"); + lines.add("key:k1:bare-login=" + encode(key(1))); + lines.add("key:k1:connect-token=" + encode(key(2))); + lines.add("key:k1:pending-reset=" + encode(key(3))); + if (includeControlUiPurpose) { + lines.add("key:k1:control-ui-response=" + encode(key(4))); + } + Files.writeString(manifestPath, String.join("\n", lines) + "\n", StandardCharsets.US_ASCII); + } + + private void writeRotatedManifest(boolean retainOriginalKey) throws Exception { + List lines = new ArrayList<>(); + lines.add("version=1"); + lines.add("activeKeyId=k2"); + if (retainOriginalKey) { + appendKeySet(lines, "k1", 1); + } + appendKeySet(lines, "k2", 5); + Files.writeString(manifestPath, String.join("\n", lines) + "\n", StandardCharsets.US_ASCII); + } + + private static void appendKeySet(List lines, String keyId, int firstKey) { + lines.add("key:" + keyId + ":bare-login=" + encode(key(firstKey))); + lines.add("key:" + keyId + ":connect-token=" + encode(key(firstKey + 1))); + lines.add("key:" + keyId + ":pending-reset=" + encode(key(firstKey + 2))); + lines.add("key:" + keyId + ":control-ui-response=" + encode(key(firstKey + 3))); + } + + private static AccountControlUiResponseEnvelopeBinding binding() throws Exception { + byte[] response = "the exact original control-ui response".getBytes(StandardCharsets.UTF_8); + return binding( + ACCOUNT_ID, + OPERATION_ID, + REQUEST_ID, + digest(1), + TOKEN_HASH, + digestFor(response), + digest(3), + digest(4), + ISSUED_AT, + EXPIRES_AT); + } + + private static AccountControlUiResponseEnvelopeBinding binding( + String accountId, + String operationId, + String requestId, + byte[] requestDigest, + String tokenHash, + byte[] responseDigest, + byte[] authorityCaptureDigest, + byte[] issuanceFenceDigest, + Instant issuedAt, + Instant expiresAt) { + return new AccountControlUiResponseEnvelopeBinding( + accountId, + operationId, + requestId, + requestDigest, + tokenHash, + responseDigest, + authorityCaptureDigest, + issuanceFenceDigest, + issuedAt, + expiresAt); + } + + private static AccountEnvelopeBinding connectBinding() { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + "connect-op-1", + "connect-request-1", + "account-17", + "tenant-a", + "connect-scope-a", + null, + digest(1), + digest(2), + digest(3), + digest(4), + digest(5)); + } + + private static void assertAuthenticationFailure( + AccountEnvelopeCrypto crypto, + AccountEncryptedEnvelope envelope, + AccountControlUiResponseEnvelopeBinding binding) { + assertFailure( + Failure.AUTHENTICATION_FAILED, () -> crypto.decryptControlUiResponse(envelope, binding)); + } + + private static void assertFailure(Failure expected, Runnable action) { + AccountEnvelopeCryptoException exception = + assertThrows(AccountEnvelopeCryptoException.class, action::run); + assertEquals(expected, exception.failure()); + } + + private static byte[] digest(int value) { + byte[] digest = new byte[32]; + Arrays.fill(digest, (byte) value); + return digest; + } + + private static byte[] digestFor(byte[] value) throws Exception { + return MessageDigest.getInstance("SHA-256").digest(value); + } + + private static String encode(byte[] key) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } + + private static byte[] key(int value) { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) value); + return key; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java index 8531750d36..b90ecc152f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -8,12 +8,15 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.LocalDateTime; import java.util.HexFormat; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -29,7 +32,10 @@ import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -302,6 +308,186 @@ void retainedReadRejectsChangedEventBytesAndMissingReceipts() { .hasMessageContaining("receipt does not match its source event"); } + @Test + void structuralSecurityStateSnapshotAcceptsCompleteCurrentAndRetainedEvents() { + Event original = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + AccountSourceSnapshot originalSnapshot = structuralSnapshot(original, 2L, 2L); + AccountSourceSnapshot newer = + structuralSnapshot(securityStateEvent(ACCOUNT_UUID, 2L, "3", "3"), 3L, 3L); + + assertThat(originalSnapshot.latestEvent()).contains(original); + assertThat(new AccountSourceEventReadback(newer, original).requestedEvent()) + .isEqualTo(original); + } + + @Test + void structuralSecurityStateSnapshotBindsEveryEventIndexAndCompleteCanonicalBytes() + throws Exception { + Event original = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + ObjectMapper json = new ObjectMapper(); + ObjectNode substituted = (ObjectNode) json.readTree(original.payload()); + ((ObjectNode) substituted.get("accountState")).put("emailVerified", false); + ObjectNode wrongScope = (ObjectNode) json.readTree(original.payload()); + wrongScope.put("sourceScope", "account/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + for (Event invalid : + List.of( + new Event( + original.outboxStreamKey(), + "33333333-3333-4333-8333-333333333333", + 1L, + original.eventId(), + original.eventDigest(), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 1L, + original.eventId() + "other", + original.eventDigest(), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 1L, + original.eventId(), + "sha256:" + "a".repeat(64), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 2L, + original.eventId(), + original.eventDigest(), + original.payload()), + withPayload(original, substituted.toString().getBytes(StandardCharsets.UTF_8)), + withPayload(original, wrongScope.toString().getBytes(StandardCharsets.UTF_8)), + withPayload( + original, + (" " + new String(original.payload(), StandardCharsets.UTF_8)) + .getBytes(StandardCharsets.UTF_8)))) { + assertThatThrownBy(() -> structuralSnapshot(invalid, 2L, 2L)) + .isInstanceOf(IllegalStateException.class); + } + Event foreign = + securityStateEvent(UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), 1L, "2", "2"); + assertThatThrownBy(() -> structuralSnapshot(foreign, 2L, 2L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void structuralSecurityStateCountersRequireCurrentEqualityAndRetainedNotAhead() { + Event generationMismatch = securityStateEvent(ACCOUNT_UUID, 1L, "3", "2"); + Event versionMismatch = securityStateEvent(ACCOUNT_UUID, 1L, "2", "3"); + Event arbitraryPrecision = + securityStateEvent(ACCOUNT_UUID, 1L, "922337203685477580812345678901234567890", "2"); + AccountSourceSnapshot current = + structuralSnapshot(securityStateEvent(ACCOUNT_UUID, 2L, "3", "3"), 3L, 3L); + for (Event invalid : List.of(generationMismatch, versionMismatch, arbitraryPrecision)) { + assertThatThrownBy(() -> structuralSnapshot(invalid, 2L, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("counters contradict or lead"); + } + assertThatThrownBy(() -> new AccountSourceEventReadback(current, arbitraryPrecision)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("counters contradict or lead"); + } + + @Test + void structurallyValidSecurityStateCannotPassOwnerCurrentOrHistoricalReceiptReadback() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + Event event = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + assertThat(structuralSnapshot(event, 2L, 2L).latestEvent()).contains(event); + when(outbox.readCheckpoint(event.outboxStreamKey())) + .thenReturn( + Optional.of( + new Checkpoint(event.outboxStreamKey(), 1L, event.eventId(), event.eventDigest()))); + when(outbox.findEvent(event.outboxStreamKey(), 1L)).thenReturn(Optional.of(event)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 2L, 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a valid declared password-reset or logout-all event"); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), event, accountState(3L, 3L, 3L, 3L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a valid declared password-reset or logout-all event"); + verifyNoInteractions(resets, logouts); + } + + private AccountSourceSnapshot structuralSnapshot( + Event event, long generation, long sourceVersion) { + return new AccountSourceSnapshot( + ACCOUNT_UUID, + accountState(generation, sourceVersion, 2L, 2L), + "account:auth-authority:v1:account/" + ACCOUNT_UUID, + event.outboxSequence(), + Optional.of(event)); + } + + private Event withPayload(Event original, byte[] payload) { + return new Event( + original.outboxStreamKey(), + original.requestId(), + original.outboxSequence(), + original.eventId(), + original.eventDigest(), + payload); + } + + private Event securityStateEvent( + UUID accountUuid, long sequence, String generation, String sourceVersion) { + String requestId = "11111111-1111-4111-8111-111111111111"; + String stream = "account:auth-authority:v1:account/" + accountUuid; + var event = + AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + stream, + "outboxSequence", + Long.toString(sequence))), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))); + return new Event( + stream, + requestId, + sequence, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()); + } + private void assertRejectedCheckpoint( AccountAuthoritySourceEventReadback readback, long generation, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java index 45381b6c0b..b0702a25ef 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java @@ -3,8 +3,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.math.BigInteger; import java.nio.charset.StandardCharsets; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -15,6 +18,7 @@ import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; import org.junit.jupiter.api.Test; @@ -109,8 +113,6 @@ void rejectsChangedEventCheckpointAndInvalidSequenceZeroRepresentations() { assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "3", "2", "1", Optional.of(event))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("declared closed schemas") - .cause() .hasMessageContaining("does not match"); assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "2", "2", "0", Optional.empty())) .isInstanceOf(IllegalArgumentException.class) @@ -131,6 +133,133 @@ void localIssuanceFenceIsNotSerializedOrComparedAsProjectionEvidence() { assertThat(first.toJson()).doesNotContain("issuanceFence"); } + @Test + void preservesTheCompleteSecurityStateEventWithTheOriginalProjectionSchema() { + String event = securityEvent(ACCOUNT_TEXT, "2", "2", "1"); + AccountGenerationProjection projection = + projection(ACCOUNT_TEXT, "2", "2", "1", Optional.of(event)); + + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.sourceEvent()).contains(event); + assertThat(projection.toJson()) + .startsWith("{\"schemaVersion\":\"account-auth-account-generation-projection/v1\""); + assertThat(projection.key()).isEqualTo("session:auth:generation:account:" + ACCOUNT_TEXT); + assertThat(projection.toJson()).doesNotContain("issuanceFence"); + } + + @Test + void securityStateCountersRetainArbitraryPrecisionThroughProjectionRoundtrip() { + String large = "18446744073709551616000000000000000001"; + String event = securityEvent(ACCOUNT_TEXT, large, large, large); + AccountGenerationProjection projection = + projection(ACCOUNT_TEXT, large, large, large, Optional.of(event)); + + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.generationValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.sourceVersionValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.outboxSequenceValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.sourceEvent()).contains(event); + } + + @Test + void securityStateRequiresExactAccountCountersAndCheckpoint() { + String event = securityEvent(ACCOUNT_TEXT, "2", "3", "4"); + String foreign = securityEvent("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", "2", "3", "4"); + for (AccountGenerationProjectionRequest request : + List.of( + new AccountGenerationProjectionRequest("3", "3", "4", event), + new AccountGenerationProjectionRequest("2", "4", "4", event), + new AccountGenerationProjectionRequest("2", "3", "5", event), + new AccountGenerationProjectionRequest("2", "3", "4", foreign))) { + assertThatThrownBy( + () -> + projection( + ACCOUNT_TEXT, + request.generation(), + request.sourceVersion(), + request.sequence(), + Optional.of(request.event()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match its current projection checkpoint"); + } + } + + @Test + void securityStateRejectsSubstitutedStateNoncanonicalBytesGenericSchemasAndFences() + throws Exception { + String event = securityEvent(ACCOUNT_TEXT, "2", "2", "1"); + ObjectMapper json = new ObjectMapper(); + ObjectNode changedState = (ObjectNode) json.readTree(event); + ((ObjectNode) changedState.get("accountState")).put("emailVerified", false); + ObjectNode generic = (ObjectNode) json.readTree(event); + generic.put("schemaVersion", "account-auth-authority-source-event/v1"); + ObjectNode fence = (ObjectNode) json.readTree(event); + fence.put("issuanceFence", "2"); + ObjectNode wrongStream = (ObjectNode) json.readTree(event); + wrongStream.put("outboxStreamKey", STREAM_KEY + "other"); + for (String invalid : + List.of( + changedState.toString(), + generic.toString(), + fence.toString(), + wrongStream.toString(), + " " + event, + event.replace( + "\"emailVerified\":true", "\"emailVerified\":true,\"emailVerified\":true"))) { + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "2", "2", "1", Optional.of(invalid))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "1", "1", "0", Optional.of(event))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + } + + private record AccountGenerationProjectionRequest( + String generation, String sourceVersion, String sequence, String event) {} + + private static String securityEvent( + String accountId, String generation, String sourceVersion, String sequence) { + String requestId = "11111111-1111-4111-8111-111111111111"; + String stream = "account:auth-authority:v1:account/" + accountId; + return AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountId), + Map.entry("sourceScope", "account/" + accountId), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + stream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))) + .canonicalJson(); + } + private static AccountGenerationProjection projection( String accountId, String generation, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStoreTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStoreTest.java index 216fbdae52..3751e6d9ae 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStoreTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStoreTest.java @@ -14,6 +14,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; @@ -26,6 +27,7 @@ import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.RedisAccountGenerationProjectionStore; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.data.redis.connection.RedisConnection; @@ -186,6 +188,44 @@ void sameCheckpointDisagreementFailsClosed() throws Exception { harness.store().close(); } + @Test + void completeSecurityStateSnapshotReplaysWithExactCanonicalBytes() throws Exception { + // Synthetic owner snapshot: this proves projection consumption, not receipt-backed SQL reads. + AccountSourceSnapshot source = source(2L, 2L, 1L, securityEvent(true), 2L); + AccountGenerationProjection projection = AccountGenerationProjection.fromSource(source); + FakeRedis redis = new FakeRedis(projection.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, source, source); + + var result = harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()).isEqualTo(RedisAccountGenerationProjectionStore.Outcome.REPLAYED); + assertThat(redis.lastMode).isEqualTo("VERIFY"); + assertThat(redis.bytes).isEqualTo(projection.toJson().getBytes(StandardCharsets.UTF_8)); + verify(harness.reader(), times(2)).readCurrent(ACCOUNT_ID); + harness.store().close(); + } + + @Test + void sameSecurityCheckpointWithResealedChangedStateIsQuarantinedWithoutWrite() throws Exception { + // Both events have valid digests and identical request/counters; complete payloads still + // differ. + AccountGenerationProjection stored = + AccountGenerationProjection.fromSource(source(2L, 2L, 1L, securityEvent(true), 2L)); + AccountSourceSnapshot changed = source(2L, 2L, 1L, securityEvent(false), 2L); + FakeRedis redis = new FakeRedis(stored.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, changed); + + var result = harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisAccountGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("SAME_CHECKPOINT_DISAGREEMENT"); + assertThat(redis.scriptCalls).isZero(); + assertThat(redis.bytes).isEqualTo(stored.toJson().getBytes(StandardCharsets.UTF_8)); + verify(harness.reader(), times(1)).readCurrent(ACCOUNT_ID); + harness.store().close(); + } + @Test void staleCasReturnsWithoutBlindRetry() throws Exception { AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); @@ -445,6 +485,54 @@ private static Event logoutEvent( evidence.canonicalJsonUtf8()); } + private static Event securityEvent(boolean emailVerified) { + String requestId = "11111111-1111-4111-8111-111111111111"; + var evidence = + AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", ACCOUNT_TEXT), + Map.entry("sourceScope", "account/" + ACCOUNT_TEXT), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", "1"), + Map.entry("accountAuthorityGeneration", "2"), + Map.entry("sourceVersion", "2"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + "2", + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + "1")), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + emailVerified, + "loginAuthModes", + List.of("PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))); + return new Event( + STREAM_KEY, + requestId, + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.canonicalJsonUtf8()); + } + private record Harness( RedisAccountGenerationProjectionStore store, AccountAuthoritySourceReader reader, diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java new file mode 100644 index 0000000000..c9ebc30d2f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java @@ -0,0 +1,391 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Closed source evidence for one Account-owned, non-password security-state mutation. */ +public final class AccountSecurityStateAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-account-security-state-event/v1"; + public static final String EVENT_TYPE = "ACCOUNT_SECURITY_STATE_CHANGED"; + public static final String EVENT_ID_PREFIX = "account-security-state-event-v1:"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff", + "mutationKinds", + "accountState"); + private static final Set WIRE_FIELDS; + private static final Set CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set STATE_FIELDS = + Set.of("emailVerified", "loginAuthModes", "globalRoles", "lifecycleState"); + private static final Set MUTATION_KINDS = + Set.of( + "EMAIL_LOGIN_ELIGIBILITY_CHANGED", + "LOGIN_AUTH_MODES_CHANGED", + "GLOBAL_ROLE_CHANGED", + "LIFECYCLE_STATE_CHANGED"); + private static final Set LOGIN_MODES = Set.of("EMAIL_OTP", "PASSWORD"); + private static final Set GLOBAL_ROLES = + Set.of("platformAdmin", "support", "billingAdmin"); + private static final Set LIFECYCLE_STATES = + Set.of("ACTIVE", "SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var fields = new java.util.HashSet<>(PREIMAGE_FIELDS); + fields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(fields); + } + + private AccountSecurityStateAuthorityEventV1Codec() {} + + /** Seals the complete declared preimage; caller authorization and receipt proof are separate. */ + public static AccountSecurityStateAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "event preimage is required"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event preimage must be an object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return evidence(wire, digest); + } + + /** Verifies the closed payload and digest, returning complete immutable canonical evidence. */ + public static AccountSecurityStateAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "event JSON is required"); + final JsonNode tree; + try { + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event must be an object"); + } + exactFields(wire, WIRE_FIELDS); + String supplied = text(wire, "eventDigest"); + if (!DIGEST_PATTERN.matcher(supplied).matches()) { + throw invalid("eventDigest must be canonical sha256 hexadecimal"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + if (!MessageDigest.isEqual( + supplied.getBytes(StandardCharsets.US_ASCII), + digest(preimage).getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest does not match the complete canonical preimage"); + } + return evidence(wire, supplied); + } + + private static void validatePreimage(ObjectNode event) { + exactFields(event, PREIMAGE_FIELDS); + equalText(event, "schemaVersion", SCHEMA_VERSION); + equalText(event, "eventType", EVENT_TYPE); + String requestId = uuid(event, "requestId"); + equalText(event, "eventId", EVENT_ID_PREFIX + requestId); + String scope = "account/" + uuid(event, "accountId"); + equalText(event, "sourceScope", scope); + equalText(event, "outboxStreamKey", EVENT_STREAM_PREFIX + scope); + positive(event, "outboxSequence"); + positive(event, "accountAuthorityGeneration"); + positive(event, "sourceVersion"); + ObjectNode cutoff = object(event, "accountSecurityCutoff"); + exactFields(cutoff, CUTOFF_FIELDS); + positive(cutoff, "accountAuthorityGeneration"); + positive(cutoff, "outboxSequence"); + for (String field : CUTOFF_FIELDS) { + equalText(cutoff, field, text(event, field)); + } + orderedValues(event.get("mutationKinds"), MUTATION_KINDS, "mutationKinds"); + ObjectNode state = object(event, "accountState"); + exactFields(state, STATE_FIELDS); + if (!state.get("emailVerified").isBoolean()) { + throw invalid("accountState.emailVerified must be a boolean"); + } + orderedValues(state.get("loginAuthModes"), LOGIN_MODES, "accountState.loginAuthModes"); + orderedValues(state.get("globalRoles"), GLOBAL_ROLES, "accountState.globalRoles", true); + if (!LIFECYCLE_STATES.contains(text(state, "lifecycleState"))) { + throw invalid("accountState.lifecycleState is unsupported"); + } + } + + private static List orderedValues(JsonNode array, Set allowed, String field) { + return orderedValues(array, allowed, field, false); + } + + private static List orderedValues( + JsonNode array, Set allowed, String field, boolean allowEmpty) { + if (array == null || !array.isArray() || (!allowEmpty && array.isEmpty())) { + throw invalid(field + " must be a declared array with supported cardinality"); + } + List values = new ArrayList<>(); + String previous = null; + for (JsonNode item : array) { + if (!item.isTextual() || !allowed.contains(item.textValue())) { + throw invalid(field + " contains an unsupported value"); + } + String value = item.textValue(); + if (previous != null && previous.compareTo(value) >= 0) { + throw invalid(field + " must be sorted and unique"); + } + values.add(value); + previous = value; + } + return List.copyOf(values); + } + + private static ObjectNode object(ObjectNode parent, String field) { + if (!(parent.get(field) instanceof ObjectNode value)) { + throw invalid(field + " must be a required object"); + } + return value; + } + + private static void exactFields(ObjectNode object, Set expected) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(expected)) { + throw invalid("object must contain exactly the declared fields"); + } + } + + private static String text(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(field + " must be a required string"); + } + return value.textValue(); + } + + private static void equalText(ObjectNode object, String field, String expected) { + if (!expected.equals(text(object, field))) { + throw invalid(field + " does not match its exact binding"); + } + } + + private static String uuid(ObjectNode object, String field) { + String value = text(object, field); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static void positive(ObjectNode object, String field) { + if (!POSITIVE_DECIMAL.matcher(text(object, field)).matches()) { + throw invalid(field + " must be a positive canonical decimal string"); + } + } + + private static String canonicalJson(ObjectNode object) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(object.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static String digest(ObjectNode object) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(canonicalJson(object).getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static AccountSecurityStateAuthorityEvent evidence(ObjectNode wire, String digest) { + ObjectNode state = object(wire, "accountState"); + ObjectNode cutoff = object(wire, "accountSecurityCutoff"); + return new AccountSecurityStateAuthorityEvent( + text(wire, "eventId"), + text(wire, "requestId"), + text(wire, "accountId"), + text(wire, "outboxStreamKey"), + text(wire, "outboxSequence"), + text(wire, "accountAuthorityGeneration"), + text(wire, "sourceVersion"), + new AccountSecurityCutoff( + text(cutoff, "accountAuthorityGeneration"), + text(cutoff, "outboxStreamKey"), + text(cutoff, "outboxSequence")), + orderedValues(wire.get("mutationKinds"), MUTATION_KINDS, "mutationKinds"), + new AccountState( + state.get("emailVerified").booleanValue(), + orderedValues(state.get("loginAuthModes"), LOGIN_MODES, "loginAuthModes"), + orderedValues(state.get("globalRoles"), GLOBAL_ROLES, "globalRoles", true), + text(state, "lifecycleState")), + digest, + canonicalJson(wire)); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} + + public record AccountState( + boolean emailVerified, + List loginAuthModes, + List globalRoles, + String lifecycleState) { + public AccountState { + loginAuthModes = List.copyOf(loginAuthModes); + globalRoles = List.copyOf(globalRoles); + } + } + + /** Immutable evidence constructible only by sealing or verifying this exact schema. */ + public static final class AccountSecurityStateAuthorityEvent { + private final String eventId; + private final String requestId; + private final String accountId; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final List mutationKinds; + private final AccountState accountState; + private final String eventDigest; + private final String canonicalJson; + + private AccountSecurityStateAuthorityEvent( + String eventId, + String requestId, + String accountId, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + List mutationKinds, + AccountState accountState, + String eventDigest, + String canonicalJson) { + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.mutationKinds = List.copyOf(mutationKinds); + this.accountState = accountState; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return SCHEMA_VERSION; + } + + public String eventType() { + return EVENT_TYPE; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return "account/" + accountId; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public List mutationKinds() { + return mutationKinds; + } + + public AccountState accountState() { + return accountState; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..146847ada6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java @@ -0,0 +1,327 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateAuthorityEventV1CodecTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + private static final String REQUEST = "22222222-2222-4222-8222-222222222222"; + private static final String STREAM = "account:auth-authority:v1:account/" + ACCOUNT; + private static final String DIGEST = + "sha256:6e6b82b81006e447301262b666825022462f4298a8b3fc0d44ce4a73895b3374"; + private static final String CANONICAL_PREIMAGE = + "{\"accountAuthorityGeneration\":\"2\",\"accountId\":\"" + + ACCOUNT + + "\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"2\"," + + "\"outboxSequence\":\"1\",\"outboxStreamKey\":\"" + + STREAM + + "\"},\"accountState\":{\"emailVerified\":true,\"globalRoles\":[]," + + "\"lifecycleState\":\"ACTIVE\",\"loginAuthModes\":[\"EMAIL_OTP\",\"PASSWORD\"]}," + + "\"eventId\":\"account-security-state-event-v1:" + + REQUEST + + "\",\"eventType\":\"ACCOUNT_SECURITY_STATE_CHANGED\"," + + "\"mutationKinds\":[\"EMAIL_LOGIN_ELIGIBILITY_CHANGED\",\"LOGIN_AUTH_MODES_CHANGED\"]," + + "\"outboxSequence\":\"1\",\"outboxStreamKey\":\"" + + STREAM + + "\",\"requestId\":\"" + + REQUEST + + "\",\"schemaVersion\":\"account-auth-account-security-state-event/v1\"," + + "\"sourceScope\":\"account/" + + ACCOUNT + + "\",\"sourceVersion\":\"2\"}"; + private static final String CANONICAL_WIRE = + CANONICAL_PREIMAGE.replace("\"eventId\":", "\"eventDigest\":\"" + DIGEST + "\",\"eventId\":"); + + @Test + void fixedCombinedFamilyVectorSealsAndVerifiesExactCanonicalBytesAndHash() throws Exception { + var sealed = seal(preimage()); + var verified = AccountSecurityStateAuthorityEventV1Codec.verify(CANONICAL_WIRE); + assertThat(sealed.eventDigest()).isEqualTo(DIGEST); + assertThat(sealed.canonicalJson()).isEqualTo(CANONICAL_WIRE); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(CANONICAL_WIRE.getBytes(StandardCharsets.UTF_8)); + assertThat(verified.accountId()).isEqualTo(ACCOUNT); + assertThat(verified.requestId()).isEqualTo(REQUEST); + assertThat(verified.sourceScope()).isEqualTo("account/" + ACCOUNT); + assertThat(verified.accountState().globalRoles()).isEmpty(); + assertThat(verified.mutationKinds()) + .containsExactly("EMAIL_LOGIN_ELIGIBILITY_CHANGED", "LOGIN_AUTH_MODES_CHANGED"); + assertThat(verified.accountSecurityCutoff().outboxSequence()).isEqualTo("1"); + } + + @Test + void positiveCountersBeyondLongArePreservedWithoutNumericConversion() throws Exception { + ObjectNode value = preimage(); + String huge = "18446744073709551616000000000000000001"; + value.put("accountAuthorityGeneration", huge); + value.put("sourceVersion", huge); + value.put("outboxSequence", huge); + cutoff(value).put("accountAuthorityGeneration", huge); + cutoff(value).put("outboxSequence", huge); + var sealed = seal(value); + var verified = AccountSecurityStateAuthorityEventV1Codec.verify(sealed.canonicalJson()); + assertThat(verified.accountAuthorityGeneration()).isEqualTo(huge); + assertThat(verified.sourceVersion()).isEqualTo(huge); + assertThat(verified.outboxSequence()).isEqualTo(huge); + assertThat(verified.accountSecurityCutoff().accountAuthorityGeneration()).isEqualTo(huge); + } + + @Test + void everyDeclaredRootAndNestedFieldIsRequiredAndBoundToOriginalDigest() throws Exception { + ObjectNode wire = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + for (String section : List.of("", "accountState", "accountSecurityCutoff")) { + ObjectNode sectionNode = section.isEmpty() ? wire : (ObjectNode) wire.get(section); + List fields = new ArrayList<>(); + sectionNode.fieldNames().forEachRemaining(fields::add); + for (String field : fields) { + ObjectNode missing = wire.deepCopy(); + node(missing, section).remove(field); + reject(missing); + ObjectNode changed = wire.deepCopy(); + node(changed, section).putNull(field); + reject(changed); + } + } + } + + @Test + void supportedSemanticChangesRequireNewDigest() throws Exception { + List> changes = + List.of( + value -> { + String request = "33333333-3333-4333-8333-333333333333"; + value.put("requestId", request); + value.put("eventId", "account-security-state-event-v1:" + request); + }, + value -> { + String account = "44444444-4444-4444-8444-444444444444"; + String stream = "account:auth-authority:v1:account/" + account; + value.put("accountId", account); + value.put("sourceScope", "account/" + account); + value.put("outboxStreamKey", stream); + cutoff(value).put("outboxStreamKey", stream); + }, + value -> { + value.put("accountAuthorityGeneration", "3"); + cutoff(value).put("accountAuthorityGeneration", "3"); + }, + value -> value.put("sourceVersion", "3"), + value -> { + value.put("outboxSequence", "2"); + cutoff(value).put("outboxSequence", "2"); + }, + value -> state(value).put("emailVerified", false), + value -> state(value).putArray("loginAuthModes").add("PASSWORD"), + value -> state(value).putArray("globalRoles").add("platformAdmin"), + value -> state(value).put("lifecycleState", "SECURITY_LOCKED"), + value -> value.putArray("mutationKinds").add("GLOBAL_ROLE_CHANGED")); + for (Consumer change : changes) { + ObjectNode changed = preimage(); + change.accept(changed); + var sealed = seal(changed); + assertThat(sealed.eventDigest()).isNotEqualTo(DIGEST); + changed.put("eventDigest", DIGEST); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(changed.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void undeclaredFencesSecretsAndScalarRolesAreRejectedAtEveryObjectBoundary() throws Exception { + ObjectNode wire = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + for (String section : List.of("", "accountState", "accountSecurityCutoff")) { + for (String extra : + List.of( + "issuanceFence", + "issuanceFenceSourceVersion", + "authorityTuple", + "passwordHash", + "password", + "globalRole", + "unknown")) { + ObjectNode changed = wire.deepCopy(); + node(changed, section).put(extra, "injected"); + reject(changed); + } + } + } + + @Test + void invalidCounterGrammarAndNumericAliasesAreRejected() throws Exception { + for (String section : List.of("", "accountSecurityCutoff")) { + List fields = + section.isEmpty() + ? List.of("accountAuthorityGeneration", "sourceVersion", "outboxSequence") + : List.of("accountAuthorityGeneration", "outboxSequence"); + for (String field : fields) { + for (String invalid : List.of("", "0", "01", "+1", "-1", "1.0", "1e2", " 1", "1 ")) { + ObjectNode changed = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + node(changed, section).put(field, invalid); + reject(changed); + } + ObjectNode numeric = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + node(numeric, section).put(field, 1); + reject(numeric); + } + } + } + + @Test + void unsupportedAndUnsortedDuplicateArraysAreRejectedBeforeSealing() throws Exception { + for (String field : List.of("mutationKinds", "loginAuthModes", "globalRoles")) { + String section = field.equals("mutationKinds") ? "" : "accountState"; + List> invalid = + switch (field) { + case "mutationKinds" -> + List.of( + List.of(), + List.of("PASSWORD_RESET"), + List.of("LOGOUT_ALL"), + List.of("GLOBAL_ROLE_CHANGED", "EMAIL_LOGIN_ELIGIBILITY_CHANGED"), + List.of("GLOBAL_ROLE_CHANGED", "GLOBAL_ROLE_CHANGED")); + case "loginAuthModes" -> + List.of( + List.of(), + List.of("password"), + List.of("PASSKEY"), + List.of("PASSWORD", "EMAIL_OTP"), + List.of("PASSWORD", "PASSWORD")); + default -> + List.of( + List.of("player"), + List.of("admin"), + List.of(""), + List.of("support", "platformAdmin"), + List.of("support", "support")); + }; + for (List values : invalid) { + ObjectNode changed = preimage(); + var array = node(changed, section).putArray(field); + values.forEach(array::add); + assertThatThrownBy(() -> seal(changed)).isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void exactPolicyVocabularyAndCombinedFamilySetAreSupported() throws Exception { + ObjectNode value = preimage(); + value + .putArray("mutationKinds") + .add("EMAIL_LOGIN_ELIGIBILITY_CHANGED") + .add("GLOBAL_ROLE_CHANGED") + .add("LIFECYCLE_STATE_CHANGED") + .add("LOGIN_AUTH_MODES_CHANGED"); + state(value).putArray("globalRoles").add("billingAdmin").add("platformAdmin").add("support"); + for (String lifecycle : + List.of("ACTIVE", "SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED")) { + state(value).put("lifecycleState", lifecycle); + assertThat(seal(value).mutationKinds()).hasSize(4); + } + for (String unsupported : List.of("active", "SUSPENDED", "")) { + state(value).put("lifecycleState", unsupported); + assertThatThrownBy(() -> seal(value)).isInstanceOf(IllegalArgumentException.class); + } + state(value).put("lifecycleState", "ACTIVE"); + state(value).put("emailVerified", "true"); + assertThatThrownBy(() -> seal(value)).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void wrongIdentitiesScopeCutoffAndDiscriminatorsAreDenied() throws Exception { + List> changes = + List.of( + value -> value.put("schemaVersion", "account-auth-authority-source-event/v1"), + value -> value.put("eventType", "PASSWORD_RESET_COMMITTED"), + value -> value.put("eventId", "account-security-state-event-v1:other"), + value -> value.put("requestId", "00000000-0000-0000-0000-000000000000"), + value -> value.put("accountId", "11111111-1111-4111-8111-11111111111A"), + value -> value.put("sourceScope", "issuer/other"), + value -> value.put("outboxStreamKey", STREAM + "other"), + value -> cutoff(value).put("outboxStreamKey", STREAM + "other"), + value -> cutoff(value).put("outboxSequence", "2"), + value -> cutoff(value).put("accountAuthorityGeneration", "3")); + for (Consumer change : changes) { + ObjectNode changed = preimage(); + change.accept(changed); + assertThatThrownBy(() -> seal(changed)).isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesTrailingTokensAndNonObjectsAreDenied() { + for (String invalid : + List.of( + CANONICAL_WIRE.replace( + "\"emailVerified\":true", "\"emailVerified\":true,\"emailVerified\":false"), + CANONICAL_WIRE.replace( + "\"sourceVersion\":\"2\"", "\"sourceVersion\":\"2\",\"sourceVersion\":\"2\""), + CANONICAL_WIRE + " {}", + "[]", + "null")) { + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void propertyReorderingCanonicalizesAndEvidenceDoesNotExposeMutableStorage() throws Exception { + ObjectNode reordered = JSON.createObjectNode(); + ObjectNode original = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + List fields = new ArrayList<>(); + original.fieldNames().forEachRemaining(fields::add); + java.util.Collections.reverse(fields); + fields.forEach(field -> reordered.set(field, original.get(field))); + var evidence = AccountSecurityStateAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(evidence.canonicalJson()).isEqualTo(CANONICAL_WIRE); + byte[] bytes = evidence.canonicalJsonUtf8(); + bytes[0] = 0; + assertThat(evidence.canonicalJsonUtf8()) + .isEqualTo(CANONICAL_WIRE.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> evidence.mutationKinds().add("GLOBAL_ROLE_CHANGED")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> evidence.accountState().loginAuthModes().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> evidence.accountState().globalRoles().add("support")) + .isInstanceOf(UnsupportedOperationException.class); + } + + private static ObjectNode preimage() throws Exception { + return (ObjectNode) JSON.readTree(CANONICAL_PREIMAGE); + } + + private static ObjectNode node(ObjectNode root, String section) { + return section.isEmpty() ? root : (ObjectNode) root.get(section); + } + + private static ObjectNode state(ObjectNode root) { + return node(root, "accountState"); + } + + private static ObjectNode cutoff(ObjectNode root) { + return node(root, "accountSecurityCutoff"); + } + + private static AccountSecurityStateAuthorityEventV1Codec.AccountSecurityStateAuthorityEvent seal( + ObjectNode value) { + Map fields = JSON.convertValue(value, new TypeReference<>() {}); + return AccountSecurityStateAuthorityEventV1Codec.seal(fields); + } + + private static void reject(ObjectNode value) { + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(value.toString())) + .isInstanceOf(IllegalArgumentException.class); + } +} From bfed931173c329df3591e09aa27d09635d6c047d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:26:56 +1300 Subject: [PATCH 3/3] Supply canonical saga schema to owner manifest PostgreSQL proof --- ...GameLogicRuleInputManifestPostgresIntegrationTest.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestPostgresIntegrationTest.java index c64c0889d0..a57148f823 100644 --- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestPostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/authoring/GameLogicRuleInputManifestPostgresIntegrationTest.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -55,7 +56,12 @@ static void initializeMigratedOwnerStorage() { dataSource.setURL(POSTGRES.getJdbcUrl()); dataSource.setUser(POSTGRES.getUsername()); dataSource.setPassword(POSTGRES.getPassword()); - Flyway.configure().dataSource(dataSource).locations("classpath:db/migration").load().migrate(); + Flyway.configure() + .dataSource(dataSource) + .placeholders(Map.of("serviceSchema", "public")) + .locations("classpath:db/migration") + .load() + .migrate(); transactionManager = new DataSourceTransactionManager(dataSource); dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); repository = new GameLogicRuleInputManifestRepository(dsl, transactionManager);