diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d2f54c8ffd..5915c778f2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -945,7 +944,7 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - if [[ "${{ matrix.module }}" == "account-service" || "${{ matrix.module }}" == "game-session-service" ]]; then + if [[ "${{ matrix.module }}" == "account-service" || "${{ matrix.module }}" == "game-session-service" || "${{ matrix.module }}" == "game-design-service" ]]; then ./gradlew :${{ matrix.module }}:check -PfullCheck --no-build-cache --no-configuration-cache else ./gradlew :${{ matrix.module }}:check -PfullCheck @@ -962,6 +961,7 @@ jobs: --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#canonicalExistingPairBoundPositiveMembershipSnapshotRepeatsWithoutMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#concurrentExactIssuanceClaimsHaveOneTerminalFirstWriter()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#lostIssuanceResponseRecoversExactEncryptedResultFromDurableReadback(Path)' \ @@ -980,13 +980,75 @@ jobs: account-service - name: 🔎 Verify Account committed connect source readback proof - if: ${{ matrix.module == 'account-service' }} + if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsExactCommittedOriginalSourceAndLostResultWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsFreshUuidCommittedSourceAndStoredHistoricalFrameWithoutMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsExpiredCommittedSourceOnlyThroughHistoricalEvidenceWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#historicalReadRejectsRequestTargetHashAndTokenIdentityMismatches()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#historicalReadRequiresCommittedSuccess()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#historicalReadRequiresRegisteredGatewayAndAccountSigningKeys()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsCommittedStoredFrameAndOriginalSourceAfterGatewayContextExpiryWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#storedHistoryRejectsChangedDigestSourceContextResultHashAndKey()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#correlatesExpiredOriginalFrameWithSeparateFreshCommittedSourceWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#correlationRejectsExpiredFreshContextAndReissuedContextForOriginalSource()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#correlationRequiresExactAccountTenantAndCompleteSelectedTarget()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#correlationRechecksFreshDeadlineAfterStoredFrameReadWait()' \ + account-service + + - name: Verify Account fresh tenant association PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationIntegrationTest#exactRetryReadbackGenerationInitializationAndImmutabilityStayAccountLocal()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationIntegrationTest#concurrentRetainedAndFreshUuidClaimsSerializeOnTheSharedPrimaryKey()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationIntegrationTest#generationFailureRollsBackFreshAssociationAndCanonicalClaim()' \ + account-service + + - name: Verify Game Design fresh tenant creation PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#createCandidateExactRetryReturnsCommittedReceiptWithoutSecondGameWrite()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#concurrentDuplicateCreationRequestsConvergeOnOneUuidAndReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#runtimeIdentityLookupReadsOnlyExactNewAndRetainedGameDesignRows()' \ + game-design-service + + - name: Verify Game Design authored-world source PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#registersAndReadsExactFreshAndRetainedV29ToV30Sources()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#concurrentExactRegistrationRetriesReturnOnePersistedReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#concurrentDifferentTenantsCannotClaimTheSameTenantSlug()' \ + game-design-service + + - name: Verify Account fresh UUID pair and snapshot PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepositoryIntegrationTest \ + --require-suite net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepositoryIntegrationTest#v39PreservesRetainedPairHistoryAndEnforcesUuidOnlyFreshRows()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepositoryIntegrationTest#v39RefusesToRewriteAnExistingFreshNumericPair()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#freshUuidSnapshotEnrollsExactNonAdmittingBaselineAndRetriesWithoutSideEffects()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#freshUuidSnapshotRejectsAdvancedTenantGenerationAndRollsBackBaselineWrites()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#concurrentFreshUuidSnapshotCallsInitializeOneExactPairBaseline()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#canonicalRuntimeReadUsesFreshUuidAssociationWithoutInventingRetainedAlias()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#canonicalRuntimeReadRejectsUnmappedTenantUuidWithoutEnrollment()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#strictExistingMembershipReadDeniesFreshAssociationWithoutEnrollmentOrMutation()' \ account-service - name: 🔎 Verify Game Session PostgreSQL proof case @@ -1069,7 +1131,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 1b16e25c92..e490961164 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -62,6 +62,8 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile GET/PUT now require the exact Social Groups peer and a non-internal caller subject matching the requested account; presence-policy batch reads require the exact Social Groups peer and read only tenant-scoped profiles. The account-ID export, external-link, and verification gRPC handlers deny before data access or mutation because no authorized caller contract exists. Runtime membership, grant, and entitlement methods deny before Account reads until typed player/target binding is available; these local guards are not complete admission proof. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. +Fresh-tenant identity adds no public Account endpoint or membership shortcut. The #2915 consumer uses Account's authenticated normal workload to read exact Game Design creation evidence, then commits an immutable canonical-UUID association and shared UUID conflict claim before using the existing no-reset tenant-generation initialization; it neither infers a retained numeric key nor admits a player. Exact #2915 head `910d0a6f41d60ee7214b610d56f89c51db260413` [CI 36796087279](https://github.com/benhook1013/FireMUD/actions/runs/36796087279) executed and passed all six Account fresh-association and seven Game Design creation PostgreSQL cases without skips, including retry, concurrency and rollback. This corrected component proof supersedes the earlier schema-fixture failure; it does not prove deployed workload identity, a live cross-owner handoff or activation. Detailed proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The Game Design wire and digest remain owned by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback), and Account's local storage/readback consequence is described in [Runtime & Data](./runtime-and-data.md). The membership RPC remains denied. + `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Account runtime membership, entitlement, and grant handlers intentionally deny before data access until typed caller/target binding is available. Game Session text `PLAY` retains lifecycle, authority-generation, membership-version, and evaluation-time validation; `JOIN_REQUIRED` is limited to confirmed eligible public-production membership that is missing or `INACTIVE` after fresh entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. This status does not claim a successful public `PLAY` or first-party browser `JOIN`, whose Gateway route remains denied and target-only. Account connect-token issuance still lacks replay-cache revalidation and the independent membership-version/authority-generation issuance reread; full grant/entitlement admission, PostgreSQL/recovery, and end-to-end proof remain open. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the target browser connect-token body and OpenAPI response are metadata-only with raw token delivery only in the HttpOnly cookie. The current `ConnectTokenResponse` is metadata-only and exposes neither internal `jti` nor the raw token. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 42638fa1ee..8ded38ce4f 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -28,7 +28,13 @@ Account V29 keeps the numeric `accounts.id` primary key and adds an immutable ca The current Unit 1B authority and membership candidates build on distinct migrations: V31 positive authority-generation rows and an Account-local issuance fence; V32 membership role snapshots; V33 immutable, independently sequenced authority events; V34 retained Account authority enrollment; V35 connect-token issuance/envelope storage; and V36 durable authority for verified Account/tenant pairs. The v1 event preserves the exact one-tenant `membershipVersion` map, complete committed event and role evidence, and immutable history; a producer may derive a local numeric value only after validating the canonical map. A never-joined pair may expose a positive version/generation baseline at sequence zero only after same-fence provenance and row/receipt/event absence proof, and that baseline never admits gameplay. JOIN advances version and event sequence from the baseline, advances generation only when caller-bound authority was invalidated, and commits membership, role snapshot, event, receipt, audit, and terminal operation evidence together. Retained positive history is never renumbered; inactive reactivation remains denied without the exact current INACTIVE event and writer. Runtime RPCs, event delivery/projections, Game Session consumption, fresh-tenant UUID handoff, old-issuer fencing, and complete token issuance remain unproved. Detailed capability status belongs in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). -The local AES-256-GCM response-envelope primitive and V35 issuance/envelope storage candidate are not wired into production issuance. The offline materializer simulations, per-access principal checks, and local receipt verifier do not authenticate target-cluster identity or prove Secret delivery. Real Kubernetes operations remain denied until the [canonical target-cluster binding gate](../../infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding), protected custody, trusted writer, deployment readback, and readiness proof are implemented. An unavailable key or uncertain result never authorizes reminting. +The fresh-tenant Account consumer is a UUID-only owner boundary, separate from retained-manifest import and membership authority. The Account normal workload authenticates to Game Design's `ResolveFreshTenantCreation` read, verifies the closed operation-bound request, digest, source, and receipt evidence, then stores an immutable canonical-UUID association under a claim index shared with retained associations; that index rejects conflicts regardless of which evidence path arrives first. Unknown response fields fail closed rather than extending this evidence implicitly. Only after exact source readback may Account commit the association and invoke existing tenant-generation initialization without resetting existing state. Both the fresh-source client and the distinct retained-association client require file-backed workload mTLS and the configured workload namespace; before accepting response content they verify the exact Game Design server workload URI under the [cross-service trust owner](../../system-architecture-security.md#cross-service-trust), not merely a trusted CA or DNS name. Missing, ambiguous, another-service or cross-namespace server identity denies the read. The #2915 source and association components now have passing focused PostgreSQL proof, with the limits recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md); mocked client and local TLS construction are not live authenticated handoff or activation proof. They create no numeric Account tenant alias or selector and enable no runtime path. The identity direction is owned by [Multi-Tenancy](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge), and Game Design's evidence contract by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback). + +The V38.1 candidate adds the immutable fresh UUID association without a numeric tenant alias. V39 extends the existing pair authority table for that UUID-only association: a fresh pair has no legacy numeric tenant key, while an approved retained pair keeps its positive one-to-one bridge unchanged. Contradictory preexisting fresh numeric keys abort migration without reinterpretation or deletion. A fenced fresh-UUID producer reads back the exact immutable association and constructs the existing complete, nonadmitting never-joined snapshot from its positive pair baseline and pristine upstream authority. It does not create membership or event history, support fresh positive JOIN, reset progressed authority, or enable the runtime RPC; canonical request propagation, advanced source-event support and their producer/consumer proof remain open in the tracker. + +V35 and the bare-LOGIN migration now named V37.1 retain their originally published numeric storage definitions. V39.1 permits the UUID storage-shape transition only when the entire operation/envelope table set is locked and empty; retained evidence blocks unchanged pending separate Account-owned audited recovery, never an inferred identity mapping. Old-writer quiescence, exact database proof and activation limits are recorded in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). + +The local AES-256-GCM response-envelope primitive and V35 issuance/envelope storage candidate are not wired into production issuance. Offline materializer simulations, per-access principal checks, and local receipt verification do not authenticate target-cluster identity or prove Secret delivery. Real Kubernetes operations remain denied until the [canonical target-cluster binding gate](../../infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding), protected custody, trusted writer, deployment readback, and readiness proof are implemented. An unavailable key or uncertain result never authorizes reminting. Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Six focused unit cases in `ExpiredCredentialCleanupJobTest` executed locally; seven PostgreSQL integration cases in `CredentialCleanupRepositoryIntegrationTest` passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. @@ -40,9 +46,9 @@ Current Account membership, entitlement, and grant runtime handlers fail `FAILED The current cached-success connect-token path rechecks current public-target eligibility, membership lifecycle/admission, and entitlement before failing with retryable `AUTH_UNAVAILABLE` when complete selected-target evidence is unavailable; it does not return the cached success. Fresh success likewise remains denied until the independent same-snapshot membership map/generation/issuance-fence proof and durable registry-backed issuance exist. This guard is not a complete Account-signed `gameplay-connect` producer or live path. -The unwired Account source reader retrieves the original successful V35 issuance and purpose-bound encrypted envelope under the row fence. It verifies the original token hash/signature/profile, independently signed Gateway context, exact Game Session peer, approved UUID/tenant mapping, source-context correspondence, and unchanged deadlines after fence waits. It returns source evidence only—not a credential or proof of current authority, registry readiness, or admission—and is not wired as a producer or RPC. Protected key delivery, fresh tenant handoff, current-authority/registry proof, and the complete exchange remain activation gates; see [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +The unwired Account component reads an original successful V35 connect-issuance operation and its exact purpose-bound encrypted response envelope under the Account row fence. Its local successful-envelope payload is the strict UTF-8 compact Account JWT, not a reconstructed token or a second credential. It verifies the independently signed Gateway context, the exact Game Session workload identity, Account UUID provenance and the exact canonical tenant association, the stored token hash and identity, the original Account signature/profile, and complete original source/context correspondence. Fresh tenant provenance comes only from the immutable V38.1 owner association; retained tenant provenance comes only from the approved bridge and current retained-source digest. Neither path infers a numeric tenant alias. It rechecks the unchanged source and context deadlines after any fence wait. Its immutable result is original-source evidence only: stored authority/postcondition digest binding is not proof of current authority, registry readiness, or admission. This component is not registered as a runtime credential producer or RPC handler; live fresh tenant handoff, complete Account-authenticated evidence, current-authority and registry consumption, protected key delivery, and end-to-end exchange remain separate activation gates. Focused proof status is recorded in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). -The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. The membership request now carries typed `PlayerExecutionContext`, and Game Session sends that typed context; Account's handler still denies before producer/data access with `FAILED_PRECONDITION`. The held-back candidate producer/consumer path remains incomplete, so this typed request is not a working admission path or proof of the target membership/entitlement snapshot. The entitlement and realm-grant reads retain their local request shapes and must likewise remain denied until their exact caller/target contracts are carried and verified. +The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. The membership request carries typed `PlayerExecutionContext` with exact canonical Account/tenant UUIDs rather than private numeric row keys. Its held-back encoder validates the canonical selected target and exact identity echoes; the unwired producer resolves fresh UUIDs only through V38.1 evidence and retained UUIDs through the approved association and current source digest under the Account fence. Game Session rejects invalid Account/tenant UUID selectors before making the call. Account's handler still denies before producer/data access with `FAILED_PRECONDITION`: the canonical session/catalog handoff and authenticated complete producer/consumer proof remain incomplete. This typed request is not a working admission path. The entitlement and realm-grant reads retain their local request shapes and likewise remain denied until their exact caller/target contracts are carried and verified. Detailed proof and activation gates remain in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). The unwired Account snapshot reader builds a one-tenant version map, four ordered checkpoints, and separate positive source-event evidence from one fenced transaction. Sequence zero is allowed only with same-fence positive absence/provenance and baseline checks; advanced upstream history without its event proof fails closed, and the account-local issuance fence is preserved. This is a component, not an authenticated gRPC response or admission path. @@ -170,7 +176,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - It establishes account identity for first-party gameplay bootstrap only. The target creates public-game membership only through explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` require existing membership and the selected target's grants, entitlements, and admission checks. Current Account connect-token issuance and character discovery return non-actionable `JOIN_REQUIRED` only for missing or explicit `INACTIVE` membership on an eligible public-production target; an existing non-admitting membership is rejected. These paths do not create or restore membership. Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only fresh `MISSING`/`INACTIVE` membership can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account runtime readers still fail closed before reads, so this local classification does not prove a composed outcome; canonical eligibility and remaining outcome mapping belong to [Authentication](../../system-architecture-authentication.md). World and realm discovery remain available before membership. The Account JOIN writer/controller and direct text `JOIN` dispatch exist locally, but the Gateway guard blocks external route exposure and first-party `Join & Play` remains unavailable. Durable recovery after an unknown database commit outcome remains open. Non-public targets remain subject to their realm-access and grant checks rather than public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. -- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The V37.1 storage candidate binds an exchange to a committed V35 connect operation and stores an immutable purpose-bound terminal envelope, but neither operation is wired to credential issuance or recovery. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish the complete proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. +- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The V37.1 storage candidate binds an exchange to a committed V35 connect operation and stores an immutable purpose-bound terminal envelope, but neither operation is wired to credential issuance or recovery. The selected expired-context terminal-recovery contract is owned by [Authentication](../../system-architecture-authentication.md#terminal-bare-login-result-recovery-normative); it is unimplemented and unproved. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish the complete proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. - It is backed by one `session:auth:token:` record so per-token logout and account-level revocation semantics remain consistent. - `POST /auth/logout` and `POST /auth/logout-all` must accept this profile so first-party gameplay UIs can explicitly revoke bootstrap capability on sign-out rather than waiting for expiry. @@ -209,7 +215,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before a snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The current response proto carries string-map `membershipVersion`, opaque string `membershipAuthorityGeneration`, lifecycle, baseline, complete authority tuple, issuance fence, ordered checkpoints, source-event evidence, roles, and echoes; `authorityAvailability` remains a target requirement not declared in the proto. The live Account handler still rejects before data access. Game Session's supplied-authority `PLAY` validates the complete held-back candidate carrier, including roles, tuple/checkpoint/event content and digest/response agreement. These local checks do not prove a live Account snapshot or admission. Account issuance still lacks the independent same-snapshot map/generation/fence comparison and durable registry proof; entitlement consumers remain partial. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). +- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before a snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The current response proto carries string-map `membershipVersion`, opaque string `membershipAuthorityGeneration`, lifecycle, baseline, complete authority tuple, issuance fence, ordered checkpoints, source-event evidence, roles, and identity echoes; `authorityAvailability` remains a target requirement not declared in the proto. Game Session's supplied-authority `PLAY` validates the complete held-back response carrier, including roles, tuple/checkpoint/event content and digest/response agreement. These local checks do not prove a live Account snapshot or admission. The live Account handler still rejects before data access; Account issuance still lacks the independent same-snapshot map/generation/fence comparison and durable registry proof, and entitlement consumers remain partial. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. @@ -251,12 +257,18 @@ Runtime caller contract: ### Connect-token issuance persistence and retention +The exact tenant identity in connect issuance, bare-`LOGIN` exchange, operation readback and envelope authentication is the canonical non-nil tenant UUID. A numeric Account primary key may remain private row/fence provenance after Account proves its exact immutable account UUID; it is not a public account identifier. Fresh tenant associations have no numeric tenant alias. Retained tenant keys participate only through their approved one-to-one bridge, not as an alternative operation identity or ciphertext binding. The unactivated V35/V37.1 candidates converge directly on this tenant-UUID shape before deployment; no deployed ciphertext, AAD, retained operation or history may be silently rewritten to change identity. Storage/readback component proof does not enable issuance or exchange, and exact recovery preserves the original credential, signed context and expiry. + The target Account persistence shape is not current implementation: one Account-schema `connect_token_issuance_operation` record owns the exact `(accountId, tenantId, connectScopeId, requestId)` identity, Account-computed versioned request digest, lifecycle (`PENDING`, `COMMITTED`, deterministic `FAILED`, or `ABORTED`), token identity/hash and authority/postcondition evidence, and reconciliation metadata; it never stores a raw JWT. A separate bounded `connect_token_response_envelope` record is keyed to that operation and stores the exact success credential or deterministic failure only as an Account-encrypted envelope with its key/version and authenticated binding to the operation identity, digest, authority tuple, Account-local issuance CAS fence, and applicable postconditions. That Account-local fence serializes the durable operation; it is not an `issuanceFence` claim in the `gameplay-connect` token or a substitute for Gateway's distinct `replayAdmissionFence`. Both records are Account-owned service-schema objects introduced and accessed through the service-local Flyway/jOOQ lineage; Redis remains only the reset-sensitive exact-result projection/cache. Account owns one versioned, mounted-secret key ring and rotation procedure for both connect-token issuance and bare first-party `LOGIN` response envelopes. The ring contains distinct AEAD keys for the two purposes; an envelope records its purpose and key ID, and a key for one purpose must never decrypt the other. These encryption keys are separate from JWT signing and request-digest keys. New envelopes use the current write key for their purpose. Rotation makes older keys decrypt-only, and Account retains each old key until no retained envelope requiring exact-result recovery references it; removal is an evidence-backed cleanup decision, not a fixed timer. Decryption authenticates the exact durable operation identity, request digest and applicable authority/postcondition binding. Recovery first reads back that operation and its exact envelope, then checks the recorded purpose, key ID and binding before returning the original result. A missing key, failed authentication, missing or mismatched operation or envelope, or binding mismatch fails closed and never mints a replacement credential. Neither envelope purpose is enabled until rotation, wrong-purpose and wrong-operation rejection, and lost-response recovery are proved for its producer and consumer. The operation identity is claimed by a serializable transaction or equivalent Account-owned CAS: one matching digest wins, a concurrent matching request waits for and reads the same operation, and any changed digest returns `IDEMPOTENCY_CONFLICT` without minting or mutating. Account records the durable operation before exposing a result, accepts and reads back the required registry/admission postconditions before `COMMITTED`, and exact retries revalidate current authority and all applicable registry/admission postconditions before decrypting and returning a successful credential envelope. If that revalidation fails, the retry returns the applicable canonical denial and leaves the committed operation and envelope unchanged; it does not remint or replace the credential. A deterministic `FAILED` result, such as `JOIN_REQUIRED`, replays its stored failure envelope directly after the exact operation identity and digest match, without rerunning authority or membership checks, while that failure envelope remains retained. If the matching compact receipt remains after its response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`; a changed digest still returns `IDEMPOTENCY_CONFLICT`. That outcome is terminal for the original issuance attempt and callers must use a new `requestId` for a fresh authorized request. Missing, ambiguous, or unreconciled durable state fails closed; no retry reconstructs or silently remints a JWT. The response envelope must not be removed while the operation is pending, ambiguous, or otherwise blocked on reconciliation. This target persistence/CAS/readback path is unimplemented and must not be inferred from the current Redis map. +For the Authentication-owned [terminal bare-`LOGIN` result-recovery exception](../../system-architecture-authentication.md#terminal-bare-login-result-recovery-normative), Account retains the original signed Gateway context bytes encrypted with the exact original result under the existing `BARE_LOGIN_RESPONSE` purpose and unchanged operation binding. The operation row stores no raw JWT or context bytes. Its local `BareLoginRecoveryPayload` uses one closed versioned, byte-length-framed representation within the existing envelope plaintext bound; it preserves context and opaque result bytes without normalization and introduces no additional key purpose. Envelope reads must verify the exact committed operation, request/source/context evidence, purpose and key before decoding. The shared history-only Gateway evidence type is distinct from current authorization and never substitutes into a current-context API. Original result expiry and a separately declared recovery horizon remain mandatory Account checks; neither is inferred from `created_at` or extended. The complete fresh-proof, authority and postcondition requirements remain at Authentication's owner. The unwired Account source reader has separate strict-current and history-only methods: the latter checks an exact committed V35 source against the supplied signed historical Gateway assertion and returns immutable, non-authorizing evidence. It does not establish that V37.1 retained that assertion or that Gateway accepted it. The actual V37.1 producer does not yet persist the frame, and current-authority/registry/recovery composition and complete canonical-UUID request wiring remain open in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). No fixed TTL, new public route or runtime enablement is selected. + +The unwired `AccountStoredBareLoginRecoveryReader` reads an exact committed V37.1 operation and purpose-bound encrypted frame under the Account fence, verifies the opaque result hash and stored signed context against its exact committed V35 source, and returns only immutable, redacted provenance facts. Its separate correlation read first verifies a distinct strict-current committed connect source and signed Gateway context, then exact-compares the original and fresh canonical player, tenant and complete selected target, including conditional lifecycle/generation. A final unchanged strict-source read rechecks deadlines after historical work; original/fresh operation identities, requests, scope hashes and timestamps remain separate evidence rather than being rewritten. Stored historical Gateway expiry is the signed context's `expiresAt`, not the source token's potentially later `exp`. This is non-authorizing correspondence only: it does not return the context or result, establish past Gateway acceptance, verify the original result JWT/expiry or recovery horizon, compare the producer's complete context/authority/postcondition evidence, or authorize recovery. Detailed component proof and the remaining producer/composition gates are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + The target projection is physically isolated from the legacy map: `session:connect-token:v1:tenant::account::scope::request:` is target-only, while the unversioned family remains legacy-only. Because the legacy writer has no issuance fence, cutover requires closing issuance for the full Account cohort, stopping legacy writers, draining in-flight requests, waiting the configured maximum legacy TTL/retry horizon, and verifying that no legacy writer remains before enabling target issuance. A mixed-version rollout is not permitted unless every writer first honors a shared owner fence. Legacy entries are retained read-only through the TTL/retry horizon, then Account performs owner cleanup from an exact inventory with readback; they are not migrated, promoted, or interpreted as target envelopes. Region/tenant reset preservation follows the reset matrix for both families; after a cluster/cold-start loss, exact durable target repair/readback is required and otherwise the handshake fails closed. Under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md), the operation is an Account-owned **retry and idempotency receipt** class. `PENDING`, `ABORTED` with unresolved reconciliation, and any row with a live registry/admission/postcondition blocker are nonterminal and retained; `COMMITTED` and deterministic `FAILED` become eligible only after the complete supported client, producer, duplicate-delivery, reconnect, reset-recovery, and audit-read window ends. The minimum horizon is the greatest applicable connect-scope, response-envelope, client/internal retry, recovery, and legal/governance horizon, with no universal duration assumed. Account-owned bounded cleanup records holds and blocker reason, never deletes held or nonterminal rows, and removes the encrypted credential-bearing response envelope only after its declared response-recovery horizon while retaining the compact receipt through the deduplication horizon. A matching duplicate after envelope removal but before receipt expiry returns `RESPONSE_RECOVERY_EXPIRED`; exact digest comparison remains mandatory, changed input remains `IDEMPOTENCY_CONFLICT`, and no replacement credential is minted. A retained deterministic `FAILED` envelope continues to replay its exact failure; after that envelope is removed, the same recovery-expired outcome applies. Callers treat `RESPONSE_RECOVERY_EXPIRED` as terminal for the original issuance attempt and start a fresh authorized request under a new `requestId`. Cleanup never removes an envelope while the operation is pending, ambiguous, or blocked on unresolved reconciliation. Account exposes oldest-blocking-row and cleanup-lag metrics. Partition/drop or row deletion requires the same terminal, reference, hold, and safe-watermark checks as the shared retention contract. diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 0f1ce4f0d3..0c2d464e6d 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -16,6 +16,8 @@ Authoritative read surfaces worth wiring into creator/operator tooling: Current capability and proof gaps remain: Game Session's exact pin/epoch persistence and convergence, plus its append-only rollout-history append/readback, are partial and unproved; Game Design plugin publication currently uses the signed-only intake path and exposes one allowlisted `signerKeyId` rather than the target complete `verifiedSignatures[]` set. The ADR 0111 operator-permitted unsigned provenance path remains unimplemented. Draft commit coordination, owner-local compare-and-swap, and the synchronized read fence in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) are also target-state and unproved. The official-hosted creator mutation gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and changed-term continuity in [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) are also target-only: no Account evidence check, stale-write classification, or durable tenant/evidence binding is implemented or proved. The target 25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer for asset uploads are not implemented or proved, because `GameAssetServiceImpl` uses `MultipartFile.getBytes()` without matching limits in `AssetStoreProperties`; upload admission and resource-safety readiness remain blocked. The service exposes only the creator `POST /assets` path, with no public asset `GET`/download route. Publish/export later writes version-prefix objects and a manifest through the private object-store endpoint; target private-candidate/content-addressed publication and approved public `/assets/**` delivery remain unimplemented. Public `PublishVersion` fails with `PUBLISH_WORKFLOW_UNAVAILABLE` when the Temporal orchestrator is absent; its publish command/readback callbacks are workflow internals, not a synchronous public fallback. Current asset repair, lifecycle CAS, and release-attestation gaps are recorded in [Asset Storage](./asset-storage.md), and the following target-state script-patch and release-bundle descriptions are not current implementation proof. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status), [modding-framework.md](./modding-framework.md), [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0128](../../decisions/adr-0128-game-design-plugin-trust-provenance.md). +Tenant identity status is narrower: V30 gives each `game` row an opaque canonical UUID with immutable source-row/key provenance, and the repository verifies that persisted UUID on insert. The #2915 Account-consumer extension remains in progress; historical creation and Account-association database component proof does not establish a current-head run, live mTLS/SPIFFE handoff, production creator caller, or runtime capability. The 255-Unicode-code-point description limit remains bounded to the unchanged `game.description VARCHAR(255)` column. See the [API contract](./api-contracts.md#fresh-tenant-creation-operation-and-account-readback) for the canonical wire/digest rules and the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for exact proof scope and remaining gaps. + ## Responsibilities - Provide REST/gRPC tools and a web UI for editing game assets. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index f340bc16a2..325e80b8c7 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -10,11 +10,49 @@ For REST endpoints, the authoritative request/response schema source is [openapi Game Design is the canonical issuer of opaque UUID `tenantId` values and the owner of stable `tenantSlug` selectors under [Multi-Tenancy](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge). A retained Game Design game row may receive a UUID with exact owner-local provenance naming its row and former `game.tenant_id`; that binding is immutable and read back exactly. A newly created tenant receives a fresh persisted UUID rather than a numeric-key conversion. Selector assignment is explicit and unique; a game name, row key, former tenant string, or guessed slug is not a selector. Resolving a selector requires the current authoritative binding and does not authorize the caller by itself. -The fresh-tenant Account handoff is distinct from both retained-key reads below. Game Design must durably bind the exact creation request to its issued UUID and return authenticated operation-bound creation/readback evidence to Account under the [canonical identity contract](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge). The current tenant-identity proto has no such method, and the current new-game repository path has no stable creation operation identity; neither the smoke seeder nor a legacy-manifest read supplies this handoff. +The fresh-tenant Account handoff is distinct from both retained-key reads below. Game Design must durably bind the exact creation request to its issued UUID and return authenticated operation-bound creation/readback evidence to Account under the [canonical identity contract](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge). The smoke seeder and a legacy-manifest read do not supply this handoff. The owner-local operation/readback contract is specified below; executed database component proof and the remaining product-caller and live handoff gates are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). No production creation caller or Account handoff is enabled. The separate `TenantIdentityService.ResolveLegacyGameTenantIdentity` read is limited to the verified Account workload peer. It accepts only an exact former Game Design tenant key and returns the persisted UUID, source key, source game row, and provenance kind together. A missing source returns `NOT_FOUND`; malformed input, missing peer, changed provenance, and ambiguous owner data fail closed before returning content. This read does **not** attest that an Account-retained numeric tenant key has the same identity as a numerically similar Game Design key. The separate `ResolveLegacyAccountTenantAssociation` read returns that cross-owner association only when a signed, owner-approved migration manifest has been applied and its exact source tuple still reads back. It is limited to the verified, same-namespace `account-tenant-migrator` workload identity; ordinary Account and other service peers are denied. It returns the immutable operation, approval, signature, digest, and retained-source evidence with the mapping, and denies absent or contradictory rows. Account's own retained-row verification and mapping readback are still required before it may use the UUID, and neither read itself grants membership admission. The [multi-tenancy identity bridge](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge) owns the target contract; [Game Design operations](./operations.md#legacy-tenant-association-migration) records the controlled migration sequence and current proof limits. -**Implementation status:** Current Game Design data does not include a stable tenant slug, a normal operation-bound fresh-tenant handoff to Account, or a proved cross-owner Account legacy-key association, and no current player-facing selector resolution is claimed. The owner-local UUID source/read is a bounded prerequisite; it does not make the Account runtime membership snapshot RPC safe to enable. Live retained-row migration, mounted-certificate acceptance, and Account/Game Session consumer proof must be reported separately from schema and unit tests. +**Implementation status:** Authored-world selector registration is an owner-local candidate with authenticated source readback, not a protected product creator or deployed runtime catalog intake; no current player-facing selector resolution is claimed. The fresh-creation and Account-association components have executed PostgreSQL proof, separately scoped in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md); that does not prove a live product caller or deployed handoff. Source and selector components do not establish a proved deployed cross-owner legacy-key association, catalog enrollment or admission. Retained-row migration, mounted-certificate acceptance, full Account/Game Session authority and live caller/consumer proof remain separate gates; the membership RPC and credential paths remain disabled. + +### Runtime tenant identity read for Game Session + +`TenantIdentityService.ResolveRuntimeTenantIdentity` supplies Game Design's persisted tenant identity to Game Session, which remains the [sole runtime realm-catalog and admission-pointer resolver/persister](../game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). This read neither creates a tenant nor allocates or changes a realm, namespace, catalog or pointer. It does not replace Account's creation-operation readback or the approved retained Account association. + +The request carries canonical non-nil UUIDs `canonical_tenant_id` and `request_id`. The closed version-1 response carries `schema_version`, `target_namespace`, the exact `request_id` and `canonical_tenant_id`, positive `source_game_row_id`, exact `source_game_tenant_key` and `provenance_kind` (`NEW_GAME_ROW` or `RETAINED_GAME_V30`). The source key and row are private Game Design provenance, not selectors or assertions about any Account or Game Session numeric key. The repository uniquely reads the actual canonical-UUID row and verifies its provenance against that same row and source key; missing, ambiguous, changed or contradictory identity fails closed without mutation. + +Only the verified peer `spiffe://firemud/ns/{configured_namespace}/sa/game-session-service` may read this method. The exact peer check precedes data access, and any bearer bypass is limited to this method; a JWT service claim, another workload or another namespace cannot substitute. Existing Account-only creation and migration method guards are unchanged. The Game Session consumer requires file-backed workload mTLS, validates the closed evidence and exact namespace/request/tenant echoes, and rejects aliases or incomplete evidence before using it. This proves owner identity provenance only, not a membership grant, Account authority, World lifecycle, selected-target readiness or admission. Runtime catalog intake must separately persist and read back the association at Game Session's owner boundary; missing provenance and unmapped retained runtime rows remain denied rather than deriving UUIDs from numeric IDs. + +**Runtime tenant-read proof:** Exact #2920 `728a0dd09982506e801e21f6154bec420548984a` [CI 36812079812](https://github.com/benhook1013/FireMUD/actions/runs/36812079812) executed and passed all eight creation/runtime-source PostgreSQL cases without skips, including exact fresh/retained lookup after real migration and no-mutation readback. This is owner database proof, not a deployed Game Session client, retained Game Session association, authored-world enrollment or catalog activation; remaining proof belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + +### Authored-world source registration and Game Session readback + +Game Design owns a persisted authored-world selector source; Game Session consumes its authenticated readback and remains the sole runtime catalog writer. A Game Design owner transaction binds the existing canonical tenant identity and exact source-game provenance to separately supplied stable `tenantSlug` and tenant-scoped `worldSlug` values. Neither selector is inferred from a display name, template, numeric key, realm slug or runtime instance. A template or launch descriptor is not itself an authored-world identity. This source is selector provenance, not a content-version release, realm policy, membership grant, selected runtime or admission permission. + +The closed `game-design-authored-world-source/v1` evidence contains `schemaVersion=1`, `targetNamespace`, canonical non-nil `registrationRequestId`, canonical non-nil owner `operationId`, `requestDigest`, canonical non-nil `canonicalTenantId`, `tenantSlug`, `worldSlug`, `worldDisplayName`, positive private `sourceGameRowId`, exact private `sourceGameTenantKey`, `provenanceKind` (`NEW_GAME_ROW` or `RETAINED_GAME_V30`) and `evidenceDigest`. Slugs use the existing canonical lower-case routing-selector grammar `[a-z0-9]+(?:-[a-z0-9]+)*`, bounded to 120 UTF-8 bytes; no case folding, trimming or inference changes a signed or stored selector. The display name is explicitly supplied, nonblank valid Unicode and at most 100 code points. Source-key bounds and actual game-row provenance retain the tenant-identity rules above. Private source row/key fields are provenance only, not public logical identifiers or a Game Session numeric tenant association. + +The owner claims `(targetNamespace, registrationRequestId)` and commits the tenant-selector binding and complete world-source receipt atomically under the actual Game Design tenant row fence; no claim-only or partial source is authoritative. `tenantSlug` is unique within that namespace's tenant authority, one tenant has one stable slug, and `worldSlug` is unique only within the exact tenant. An exact registration retry returns the same operation, source tuple, metadata and digests. Changed input under the same request, rebinding a tenant slug, slug ownership collision, another request claiming an existing world, absent/contradictory source or failed commit denies without leaving a partial assignment. Reads do not allocate selectors or repair mappings. Ordinary creation and its eventual handoff are automated owner work, not a routine operator import. + +Both digests are SHA-256 rendered as `sha256:` plus 64 lowercase hexadecimal digits over fixed-order UTF-8 segments with decimal byte-length `:` framing, as in the fresh-creation contract. The request preimage is `game-design-authored-world-source-request/v1`, namespace, registration request UUID, canonical tenant UUID, tenant slug, world slug and world display name. The evidence preimage is `game-design-authored-world-source-receipt/v1`, namespace, registration request UUID, operation UUID, request digest, canonical tenant UUID, tenant slug, world slug, world display name, canonical decimal source row ID, exact source game tenant key and provenance kind. No field, implicit normalization or unframed concatenation is omitted. Producer and consumer recompute both digests and share positive/changed-field vectors. + +The readback request binds a distinct canonical non-nil read `requestId` to the exact source `operationId`, canonical tenant UUID and world slug; the closed response echoes that read identity separately from the original registration identity and carries the complete source evidence. Only the verified same-namespace Game Session workload may read it. The guard precedes owner data access, and the receiver authenticates Game Design rather than accepting a JWT service claim or digest alone. Missing or changed source, digest/echo/scope mismatch, wrong workload or namespace, and unknown wire fields fail closed. Exact committed readback returns the same source receipt without mutation; it is not a catalog enrollment result. + +**Implementation and activation boundary:** The source repository/codec/readback is a prerequisite candidate, not a protected product creator or a live catalog handoff. Normal official-hosted authoring remains subject to the Account-owned commit-bound creator/terms gate below, which cannot be replaced by the source transaction or a caller-supplied authorization flag. No new public creation route or catalog admission is enabled before its producer, receiver, owner authorization and negative proof pass. Retained Game Session tenant keys need a separate audited, Game Design-authenticated association and Game Session's own exact retained-row readback; Account's manifest and numeric/slug similarity cannot establish it. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) owns the remaining implementation and proof. + +### Fresh tenant creation operation and Account readback + +This owner-local prerequisite binds a fresh Game Design-issued UUID to a stable creation request and exposes only authenticated readback to Account. It is not a tenant-creation API, product caller, selector-registration path, membership grant, or runtime activation. The internal producer candidate is not a protected product creator; it must not change smoke-seeder behavior or bypass the official-hosted creator gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). Any official-hosted creator-intent mutation remains subject to that gate and its current missing implementation/proof. + +The owner transaction claims a unique `(target_namespace, creation_request_id)` using a canonical non-nil UUID request identity, computes `request_digest`, creates the row through the existing Game Design repository UUID issuer, and commits one immutable `game_tenant_creation_operations` record with the source row/key and receipt evidence. Migration V32 introduces this storage; the evidence schema version is `1`. There is no committed `PENDING` operation: the game row and complete operation evidence commit atomically. An exact retry returns the same persisted receipt; reuse of the same namespace/request UUID with changed input or source key conflicts without mutation. The operation record retains the immutable creation inputs needed to recompute the request digest; later edits to mutable game name/description do not rewrite creation identity. + +The request digest is `sha256:` followed by 64 lowercase hexadecimal digits over fixed-order, length-framed UTF-8 byte segments. Each segment is encoded as its decimal byte length, `:`, then its bytes; the decimal length has no leading zero except for the single digit `0`. Before digest framing or database work, validate cheap input bounds: source key at most 36 Unicode code points, name at most 100 Unicode code points, and description at most 255 Unicode code points. These bounds match the owner columns, including the existing `game.description VARCHAR(255)`; do not expand that owner column for this candidate. Then strictly encode each exact string as UTF-8, rejecting unpaired surrogates; encoding does not replace, trim, or Unicode-normalize input. In order, the request preimage segments are `game-design-tenant-creation-request/v1`, target namespace, canonical creation-request UUID, exact source game tenant key, name, description-presence (`absent` for null and `present` otherwise), and description bytes (empty when absent). Thus absent and present-empty descriptions differ. Length framing counts UTF-8 bytes, not Unicode code points. + +The receipt digest uses the same framing and encoding rules, with ordered preimage segments `game-design-tenant-creation-receipt/v1`, target namespace, creation-request UUID, owner-issued operation UUID, request digest, issued canonical tenant UUID, positive decimal Game Design row ID, exact source game tenant key, and `NEW_GAME_ROW`. Persisted source key and numeric row ID are private owner provenance, not selectors and not assertions about any Account key. + +The candidate read-only method is `TenantIdentityService.ResolveFreshTenantCreation`. Its request carries a canonical non-nil `creation_request_id` and mandatory canonical `expected_request_digest`. The response carries exactly `schema_version=1`, `target_namespace`, `creation_request_id`, `operation_id`, `request_digest`, `canonical_tenant_id`, `source_game_row_id`, `source_game_tenant_key`, `provenance_kind=NEW_GAME_ROW`, and `evidence_digest` (the receipt digest). The receiver requires the verified mTLS peer `spiffe://firemud/ns/{target_namespace}/sa/account-service` for the same configured namespace; the bearer/JWT bypass, if needed for this method, is scoped only to this exact RPC and does not relax the peer guard or authorize another method/caller. Missing, ambiguous, changed, or digest-mismatched operation evidence fails closed using standard shared gRPC status errors; no new error enum is introduced. + +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. ## Official Hosted Creator Mutation Gate diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..27cbc2f420 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -36,6 +36,18 @@ It also communicates game lifecycle changes to other microservices over gRPC so ## World Lifecycle and Admission Boundary +Game Session consumes the exact authenticated authored-world receipt defined by [Game Design's source contract](../game-design-service/api-contracts.md#authored-world-source-registration-and-game-session-readback) before its own runtime catalog intake. The source client validates the separate read identity, complete tenant/world scope and both immutable digests; it does not create or update a catalog, select a runtime, or grant admission. Game Session alone persists the runtime association and must prove exact owner readback. A retained numeric Game Session tenant key requires its separately audited source association and current retained-row evidence, never Account's migration manifest or a guessed selector. Normal fresh intake is an automated owner handoff, while this candidate stays unwired until producer, receiver, creator authorization and catalog proof exist. Remaining implementation and execution limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + +### Authored-world source intake and durable readback + +Game Session's source intake binds its own stable non-nil UUID `intakeRequestId` to the complete immutable Game Design source receipt under the exact workload namespace. The intake service obtains that receipt through the authenticated Game Design source client using a separate read-attempt identity and verifies the requested source operation, tenant UUID and world selector. Before delivering response headers or content, the source client also checks the authenticated TLS leaf's single exact `spiffe://firemud/ns//sa/game-design-service` URI; a trusted CA or matching DNS name alone cannot substitute for workload identity. Missing, ambiguous, another-service or cross-namespace peers fail closed. A caller-constructed receipt, digest alone, Account migration manifest or unchecked transport is not a source authorization. Game Design remains the normative source owner; Game Session's stored copy is the exact consumed evidence, not a new authored selector issuer. + +The owner transaction atomically persists the local non-nil UUID operation, immutable source evidence and tenant selector claim. Within a namespace, one tenant UUID has one `tenantSlug`, one `tenantSlug` has one tenant UUID, and each `(tenantId, worldSlug)` has one exact consumed source. Compatible additional worlds reuse the same tenant source claim; a conflicting tenant/world/source or changed request fails without partial claims. Exact retries return the original local operation and receipt without changing rows. The transient read-attempt ID is an authenticated response echo, not a replacement intake request or persisted registration field. Exact committed readback is non-mutating and checks the complete stored source and selector binding; it cannot allocate missing state or choose another candidate. + +`game-session-authored-world-intake-request/v1` hashes, in order, the domain, canonical `intakeRequestId` and Game Design `evidenceDigest`. `game-session-authored-world-intake-receipt/v1` hashes the domain, canonical local operation UUID, exact local request digest and exact Game Design evidence digest. Each value is encoded in UTF-8 as its decimal byte length, a colon, then those bytes; results are lowercase `sha256:` SHA-256 values. Game Design's closed source codec independently verifies all source fields and both owner digests before either local digest is calculated. A local digest never replaces the authenticated source read or its exact scope checks. + +This source intake records no numeric tenant alias, instance, realm, pointer, lease, membership, authority generation or admission. It does not attach a retained Game Session runtime row: that requires the separately audited association and exact retained-row proof. The normal authorized creation workflow may invoke intake automatically after its Game Design commit; the primitive is not a public creator API and cannot bypass Account-owned creator/terms authorization. Source receipts and selector claims remain immutable survivor evidence; cleanup or release requires its owner retention proof rather than an invented TTL. Runtime catalog and credential activation stay denied until their complete producer, consumer and live proof gates pass. + The World Management database row and monotonic lifecycle epoch are the admission authority under [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Game Session reads that owner state and epoch at lifecycle-sensitive boundaries; it does not use Temporal workflow status, worker memory, or a projection to admit an instance. `PREPARING` is non-admissible, `ACTIVE` is admissible only after the final version-state and owner checks, `FAILED_PRE_ACTIVATION` is terminal for admission, `TERMINATING` rejects new and reconnected bindings, and `TERMINATED` remains closed. Multi-Tenancy owns the realm catalog, the canonical durable `{tenantId, realmId}` pointer identity and its routing/admission semantics, while Game Session is the sole runtime resolver, persister, and compare-and-set orchestrator for that resolved catalog and admission-pointer state; neither service owns World lifecycle state. Replacement preparation and pointer swap carry the catalog-bound `worldSlug`/`realmSlug` selectors, stable `playableStateNamespaceId`/`playableStateScope`, and, for private/playtest targets, the canonical lifecycle proof tuple `{playtestLifecycleId, playtestStateGeneration}` from [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); changing `gameInstanceId` does not authorize a new realm identity, namespace, or durable-state copy. Cutover remains closed unless every owner reports fresh compatible state and the fenced pointer CAS succeeds. After a source swap, Game Session drains and closes source bindings, then asks World to progress termination; it reports a stopped runtime only after authoritative `TERMINATED` readback. Public-production requests omit both playtest fields and reject supplied values. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 8fecf2f05b..5da67af012 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -12,6 +12,10 @@ The sections below define the target-state runtime contract. Current implementat - The shared Gateway connect-context codec now declares and verifies the complete signed-context shape and has local vectors, but first-party runtime parsing remains fail-closed. It does not admit the target context until the independent Gateway Ed25519 verification key is published, Account-to-tenant UUID mapping is available, and the real Account exchange/source-evidence path is proved. Codec and vector presence is not a live issuer/consumer handoff or gameplay-admission proof. +- The Account membership client rejects noncanonical, nil or numeric Account/tenant selectors before stub/channel use and preserves exact UUID request echoes. This is boundary validation, not Account authorization. The current numeric session/catalog carriers still lack the proved canonical UUID handoff required by the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions); numeric stringification cannot satisfy that handoff. The complete signed-context parser, Account runtime RPC and credential producer remain denied; component and runtime proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). + +- The unwired Game Session tenant-source client and authored-world intake implementation are packaged in successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923); the prerequisite producer remains in #2915. They consume the separate [Game Design tenant-source read](../game-design-service/api-contracts.md#runtime-tenant-identity-read-for-game-session), requiring file-backed workload mTLS and exact namespace, request and canonical UUID echoes before returning typed provenance. That source read proves neither a retained Game Session numeric-key association nor catalog enrollment, a realm/namespace, a runtime target or admission. Game Session remains the sole persister of its resolved catalog and pointer; canonical UUID intake and propagation into those current numeric carriers remain required before the denied first-party paths can activate. Exact proof and activation limits remain in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). + - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. - **Target effective-settings boundary:** keep this as a read-only operator surface but make authorization route-aware. Bind a tenant-scoped role to the exact target tenant and require persisted session tenant ownership/equality; allow a global `platformAdmin` branch to select a tenant only with current operator authorization, target-tenant generation, and `privileged_control`. Reject ambiguous/missing target authority, tenant/session mismatches, and unavailable owner/session evidence before invoking any resolver. The negative proof must cover scoped cross-tenant synthetic and persisted-session reads and the global branch without privileged control. - Script pin/epoch rollout remains partial: the authoritative `{scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId}` owner read, CAS-backed pin transition, and instance-bound Automation admission epoch validation are live. Local instance-scoped Automation admission, duplicate replay, durable tick staging/replay, and final Game Session execution now compare the complete tuple; the live ledger is still limited to current atomic request/result rows, and bounded rollout-history readback plus complete source/target remote command identity and final-effect fencing remain gaps. See the [canonical runtime-execution owner](../../system-architecture-scripting-runtime-execution.md#normative-target-contract) and the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index f7f1a0420c..e4d7b64ab5 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -62,7 +62,7 @@ For the closed `account-auth-authority-event/v1` membership event, `membershipVe - **JWT claim contract** – Services must validate a strict JWT claim profile (required claims and audience per token profile), not only signature plus ad-hoc fields. Registry-backed profiles carry the complete `authorityTuple` and positive `issuanceFence` with the exact nested names above. A field marked `Absent` by its profile is omitted, not encoded as an empty string, null, map, or list; an empty map/list is valid only when that profile declares the field present and its value is empty. `control-ui` must include `scopedRoles` as `{}` when empty; omission is rejected. Its `tenantAuthorityGeneration` keys equal the non-empty scoped-role tenant keys whose allowed routes require target-tenant authority, while its independent `membershipAuthorityGeneration` and `membershipVersion` keys equal the caller-membership tenants needed by the token's allowed route classifications, including a `billing_safe_tenant` key that deliberately has no target-tenant authority entry. Explicitly unscoped profiles use empty maps/lists only where their profile declares those fields present, never absent or fabricated scope values. - **Authority tuple comparison** – Every applicable `issuerAuthGeneration`, `accountAuthorityGeneration`, exact tenant and membership map entry, private-realm `grantVersion`, `accountSecurityCutoff`, and `tenantBillingCutoff` is compared as part of one tuple. `membershipVersion` is a separate current/stored membership projection check and is never substituted for `membershipAuthorityGeneration`; a tuple, cutoff, fence, or membership mismatch fails closed. - **Internal gameplay delegation boundary** – Gameplay services authenticate the concrete mTLS workload identity, enforce an exact method-level caller allowlist, and validate a typed `PlayerExecutionContext` against request and domain scope. -- **First-party bare `LOGIN` delegation** – A first-party WebSocket `LOGIN` without credentials may obtain the private `game-session-account-delegation` JWT only through an Account-owned, one-use, idempotent exchange. Account verifies its committed gameplay-connect issuance and bootstrap subject, the verified Gateway-signed connect context, the exact Game Session mTLS caller, the player/tenant/target binding, current authority, and the issuance fence before issuing. Gateway context or a connect-token `jti` alone is not Account authentication. Game Session never mints this JWT or returns it to a gameplay client; an exact retry recovers the same bounded exchange result, while changed binding or fence evidence fails closed. +- **First-party bare `LOGIN` delegation** – A first-party WebSocket `LOGIN` without credentials may obtain the private `game-session-account-delegation` JWT only through an Account-owned, one-use, idempotent exchange. Account verifies its committed gameplay-connect issuance and bootstrap subject, the verified Gateway-signed connect context, the exact Game Session mTLS caller, the player/tenant/target binding, current authority, and the issuance fence before issuing. Gateway context or a connect-token `jti` alone is not Account authentication. Game Session never mints this JWT or returns it to a gameplay client; exact terminal-result recovery after context expiry is governed by [Terminal bare-`LOGIN` result recovery](#terminal-bare-login-result-recovery-normative), and changed binding or fence evidence fails closed. - **No universal player attestation** – Routine gameplay delegation does not use signed per-action player attestations or a replay cache. Mutation replay is controlled by the owning command/effect/request idempotency contract. - **Route classification governance** – Protected routes must be classified in the shared route matrix document and enforced through middleware annotations/interceptors; behavior must not rely on per-service ad-hoc interpretation. - **Gameplay session ownership** – Game Session owns gameplay binding records, the atomic monotonic binding CAS, and bounded secondary indexes that map gameplay bindings by the target uniqueness key `{tenantId, playableStateNamespaceId, characterId}`, account/tenant scope, and tenant scope so takeover, reconnect, and revocation do not require scans. Server-derived `playableStateScope` and binding values/evidence retain `{sessionId, gameInstanceId, bindingGeneration}` as locally appropriate. Account owns the admission decision and exact-binding lease only; Account finalization commits lease/decision evidence and never creates, deletes, or mutates Game Session bindings or indexes. Orphan evidence from Account reconciliation becomes a durable cleanup request that Gateway and Game Session consume under their respective edge and gameplay fences. @@ -70,6 +70,12 @@ For the closed `account-auth-authority-event/v1` membership event, `membershipVe - **Ordinary gameplay authentication** – Each gameplay `LOGIN` uses one account-selected mode, either `PASSWORD` or verified `EMAIL_OTP`. Account configuration may expose both choices separately, but no combined password-plus-email-OTP request is part of the wire contract. Gameplay authentication does not perform active-gameplay reauthentication or elevate the gameplay session into account/control-plane authority; HTTPS step-up remains separate. - **Ingress identity validation** – Public and cross-service readers validate the declared shape of UUID-governed identifiers before authorization or lookup, then treat the values as opaque. Identifier contents never confer authority or determine tenant scope. +### Terminal bare-`LOGIN` result recovery (normative) + +After the original Gateway context expires, Account may return only the exact result of an already `COMMITTED` bare-`LOGIN` exchange, only while that original delegation result remains unexpired and its bounded response envelope is retained. This is a separate reauthorization for exact-result recovery, not a new `LOGIN` success path: the caller supplies a fresh Account-committed gameplay-connect issuance and its independently signed, currently valid Gateway context under the exact Game Session workload identity. Account binds that separate fresh proof to the explicitly requested original operation, request ID and digest; its committed-source reader verifies the fresh source/context pair and proves the same player, tenant, and complete Account-selected target as that original operation, including the applicable playtest lifecycle and generation. The fresh issuance's own request, scope and token identities remain fresh-source evidence and do not replace any original operation field. Gateway context or `connectTokenJti` alone is insufficient. + +Before releasing bytes, Account re-reads current authority, the separate `membershipVersion`, applicable Account issuance and token-identity fences, the original delegation's active registry record, and every applicable installation, lease, and binding postcondition. The exact original exchange operation ID, request ID and digest, committed connect-source operation identity, original signed context and its evidence digest, result bytes, and result expiry are immutable. The expired original context is historical evidence only; it is never accepted as current authorization. Recovery returns the original result byte-for-byte and does not mint, replace, or extend a credential or admit gameplay. A missing, expired, changed, stale, unavailable, ambiguous, or contradictory input or postcondition denies recovery without mutation. Ordinary bare `LOGIN` still rejects an expired Gateway context; no expiry bypass or frozen-clock compatibility path is permitted. Account-local encrypted storage and proof consequences are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md). + ## Responsibility Split - **Account Service** – Verifies login secrets according to account-selected password/email-code modes and owns Account-side authentication authority. JWT profiles, registry, generation, signer, and JWKS rules are defined in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md). diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index 5c766504f5..d8d336ee8f 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -157,7 +157,7 @@ Issuance and refresh use an explicit authority linearization boundary. One seria `membershipVersion` is an independent issuance and refresh fence carrier, not a projection of or substitute for `authorityTuple.membershipAuthorityGeneration`. For every applicable token issuance or refresh, Account must read both values from the same live membership snapshot, validate each against its own current high-water and route requirement, bind both independently into the authority evidence, registry candidate, and refresh/replacement operation, and include both in the composite compare-and-set. A membership-version advance rejects or retries a candidate even when the membership authority generation is unchanged; a membership-authority-generation advance rejects or retries it even when the membership version is unchanged. Missing, regressed, mismatched, or separately assembled evidence for either carrier fails closed, and a successful refresh must install both refreshed carriers without scalarizing or silently dropping `membershipVersion`. -Issuance and refresh have a durable idempotency commit point. Account binds each operation to a high-entropy `requestId` and immutable request digest, stores only token identities, hashes, digests, metadata, complete `authorityTuple`, `issuanceFence`, and postcondition evidence in durable operation state, and accepts the exact registry record before returning the token. For a private delegation or admission-bound operation, the applicable lease and Game Session binding/installation are additional idempotent postconditions of the same request and fence; Account and Game Session must read back the complete postcondition set before exposing a successful usable result. Durable operation evidence never stores a raw JWT. A separate bounded response envelope encrypted under Account-owned application encryption may retain the exact response credential for the same request after reconciliation, bound to the request, digest, caller workload, binding, lineage, replacement, lease, issuance fence, and tuple; it is not registry state or authorization evidence. A registry, lease, or binding timeout or ambiguous response returns no token until the durable operation and all applicable postconditions reconcile. A matching retry may recover the exact response credential only from that separate envelope after current-state revalidation, while a changed digest conflicts without mutation. Refresh applies the same rule to the replacement lineage: the replacement registry record is accepted before the predecessor is retired, and any orphaned replacement is explicitly aborted or retired by Account's reconciler rather than becoming usable by registry absence. A crash between postcondition acceptance and response is replayable by request identity, not a reason to mint a second token or infer success from partial state. +Issuance and refresh have a durable idempotency commit point. Account binds each operation to a high-entropy `requestId` and immutable request digest, stores only token identities, hashes, digests, metadata, complete `authorityTuple`, `issuanceFence`, and postcondition evidence in durable operation state, and accepts the exact registry record before returning the token. For a private delegation or admission-bound operation, the applicable lease and Game Session binding/installation are additional idempotent postconditions of the same request and fence; Account and Game Session must read back the complete postcondition set before exposing a successful usable result. Durable operation evidence never stores a raw JWT. A separate bounded response envelope encrypted under Account-owned application encryption may retain the exact response credential for the same request after reconciliation, bound to the request, digest, caller workload, binding, lineage, replacement, lease, issuance fence, and tuple; it is not registry state or authorization evidence. A registry, lease, or binding timeout or ambiguous response returns no token until the durable operation and all applicable postconditions reconcile. A matching retry may recover the exact response credential only from that separate envelope after current-state revalidation, while a changed digest conflicts without mutation. The terminal bare-`LOGIN` recovery exception after original Gateway-context expiry is owned by [Authentication](./system-architecture-authentication.md#terminal-bare-login-result-recovery-normative) and does not relax exact-envelope, current-authority, registry, or postcondition requirements. Refresh applies the same rule to the replacement lineage: the replacement registry record is accepted before the predecessor is retired, and any orphaned replacement is explicitly aborted or retired by Account's reconciler rather than becoming usable by registry absence. A crash between postcondition acceptance and response is replayable by request identity, not a reason to mint a second token or infer success from partial state. Every generation-bearing validation on a registry-backed JWT route, and every later gameplay admission lease/binding validation that consumes an issuance baseline, must obtain explicit authority-projection freshness evidence for the registry, lease, binding, token-identity fence, and Account authority evidence used by the operation. The evidence fence identifies the exact authority scope, every applicable field in `authorityTuple`, cutoff checkpoint, `issuanceFence`, source transaction or outbox/event version, and observed projection status. A validator may authorize only when that evidence proves the projection represents the current committed authority for the requested scope; Redis key presence, a successful read, a timestamp, or a cached value is not freshness evidence. This requirement explicitly excludes Gateway's replay-fence validation in the bounded `gameplay-connect` issuance-evidence path: Gateway does not read the ordinary issued-token registry or the Account authority evidence bundle, and it validates the signed `replayAdmissionFence` and atomically consumes the dedicated single-use replay record. Game Session performs the later exact-binding lease, binding-fence, and current-authority checks. Missing, malformed, ambiguous, stale, regressed, or unavailable fence evidence fails closed. An unreachable or timed-out registry, lease, binding, fence, authority-generation source, or Account authority-evidence dependency is retryable `AUTH_UNAVAILABLE` / HTTP 503; entitlement-only unavailability is classified as `ENTITLEMENT_UNAVAILABLE` by the owning entitlement/admission contract and never relabeled as an auth-authority outage. Reachable missing, expired, revoked, mismatched, or otherwise invalid evidence is `AUTH_SESSION_REVOKED` or the specific invalid-token outcome requiring reauthentication. diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index a357dbf576..a4a30ef604 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -45,9 +45,11 @@ Current Game Session bootstrap/reconnect context remains on the implementation-l ### Canonical Identity and Retained-Key Bridge +The separate authenticated [authored-world source handoff](./microservices/game-design-service/api-contracts.md#authored-world-source-registration-and-game-session-readback) binds Game Design's explicit tenant and tenant-scoped world selectors to its persisted tenant provenance. Game Session consumes that source before its own catalog persistence; it is not an admission or runtime association receipt. Retained Game Session tenant keys require a separately audited owner assertion and exact Game Session retained-row readback, not Account's manifest, inferred numeric equality or slug similarity. Both ordinary creation and fresh source intake are automated owner work, with unresolved identity or source evidence denied rather than repaired by guesses. + Game Design issues and persists the canonical opaque UUID `tenantId` and owns its stable `tenantSlug` selector. Issuance is a durable owner transaction, not a conversion of a numeric key, an interpretation of UUID bits, or a slug-derived value. An exact owner read must return the same persisted UUID and the source/selector provenance; absence, ambiguity, or changed source binding is not a tenant identity. A retained Game Design game row can be assigned a UUID with provenance naming that exact row and its former Game Design tenant key. That assignment by itself does not prove that a numerically similar Account tenant key denotes the same tenant. -For a newly created tenant, Game Design binds a stable creation-request identity to the persisted opaque UUID and creation provenance in its owner transaction. A distinct Game Design-authenticated creation/readback handoff returns that exact operation, UUID, and persisted source evidence to Account; an exact retry returns the same binding, while a changed, absent, ambiguous, or conflicting operation fails closed. Account stores and reads back the fresh association under its own identity authority before membership work. This path does not use the retained-row migration manifest, infer a UUID or Account association from a numeric key or selector, or grant membership or admission by itself. +For a newly created tenant, Game Design binds a stable creation-request identity to the persisted opaque UUID and creation provenance in its owner transaction. The service-local operation and authenticated readback contract is owned by [Game Design API Contracts](./microservices/game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback). A distinct Game Design-authenticated creation/readback handoff returns that exact operation, UUID, and persisted source evidence to Account; an exact retry returns the same binding, while a changed, absent, ambiguous, or conflicting operation fails closed. Account stores and reads back the fresh association under its own identity authority before membership work. This path does not use the retained-row migration manifest, infer a UUID or Account association from a numeric key or selector, or grant membership or admission by itself. Account issues and persists a separate canonical UUID `accountId` for each global account while retaining private numeric row keys. Its retained account mapping is one-to-one and records the exact Account row and assignment provenance. For retained membership, JOIN, receipt, and audit rows, Account preserves the original numeric evidence and adds a separate one-to-one bridge to the Game Design-issued tenant UUID only after an authenticated Game Design owner assertion establishes the exact legacy Account tenant-key association and its provenance. Neither a matching decimal string, a game row ID, a default tenant value, nor a guessed slug is that assertion. The owner assertion and Account bridge must be durably readable back and must reject duplicate UUID claims, one legacy key mapped to multiple UUIDs, one UUID mapped to multiple legacy keys, and evidence changes on retry. Unmapped or ambiguous retained rows remain non-admitting and may not be resolved by selecting an arbitrary candidate. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index ea7414df4b..f6f4b7de63 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -282,3 +282,8 @@ Entry format: - Context: the complete Account snapshot/first-JOIN test held the Account row `FOR UPDATE` and waited for JOIN's explicit Account-lock spy. JOIN first inserts its PENDING intent, whose foreign-key check can already wait on that same row. - Observation: exact CI timed out at the later spy, not at a source invariant. Instrumenting the actual intent-insert backend before the real insert retained the exact `pg_blocking_pids` correlation and complete before/after DTO assertions; corrected CI `36778631119` executed the race once successfully. Worker exceptions are surfaced rather than hidden behind a latch timeout. - Expected pattern: trace earlier foreign-key and deferred-trigger work before selecting a concurrency signal; prove the exact blocked backend/owner relation and do not fix a misplaced signal by extending timeouts or changing production transaction order. + +- `2026-10-01`: Consume the final validation result before committing a claimed green checkpoint + - Context: a final #2917 tracker edit began a paragraph with a PR hash, which Markdown lint interpreted as a malformed heading. The documentation gate exited nonzero, but its redirected log was not inspected before the local commit. + - Observation: no push occurred; inspection identified the lint failure and the unvalidated claim was corrected in a follow-up commit. Earlier successful documentation checks did not cover that last edit. + - Expected pattern: consume every final gate's exit status and failure log before committing or publishing proof claims; after a status-only edit, validate that exact edited scope rather than inheriting the preceding green result. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 3040a231d8..5cc6c69985 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work was rebuilt into #2826 Schema, the dependen | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2881](https://github.com/benhook1013/FireMUD/pull/2881) → [#2911](https://github.com/benhook1013/FireMUD/pull/2911) → [#2914](https://github.com/benhook1013/FireMUD/pull/2914) | Earlier discovery and train pre-review did not complete the section. Exact #2911 `78c3fe886` [CI 36778631119](https://github.com/benhook1013/FireMUD/actions/runs/36778631119) executed 30 JOIN, 9 connect-issuance and 9 bare-LOGIN storage PostgreSQL cases without skips or failures, including the complete snapshot/first-JOIN race; both authority-exhaustion methods and Game Session strict cases also passed. Aggregate CI remains red on routed inherited failures. #2914 adds unwired original committed-connect source readback and strict signed-source/context correspondence; its seven new PostgreSQL cases are pending executed proof. These are component prerequisites, not credential issuance or live admission. Required complete Account authority/consumer evidence, connect/delegation producers and registry, fresh Game Design tenant handoff, protected ring delivery, durable reconnect, HTTPS/mail/abuse and live browser proof remain open in the [Player Access tracker](../implementation-tracking/player-access-and-session.md). Membership RPC and credential activation stay denied; the ring mount stays unpublished. | +| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2915](https://github.com/benhook1013/FireMUD/pull/2915) → [#2923](https://github.com/benhook1013/FireMUD/pull/2923) | Consolidated owner stages: #2880 retains fenced snapshots, one-use LOGIN storage, complete selected-target context and original committed-source proof from #2881/#2911/#2914. #2915 retains fresh tenant creation/association, UUID pair/snapshot and request candidates, historical recovery/fresh-source correlation, and Game Design tenant-source readback from #2917–#2920. #2923 owns the unwired Game Session tenant-source/intake consumer and Account LEFT/current-INACTIVE owner evidence; its new LEFT PostgreSQL proof remains open. Historical component proof remains head-specific; it does not enable a complete exchange. Full Account authority/credential/registry composition, authenticated authored-world source and audited Game Session association, protected ring delivery, durable reconnect, and HTTPS/mail/abuse/browser proof remain open. Membership RPC and new credential paths stay denied; ring mount unpublished. See the [Player Access tracker](../implementation-tracking/player-access-and-session.md) for exact proof and handoffs. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | 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 ab338d4b7b..2063242c4d 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 @@ -10,6 +10,8 @@ This tracker consolidates Game Design authoring, settings, publication, release The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30.1 assigns each retained `game` row a unique UUID with immutable row/former-key provenance after the V30 baseline-lock migration, new game rows receive distinct issued UUIDs, and an Account-workload-only former-key read returns the exact persisted source tuple. The V31 addition defines a separate signed, owner-approved manifest operation for exact Account numeric-key associations. It verifies the former Game Design key, source row, and issued UUID, stores immutable one-to-one evidence, and exposes the exact approved tuple only to the dedicated Account tenant migrator, never ordinary Account or another service peer. Its opt-in chart Job uses a separate, explicitly issued and verified certificate rather than replacing Gameplay or service identities. Focused manifest, gRPC, certificate/admission, and Helm-render tests execute locally; the new PostgreSQL manifest case executed and passed in hosted CI on a preceding head. The Docker-free V30/V30.1/V31 uniqueness/order and startup-mode regressions pass, and the combined local Account/Game Design service checks and boot-JAR packaging pass with cached/up-to-date results disclosed. Local PostgreSQL tests skip without Docker, so the newly composed database sequence and live consumer boundary remain unproved. No actual manifest has been applied or read back in a deployed environment, and the Account bridge/consumer proof remains incomplete. This is not the stable `tenantSlug` catalog/selector or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain non-admitting until the owner assertion, bridge readback, and consumer proof exist. +A separate fresh-tenant operation/readback child selected after #2914 is extended by #2915 with an Account normal-workload authenticated consumer, immutable canonical-UUID association, and shared UUID conflict claim. Account must commit only after exact operation/request/digest/source/receipt readback, then use existing tenant-generation initialization without reset. The local extension is in progress; it is not a creator mutation API or caller, and enables no Account numeric alias, selector, membership, credential, or runtime path. Earlier local source/RPC results (291 unit cases; 28 integration cases discovered and skipped) predate the Account extension. The seven strict Game Design creation database failures in [CI run 36791561008](https://github.com/benhook1013/FireMUD/actions/runs/36791561008) are historical incident evidence, superseded by passing creation and Account-association PostgreSQL component proof on later heads. Aggregate CI failures and exact run scope are recorded in the [Player Access and Session tracker](./player-access-and-session.md). No PostgreSQL execution is claimed for the current checked-out head, and these component results do not establish live mTLS/SPIFFE, a deployed cross-owner handoff, a production creator caller, or activation. The V32 producer contract and canonical digest are owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback). + The opt-in migration Jobs require separately provisioned, mode-specific database Secrets and least-privilege PostgreSQL identities as described in [Account operations](../../architecture/microservices/account-service/operations.md#legacy-tenant-association-import) and [Game Design operations](../../architecture/microservices/game-design-service/operations.md#legacy-tenant-association-migration). Existing Helm, role-name, certificate, and focused startup proof does not establish live effective grants or the role authenticated through each Secret; operator readback and deployed operation evidence remain outstanding. Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. 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 056ad29f03..9c8de3433e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,10 +6,59 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The next Account-owned committed-connect source reader is an unwired prerequisite, not an authorization or credential producer. It recovers a complete successful V35 receipt and purpose-bound envelope by exact identity, checks the original compact JWT hash/JTI and asymmetric signature against the closed selected-target profile, verifies the Gateway assertion independently, and proves source/context correspondence under the Account row fence and approved retained tenant mapping. It requires the exact Game Session peer and an active owner transaction before data access, returns no raw credential, and rechecks unchanged deadlines after a fence wait. The consolidated local Account check passed with 413 unit cases executed, including 11 original-source verifier and four early-denial cases; all 105 PostgreSQL cases compiled but skipped without Docker, including the seven new source-readback cases. The CI strict inspector requires that new suite and both exact reread and fence-expiry methods to execute without skips. This component does not supply fresh tenant authority, authenticated current-eligibility evidence, an issued-token registry, protected key delivery, or a working bare-LOGIN exchange; those gates remain open and no runtime path or mount is enabled. +The Game Session tenant-source client and authored-world intake consumer, V7 schema, tests and focused PostgreSQL gate are owned by successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923), not the reduced #2915 producer checkpoint. #2915 retains Game Design's persisted creation/source producer, closed proto/shared evidence and vectors, Account fresh/retained source and UUID authority, and recovery components. The nine-file consumer package is preserved unchanged in the child; the cumulative capability and activation limits are unchanged. Earlier #2915 intake execution below refers to the exact historical head where that package lived, not new evidence on either redistributed head. Runtime catalog, membership RPC and credential paths remain denied; the retained Game Session association, live authenticated handoff and complete authority/consumer proof remain open. + +Exact `ab93efc392fb57e53b7126d0d9ee639dce0bcd23` [CI36833651399](https://github.com/benhook1013/FireMUD/actions/runs/36833651399) resolved cross-service Flyway discovery and executed all five Game Session intake PostgreSQL cases: four passed, one failed, none skipped. The remaining failure is the tenant-binding truncate assertion: PostgreSQL rejects the referencing foreign key before reaching the expected immutable trigger. The focused correction keeps that foreign-key rejection proof and separately exercises the immutable trigger with the dependent tables included; exact corrected execution remains required. Uploaded Game Session reports are HTML-only and the strict verifier did not run, so this is execution/failure evidence, not strict success. Account again passed strict JOIN31, exchange9, issuance9, source/history18, fresh association6, pair8, fresh UUID snapshot11 and generation2/outbox4 with zero skips/failures/errors. Game Design creation8/authored-source10 passed strict; its broader retained fixture and other aggregate failures remain open. Later Game Session check, Script Pin25 and WebSocket16 gates skipped after the early intake failure. No runtime activation or corpus completion is claimed. + +Exact `03753754573afbcd5742354b4bb73cc4e8d4d2c8` [CI36831541847](https://github.com/benhook1013/FireMUD/actions/runs/36831541847) executed and passed strict Account JOIN31, bare-LOGIN storage9, connect issuance9, committed source/history18, fresh association6, pair8, fresh UUID snapshot11 and generation2/outbox4, all zero skips/failures/errors. The corrected repeated-positive read and its complete no-mutation assertion executed once and passed. Game Design creation8/authored-source10 also passed strict; the wider separately routed retained fixture remains red. The mandatory early Game Session intake task reached all five PostgreSQL cases, but all failed before repository behavior because the new fixture's classpath migration scan included other services' V1 migrations. HTML artifact counts are execution/failure evidence, not strict success or raw XML credit. Its fixture now uses the established module-owned filesystem migration location without changing schema versions or weakening any rollback, immutability or concurrency assertion. Focused integration compilation, formatting, Checkstyle and SpotBugs passed (101 tasks, 15 executed/86 up-to-date); the five PostgreSQL cases skipped locally without Docker, so corrected database execution remains open. Existing full-validation and Script Pin/WebSocket gates are retained; this run supplies no Script Pin25/WebSocket16 proof. Other aggregate failures and all activation limits remain open. + +Both Account Game Design identity clients now enforce the exact same-namespace server workload URI before accepting response content. Fresh and retained reads reject plaintext, missing namespace and non-file-backed/incomplete key material before channel creation; the fresh receipt is closed to unknown protobuf fields. Initialized-stub tests prove untrusted transport content is rejected, complementing shared certificate/parser tests, without claiming a live TLS handshake. Corrected Account full check/JAR/docs passed with456 unit executions and138 PostgreSQL skips; the retained client is final and does not require a transaction proxy. Runtime paths and the ring mount remain gated. + +Exact prior-head [CI 36826897436](https://github.com/benhook1013/FireMUD/actions/runs/36826897436) on `ada803afcf69fd69555f5ecad55275e424d8623e` failed the new repeated-positive read test at its Java object-equality assertion. Both reads completed; no SQL error was associated with that assertion. It now compares exact event ID, digest and canonical bytes while retaining complete database no-mutation checks; corrected PostgreSQL execution remains required. Strict source/history18, association6, pair8 and fresh UUID snapshot11 passed without skips/failures/errors, including the fresh no-enrollment negative. Broad JOIN/exchange/issuance and exhaustion strict steps skipped after Account check failed; HTML reports are partial execution evidence, not strict XML credit. Game Design strict creation8 and authored-source10 passed; its wider fixture failure remains routed. Game Session exhausted its20-minute job budget during cross-service tests and never started integrationTest; intake5, Script Pin25 and focused WebSocket16 remain unproved. The mandatory focused intake task and strict verifier now run before the longer broad check, without removing full validation or the other gates. Its exact local command discovers five cases, all skipped without Docker; strict verification correctly rejects those skips. An initially mismatched declared suite package was corrected before this workflow batch was published. + +The next #2915 component adds unwired Game Session authored-world intake: the authenticated source read must prove the exact Game Design server workload URI before delivering content, and the owner transaction atomically stores the complete immutable source, tenant/world claims, stable local request and exact result. Committed readback never repairs missing rows or allocates identity. Five PostgreSQL cases cover exact retry, changed-request/source collisions, transaction rollback, immutable claims, concurrency and read-only boundaries; local digest vectors and intake guards execute independently. It does not create a runtime instance, attach a retained numeric tenant or grant admission. The separate audited retained Game Session association, automatic authorized creation and full catalog/carrier convergence remain open. + +Account adds a canonical-UUID existing-positive-membership read under its private row fence. It reads back the existing pair, event, roles, receipt and authority without preparing or enrolling state. Missing, fresh non-positive, inactive or contradictory state is denied without mutation. This is positive membership evidence only, not complete current authorization, terminal recovery eligibility or permission to reject an otherwise permitted sequence-zero non-admitting LOGIN flow. Two new PostgreSQL cases plus strengthened retained negatives prove repeated readback and unchanged rows/counters/receipts; runtime RPC and credential paths remain denied. + +The corrected three-module full check, affected formatting, both service JARs, links and Markdown passed (169 tasks, 39 executed/130 up-to-date). Game Session executed 1,723 unit, 18 integration and one cross-service cases without failures; 17 unit/116 integration/33 cross-service cases skipped, including all five new PostgreSQL intake cases. Account's 451 unit and shared-core's 121 unit results were unchanged and up-to-date from their preceding executed gates; all 138 Account PostgreSQL cases compiled/discovered but skipped without Docker. Actionlint, CI-scope23, Flyway12 sets/123 files and diff hygiene passed. Mocked certificate/session interceptor tests are not an executed network TLS handshake or live workload proof. The changed Account read and Game Session intake require exact-candidate PostgreSQL execution; component tests do not enable the ring mount, catalog, membership or credential paths. + +The #2915 storage correction preserves the originally published numeric V35 and bare-LOGIN storage definitions byte-for-byte; the bare-LOGIN migration is now named V37.1, while historical V37 proof labels below remain scoped to their original heads. Forward V39.1 takes transaction-held exclusive locks on the complete four-table connect-issuance and bare-LOGIN operation/envelope set, checks that every table is empty, and only then changes the empty tenant-column shape to canonical UUIDs while preserving keys, checks and immutable/deferred guards. Any retained row aborts the transition without changing identity, provenance, ciphertext or replay evidence; no identity cast, evidence discard, resealing or inferred compatibility mapping is permitted. Retained-data transition requires a separately approved Account-owned audited recovery operation and exact readback; it is not supplied by V30's association bridge or this empty-table migration. Deployment must quiesce old storage writers before the cutover and prevent them from resuming afterward; database locks alone do not fence an old binary after commit. No live environment is assumed empty. The new focused PostgreSQL cases cover fresh migration, empty V39 upgrade, unchanged retained rows and encrypted evidence, concurrent writer fencing and retained post-upgrade guards; local database execution remains unavailable without Docker and exact-candidate PostgreSQL proof is required. The unwired Account reader still verifies the fresh immutable association or approved retained bridge under its private Account fence and returns evidence only, never a credential or recovery authorization. Credential producers, mounts and runtime admission remain disabled. + +Game Design now has an owner-transaction authored-world source registration primitive, immutable request/result receipts, atomic tenant-slug and tenant-scoped world-slug claims, exact committed readback, and the closed `ResolveAuthoredWorldSource` handoff to an authenticated same-namespace Game Session peer. Its unwired file-backed-mTLS consumer validates both digests and all exact request/scope echoes, including validly re-digested wrong-scope receipts. Ten PostgreSQL cases cover real fresh/retained source rows, retry, rollback, races and immutable/read-only boundaries. This is not automatic hosted creation, the separate audited retained Game Session numeric-key association, runtime catalog enrollment or admission. Those owner prerequisites and Account creator/terms authorization remain open. + +For that preceding source/UUID correction at `c946b644bbde2ade9d39feef247d38160c2df159`, local six-module checks, three runtime JARs and docs passed; task logs establish Account450, shared-core114, Game Design303 and final Game Session1,715 unit executions. Its exact [CI 36822480931](https://github.com/benhook1013/FireMUD/actions/runs/36822480931) then executed Account source/history18, JOIN30, exchange9, issuance9, association6, pair8, fresh snapshot10 and generation2/outbox4, plus Game Design creation/runtime-source8 and authored-source10, all strict with zero skips/failures/errors. The aggregate failed: the wider Game Design task reproduced the separately routed #2872 duplicate retained fixture, and Game Session was cancelled with its strict steps skipped after 16 WebSocket assertion failures. TCP13/17 identity-carrier failures and separate Automation/tooling failures remain open; no Script Pin25/WebSocket16 proof is credited. Counts are strict verifier stdout backed by runner JUnit parsing; uploaded artifacts are HTML/JaCoCo, not raw XML. This closes the named component database gaps on that head, not the subsequent local intake/current-membership changes or live runtime/credential/catalog activation. The ring mount remains unpublished. + +Corrected composed [CI 36815322807](https://github.com/benhook1013/FireMUD/actions/runs/36815322807) on preserved source head `8b4bdac7a4611e2ac3789452e7cad967768f19ce` executed and passed all 17 Account committed-source/history cases without skips, including the four new fresh-correlation methods, stored historical-frame positive readback, and Account-fence and historical-read deadline waits. Strict Account JOIN30, connect issuance9, exchange storage9, fresh association6, pair authority8 and fresh UUID snapshot10 passed with no failures/skips/errors; the separate generation/outbox exhaustion-rollback gate passed. Game Design creation/runtime-source8 also passed without skips. These close the named component execution gaps below, not current authorization, credential release, complete runtime handoff or activation. The initial four-stage consolidation at `dd5c625aec82ed1db1259dbdb2f07c6954b7c9df` preserved that entire code/workflow tree; its index/status-only changes are not separately credited as executed CI, and the subsequent source/UUID correction above requires fresh execution. Aggregate CI remains failed: Game Design's duplicate retained fixture is routed to #2872; Automation formatting, shared Ruff/dev-demo validator and TCP13/17 current identity-carrier failures remain open. Game Session was cancelled and all its strict steps skipped, so this run supplies neither Script Pin25 nor focused WebSocket16 proof. Strict counts are verifier stdout backed by JUnit parsing; uploaded artifacts contain HTML/JaCoCo, not raw JUnit reports. Fresh local combined service checks passed separately; Docker-backed local skips are not runtime proof. + +The active Document tail is consolidated to #2873 → #2876 → #2880 → #2915. #2880 owns the retained fenced snapshot, bare-LOGIN storage, selected-target context and committed-source components formerly packaged in #2881/#2911/#2914; #2915 owns the fresh tenant/UUID authority, historical recovery/correlation and tenant-source read components formerly in #2917/#2918/#2919/#2920. Every source head remains in normal merge ancestry, with exact source-tree preservation before this index-only correction. Historical proof below remains scoped to its named head, not a new combined-head execution claim. No accepted obligation or activation gate is closed merely by consolidation. The five original unpublished ring-mount/proof edits remain outside these stages until custody, authenticated publication/readback and readiness are proved. + +Exact #2920 `728a0dd09982506e801e21f6154bec420548984a` [CI 36812079812](https://github.com/benhook1013/FireMUD/actions/runs/36812079812) executed all eight Game Design creation/runtime-source PostgreSQL cases successfully with zero skips, including the genuine V29→V30/current fresh/retained identity lookup. Account strict association 6, pair authority 8 and fresh UUID snapshot 10 also passed without skips. The strict source/history suite executed 13 cases with one owned failure: stored-frame readback used nonexistent historical `exp` instead of signed `expiresAt`, causing `NullPointerException: signedGatewayExpiresAt`. #2918 `bf6a491cdc7c3558ff6421a9bb8d5df8e0321ca3` fixes that field and adds the non-authorizing fresh-source correlation proof; normal descendant propagation preserves it here, but corrected PostgreSQL execution remains required. Account broad JOIN/authority-rollback verifiers skipped after failure; Game Session was cancelled, so no Script Pin/focused WebSocket proof is attributed. Observed Communication WebSocket/TCP identity-carrier failures remain concrete Unit 1B obligations, not silently dismissed as flaky; separate Game Design duplicate-9301/tooling failures remain routed. Strict counts are verifier-log evidence, with HTML failure traces and no uploaded raw JUnit XML. This closes the named tenant-source database case's local-skip gap, not live workload handoff, catalog intake or activation. Overseer approved Game Design's persisted authored-world source handoff and a separate audited retained Game Session tenant association; exact schema, automatic producer/readback and negative proof are still to be built. Tenant/world selectors remain distinct and Game Session alone owns runtime catalog persistence. + +The Game Design → Game Session tenant-source candidate adds a distinct exact-method, same-namespace Game Session peer guard and canonical non-nil UUID read. The owner lookup checks the actual persisted Game Design row/key against its recorded source provenance, rejects missing/ambiguous/contradictory bindings, and does not allocate or mutate identity. A separate unwired Game Session client requires file-backed workload mTLS and closed typed response/namespace/request/UUID readback. Existing Account-only creation and migration methods remain separately guarded. New unit cases cover owner lookup and receiver/client negatives; a named PostgreSQL method creates a genuine retained row at V29, migrates through V30/current, then checks exact fresh/retained/missing lookup without mutation. A fixture that disabled the identity immutability trigger was rejected and replaced before publication. Consolidated shared-core/Game Design/Game Session full checks, both service JARs and docs passed (169 tasks, 40 executed/129 up-to-date): Game Design executed 299 unit cases; Game Session executed 1,711 unit, 18 integration and one cross-service case, with 17 unit, 111 integration and 33 cross-service cases skipped. Shared-core's 108 successful unit cases were executed in the preceding unchanged gate and up-to-date in the final run. All 29 Game Design PostgreSQL cases skipped without Docker and remained up-to-date in that final run. That initial local gate did not execute PostgreSQL; the named owner case is now attested by the exact composed CI above. Live mTLS and deployed handoff proof remain open. Root corrected the helper's test constant collision, unnecessary null-exception catch and mutable test-error retention through bounded edits; no guard or assertion was weakened. Actionlint and all 23 CI-scope contracts passed. Source evidence supplies neither retained Game Session numeric-key association nor catalog enrollment/target authorization. Game Session's own canonical tenant intake and current numeric catalog/session carrier convergence remain required, and the runtime membership/credential paths remain denied. + +The unactivated canonical membership-request slice carries exact non-nil Account/tenant UUIDs through the snapshot DTO and response echoes. Account resolves retained UUIDs through the approved reverse association and current source digest, fresh UUIDs only through immutable V38.1 evidence, then performs owner-fenced readback; private numeric keys never appear as request identities. Game Session rejects invalid/numeric selectors before any stub/channel interaction. After normal propagation of #2918's historical-source correction and the retained fixture repair, composed Account/Game Session full checks, both JARs and docs passed (154 tasks, 28 executed/126 up-to-date): 444 Account unit cases executed with no skips/failures and all 129 Account PostgreSQL cases skipped without Docker. Unchanged Game Session checks were up-to-date from their earlier executed local gate (1,705 unit, 18 integration and one cross-service executed; 17 unit, 111 integration and 33 cross-service skipped). Actionlint and all 23 CI-scope contracts passed. Earlier executed database proof is separately scoped below; corrected retained-path and new historical-readback execution remain required. Canonical session/catalog identity propagation, positive fresh membership, advanced/INACTIVE event proof, complete current authority and credential/registry composition remain required. The membership RPC, signed-context parser and credential paths remain denied and the ring mount unpublished. + +Composed [CI 36804479170](https://github.com/benhook1013/FireMUD/actions/runs/36804479170) on #2919 `68358f7d227651e36826b97a38a7db70b2f6e4d1` supersedes the local-skip limit for the strictly attested suites: all ten fresh UUID snapshot, eight pair-authority, six fresh-association and seven Game Design creation PostgreSQL cases executed and passed without skips, including the corrected rollback fixture and both canonical UUID cases. Account's broader 129-case integration run failed five retained snapshot/JOIN cases because the test workload namespace `account_service` is not a valid DNS namespace. The fixture now uses one matching `account-service-test` workload/approval namespace while preserving the `account_service` database schema and all production guards; corrected retained execution remains required. The source-seven strict step skipped and Game Session was cancelled, so this run supplies neither source nor Script Pin/WebSocket proof. Aggregate shared failures remain separately owned. Counts come from strict verifier logs; uploaded artifacts contain HTML, not raw XML. This is database component proof, not authenticated runtime or live admission proof. +The next #2918 component correlates the exact stored original V37 exchange/request/digest and V35 history with a distinct strict-current committed V35 source under the same Account fence. It compares the full canonical player/tenant/selected-target projection, retaining original and fresh requests, operations, scope hashes, token identities and timestamps separately. The strict source is checked before historical frame access and again afterward, without extending its signed deadline. Historical Gateway expiry evidence now uses signed `expiresAt`, not the source JWT's `exp`. Four additional PostgreSQL cases cover immutable exact reread, expired or non-distinct fresh proof, player/tenant/target/lifecycle/generation and original-request/digest mismatch, and an actual database lock wait during stored-frame access that outlives the fresh deadline; a unit case covers early peer/transaction denial. The consolidated Account full check/JAR, formatting, Checkstyle, SpotBugs, JaCoCo and documentation passed (70 tasks, 23 executed/47 up-to-date): 441 unit cases executed without failures/skips, and all 133 PostgreSQL cases compiled/discovered but skipped without Docker. Four new named cases are mandatory in strict CI; the preexisting Account-fence case now exercises the correlation path without losing its required method name. Actionlint and all 23 CI-scope contracts passed. Actual PostgreSQL execution of the new correlation cases remains required. These are source-correspondence prerequisites only: current authority, membershipVersion, result JWT/expiry/registry, recovery horizon, producer evidence and postconditions remain open, and no credential or runtime path is enabled. The component counts below refer to earlier checkpoints, not this batch. + +The next terminal-recovery component is an unwired `AccountStoredBareLoginRecoveryReader`: exact Game Session peer and owner transaction precede repository/crypto interaction, the Account fence protects exact committed V37 operation/envelope readback, and the decoded retained frame's result hash and signed historical context must match its exact committed V35 source. It returns redacted immutable provenance facts, never credential/context bytes or authorization. Two new PostgreSQL cases cover repeated expired-context framed readback and changed digest/source/context/result hash/key rejection, including unframed-payload denial; three unit cases cover early caller/transaction denial. Named PostgreSQL methods are required by strict CI verification. Local Account full check/JAR, formatting/static analysis and documentation passed: 440 unit cases executed with zero failures/skips, and all 129 PostgreSQL cases compiled but skipped without Docker. SpotBugs rejected an unnecessary suppression; it was removed rather than bypassing the check. Exact composed [CI 36807876923](https://github.com/benhook1013/FireMUD/actions/runs/36807876923) on `a65200c1e4bf9c28eb157a4e2ca34f44234e17b4` executed all eleven earlier source cases with zero skips and one assertion-message failure: the verifier deliberately sanitizes projection errors, but the negative test expected the underlying message. This fixture is corrected at its #2918 owner without changing rejection or no-mutation assertions; the final local rerun passed (70 tasks, 15 executed/55 up-to-date; unchanged unit results cached), and remote rerun remains required for both it and the two new stored-frame methods. That earlier run also passed the strict fresh-association 6, pair-authority 8, fresh-snapshot 10 and Game Design creation 7 cases. Game Session was cancelled; no Script Pin/WebSocket proof is credited to that run. The original result JWT/expiry, declared recovery horizon, producer evidence digests, separate fresh authorization, current authority/registry/postconditions and complete canonical-UUID wiring remain required; neither this component nor historical evidence enables the exchange. The reader clears decrypted/extracted byte arrays, but the framing object's internal defensive copies have no explicit destruction API and are left for garbage collection; no complete memory-erasure guarantee is claimed. + +The recovery foundation includes a distinct historical Account source verifier and an unwired committed V35 history reader. The reader requires the exact Game Session peer and an active owner transaction before data access, then fences the Account row, verifies canonical Account/approved retained tenant provenance, reads the exact committed operation/envelope, checks its purpose/hash/JTI and independently signed source/context correspondence, and returns deeply immutable non-authorizing evidence without the compact credentials. Decrypted bytes are cleared. The strict-current reader still rejects expired evidence and rechecks unchanged deadlines after fence waits; no clock is reset. Four new PostgreSQL cases cover expired-source historical readback with strict-reader denial, request/target/hash/JTI mismatches, noncommitted source rejection, and unregistered signing keys; existing cases also exercise historical key/provenance denial. Root removed an impossible missing-envelope fixture rather than weakening V35's deletion guard; no missing-envelope fault-injection proof is claimed. Consolidated Account/Common Security full checks, Account JAR and docs passed (82 tasks, 23 executed/59 up-to-date): 437 Account unit cases executed, including all 13 source-verifier and five early-denial cases; all 127 Account PostgreSQL cases skipped without Docker, and unchanged Common Security checks were up-to-date. Named history cases are required by strict CI verification even when another Account check fails. This supplied historical assertion is not evidence of V37 original-context retention or past Gateway acceptance. Durable original-context/result production, separate fresh authorization, current authority, active registry and exact terminal result release remain unproved; no runtime path is enabled. + +PR #2917's snapshot failure-injection fixture now stubs the underlying Mockito target instead of entering the Spring transaction proxy during setup. The actual producer call still traverses that original proxy inside its owner transaction and executes the real mutation before the injected failure; neither `MANDATORY` propagation nor the explicit repository guard is weakened. Its initial local Account full check/JAR, formatting and static analysis passed with unchanged unit results up-to-date and PostgreSQL skipped. The subsequent exact composed CI above executed and passed both previously failing cases; earlier failed runs below remain incident evidence rather than current proof. + +Exact #2915 head `910d0a6f41d60ee7214b610d56f89c51db260413` [CI 36796087279](https://github.com/benhook1013/FireMUD/actions/runs/36796087279) executed and passed all six Account fresh-association and seven Game Design creation PostgreSQL cases with zero skips, failures or errors; every strictly required retry/concurrency/rollback case executed once. These counts come from the strict JUnit XML-verifier logs, not JaCoCo; retained artifacts contain HTML but not raw JUnit XML. Account, Game Design and shared-core unit tasks ran with build/configuration caches disabled. Account's check and JAR passed; Game Design's check failed on the unchanged Entity baseline-migration fixture already routed to #2872 and its hosted JAR step skipped. Automation formatting, shared Ruff and the dev-demo summary validator also keep aggregate CI red. This supersedes the earlier failed creation-fixture proof below, not its incident evidence. Database component proof does not establish live mTLS/SPIFFE, certificate rotation, fresh-image boot, a deployed cross-owner handoff or activation. + +Draft [#2917](https://github.com/benhook1013/FireMUD/pull/2917) extends the existing V36 pair/snapshot authority through additive V39 rather than adding a parallel authority or numeric alias. Fresh provenance requires a null legacy tenant key; approved retained provenance keeps its positive key, one-to-one constraint and exact counters/history. Migration rejects any contradictory preexisting fresh numeric pair without rewriting or deleting it. The owner-fenced producer accepts canonical Account and fresh tenant UUIDs, re-reads the V38 association/claim and positive pair baseline, and assembles the existing complete event-free nonadmitting snapshot. It acquires upstream generation locks in composite order and never resets advanced generations or previously committed history. Local Account full check/JAR passed with 426 executed unit cases; 123 PostgreSQL cases skipped without Docker. [CI 36800321082](https://github.com/benhook1013/FireMUD/actions/runs/36800321082) on `023fcca557278efab398ecaba4f51262847cff17` executed all eight pair/migration cases successfully and all eight UUID-snapshot cases with zero skips but two fixture failures. Named enrollment/retry, advanced-generation rollback and actual concurrent Account-fence wait cases passed; the entire snapshot suite did not. Failure injection stubs a Spring `MANDATORY` proxy outside a transaction, raising `IllegalTransactionStateException` and leaving unfinished Mockito state that affects the provenance-negative case. A fixture-only correction must preserve the real production proxy/transaction and prove both cases before scoped completion; counts are from strict XML-verifier logs, diagnoses from HTML, not uploaded raw XML. Aggregate CI is red on these failures and separately owned Automation, Game Design, Ruff and dev-demo validator failures. No positive fresh JOIN, canonical Game Session request path, authenticated runtime response, credential producer or ring mount is enabled; Unit 1B remains provisional. + +The next Account-owned committed-connect source reader is an unwired prerequisite, not an authorization or credential producer. It recovers a complete successful V35 receipt and purpose-bound envelope by exact identity, checks the original compact JWT hash/JTI and asymmetric signature against the closed selected-target profile, verifies the Gateway assertion independently, and proves source/context correspondence under the Account row fence and approved retained tenant mapping. It requires the exact Game Session peer and an active owner transaction before data access, returns no raw credential, and rechecks unchanged deadlines after a fence wait. The consolidated local Account check passed with 413 unit cases executed, including 11 original-source verifier and four early-denial cases; all 105 PostgreSQL cases compiled but skipped without Docker, including the seven source-readback cases. Separately, exact #2914 head `ac8d52758384e16a2c5f1fc086af40589ad86350` [CI 36785132585](https://github.com/benhook1013/FireMUD/actions/runs/36785132585) passed its Account and Game Session jobs: the seven new PostgreSQL cases and exact-reread/fence-expiry methods each executed once with zero skips or failures, alongside the strict 30 JOIN, 9 connect-issuance, 9 bare-LOGIN storage, 2 authority-generation, 4 authority-outbox, 25 Script Pin, and 16 WebSocket cases. Aggregate CI remains red on failures outside this slice. The source reader supplies original-source evidence only—not current authority or authorization—and does not supply fresh tenant authority, an issued-token registry, protected key delivery, or a working bare-LOGIN exchange; no runtime path or mount is enabled. + +Terminal bare-`LOGIN` result recovery after original Gateway-context expiry is a selected extension of the canonical [Authentication contract](../../architecture/system-architecture-authentication.md#terminal-bare-login-result-recovery-normative), not an implemented exchange. It uses a separate fresh Account-committed connect issuance and independently signed valid Gateway context under the exact Game Session peer to reauthorize readback of the same player's complete same-target `COMMITTED` result. The original source/request/operation identity, digest, signed context, result bytes, and result expiry remain unchanged; no new token, expiry extension, expired-context `LOGIN`, or admission is permitted. Current authority, separate membership version, issuance/token fences, active result registry, applicable installation/lease/binding checks, original JWT `exp`, and the distinct envelope-recovery horizon must all pass. A local shared codec now verifies a closed signed assertion as a distinct immutable `HistoricalGatewayConnectEvidence` type; current-context readers still reject the same expired assertion. Its focused Common Security check passed with 116 executed unit cases and no skips or failures, including exact bytes, signature/key/schema/receiver/time-geometry negatives, source correspondence and strict-reader denial. This is historical signature/shape proof only, not Account source authentication, past Gateway acceptance, fresh authorization or terminal recovery eligibility. V37 still retains only the original context digest; encrypted original-context/result retention, current-authority/registry composition, complete canonical-UUID identity wiring and end-to-end recovery remain required. Existing #2914 source-reader cases are not recovery proof; live caller, ring/key-channel and runtime activation proof remain open, and bare `LOGIN`/membership paths remain denied. Account-local evidence requirements are in [Runtime & Data](../../architecture/microservices/account-service/runtime-and-data.md). Exact #2911 `78c3fe88614708a4cd224800ac0f1bd6d03b310e` [CI 36778631119](https://github.com/benhook1013/FireMUD/actions/runs/36778631119) passed both strict Account PostgreSQL gates: JOIN 30/30, connect issuance 9/9, bare-LOGIN storage 9/9, authority-generation 2/2 and authority-outbox 4/4, all zero skips/failures. The complete nonadmitting snapshot versus concurrent first-JOIN case and both exhaustion rollback methods each executed once. Game Session strict Script Pin 25/25 and WebSocket 16/16 also passed. Account and Game Session checks disabled build/configuration cache and executed their tasks; aggregate CI remains red on separately routed shared tooling, Game Design fixture and Automation formatting failures. This closes those source/component database-proof gaps, not the live authenticated snapshot, complete immutable Account evidence bundle, credential producer/registry, or end-to-end bare-LOGIN gates below. The runtime RPC and credential paths remain denied, and the ring mount remains unpublished. +The local terminal-recovery storage foundation adds `BareLoginRecoveryPayload` under the existing `BARE_LOGIN_RESPONSE` purpose, without a new purpose, persistence column, fixed TTL or activation. Its closed versioned byte frame preserves the original signed Gateway context and opaque result bytes within the existing plaintext limit, rejects unknown version/header, malformed lengths, invalid context encoding, truncation and trailing bytes, and defensively copies/redacts contents. Eight framing cases and the extended existing purpose-bound encryption/readback case passed in the composed Account check: **434 unit tests executed**, zero failures/errors/skips; Common Security's unchanged **116** passing cases were up-to-date from its preceding executed check. All **123 Account PostgreSQL tests skipped locally** without Docker. Formatting, Checkstyle, SpotBugs, JaCoCo, JAR packaging, links and Markdown passed. This is frame/crypto and historical-assertion component proof, not durable operation/envelope producer proof, fresh reauthorization, current registry/postcondition readback or a successful terminal exchange. The producer, protected ring channel/readiness and complete positive/negative end-to-end proof remain open. + Account-fenced runtime snapshot preparation reuses durable absence enrollment and exact readback for a verified never-joined pair, while retained active membership requires its existing receipt/event proof and preserved counters. Unmapped tenants, inactive membership, and absent rows with retained history remain denied; neither enrollment nor exact retry creates membership or an authority event. The pure snapshot reader still rejects an absent baseline. #2880 composes preparation with the complete typed same-snapshot response, and the executed PostgreSQL proof above covers that nonadmitting DTO against concurrent first JOIN. It does not prove an authenticated runtime RPC or admission; those paths and the Account ring mount remain disabled. The #2880 local Account check separately recorded 389 unit cases executed and all 83 discovered integration cases skipped without Docker; this is not PostgreSQL, authenticated RPC, or admission proof. @@ -34,7 +83,9 @@ The tail now includes the shared Ed25519 compact-JWS primitive and #2911's compl Account V32 holds version-bound tenant-role snapshots without backfilling retained memberships. First explicit public JOIN writes `player` with the membership and audit transaction; active membership and abandoned-`PENDING` reconciliation require exact current role and authority-event readback. The earlier reactivation role-update code is not a proved capability: it now fails closed before mutation unless a canonical current INACTIVE event exists, and no such writer is implemented. Prior CI executed 12 PostgreSQL JOIN cases and V32 migration; the corrected-head Account integration task passed, though its success artifact lacks per-test XML for exact method-level counts. Account runtime snapshot and Game Session consumption remain open. -The in-progress #2873 tenant bridge now has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact dedicated Account-tenant-migrator gRPC read, and an Account import boundary that recomputes retained V26 source evidence before storing an immutable local mapping. Neither migration auto-creates a pair; both chart Jobs are opt-in and require distinct verified workload certificates, and the runtime membership RPC remains denied. Game Design persists and reads back fresh opaque tenant UUIDs in its new-row repository, but no normal creation-to-Account handoff carries that UUID into Account membership; current JOIN still stores the retained numeric tenant key. The retained manifest path must not be reused to infer a fresh mapping. Local focused manifest, gRPC, certificate/admission, Helm-render and Account negative tests executed; Game Design's new V31 PostgreSQL case executed and passed in hosted CI, while Account's new V30 import case has reached Flyway fixture setup but lacks a passing hosted database run after its latest correction. No real signed manifest, live data association, composed owner/consumer snapshot, or runtime admission proof has been completed. Missing/conflicting rows remain denied; this is not a completed membership authority stream or Unit 1B closure. +The #2873 retained tenant bridge has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact dedicated Account-tenant-migrator gRPC read, and an Account import boundary that recomputes retained V26 source evidence before storing an immutable local mapping. Neither migration auto-creates a pair; both chart Jobs are opt-in and require distinct verified workload certificates, and the runtime membership RPC remains denied. This retained manifest remains separate from fresh identity: #2915 supplies Game Design's fresh creation/readback and Account normal-workload consumer, immutable canonical-UUID association and shared UUID claim index. Account commits that association only after exact operation/request/digest/source/receipt readback, then initializes tenant generation without reset. The earlier seven-failure Game Design fixture run `36791561008` on `6299ea128e174a5a3f55f3478929f5db71d4eb2f` remains incident evidence; it was corrected and superseded by the seven Game Design creation and six Account association PostgreSQL cases executed successfully in exact-head runs `36796087279` and `36804479170`, as recorded above. Game Design's API text no longer describes that old test failure as current missing component proof. A separate Game Session-only persisted tenant identity read/consumer is being prepared on the corrected UUID tail, preserving Account-only creation/migration guards and Game Session's sole catalog/pointer persistence ownership. Its actual catalog intake, retained runtime association, stable selector assignment, mounted-certificate/live handoff and complete admission proof remain open. No numeric Account alias, credential or runtime path is enabled, and retained manifests are not reused for fresh tenants. The wire/digest authority remains [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback); Unit 1B remains provisional. + +The corrected #2915 Account/shared-codec extension passed consolidated local full checks, formatting, Checkstyle, SpotBugs, JAR packaging, links and Markdown. Account's 422 unit cases executed with zero failures or skips in the final run; Game Design's 290 and shared-core's 106 passed on unchanged source in earlier correction runs and were up-to-date in the final gate. All 111 Account and 28 Game Design PostgreSQL cases compiled/discovered but skipped locally without Docker, including six new Account association cases and seven producer cases. The schema-selection correction and Account cross-provenance concurrency/readback require passing exact-head CI execution before database proof is credited. TLS channel construction and mocked consumer fixtures do not establish a live authenticated owner handoff, certificate rotation, fresh-image boot or runtime activation. The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and records missing non-public grant internally as `REALM_ACCESS_DENIED`; hidden/non-public definitive denials remain externally projected to generic selection guidance rather than revealing the target. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index e2caa7e627..6f182824e7 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -139,6 +139,8 @@ message VerifyEmailLoginOtpRequest { message GetTenantMembershipForRuntimeRequest { reserved 1, 2, 3; reserved "account_id", "tenant_id", "request_id"; + // account_id and tenant_id are exact canonical UUIDs, never private numeric row keys. + // The complete selected target is checked separately; this unsigned context is not authority. shared.v1.PlayerExecutionContext player_context = 4; } @@ -158,8 +160,8 @@ message GetTenantMembershipForRuntimeResponse { repeated RuntimeOutboxSourceEvidence outbox_source_evidence = 14; repeated string roles = 15; RuntimeMembershipBaseline membership_baseline = 17; - string request_account_id = 18; - string request_tenant_id = 19; + string request_account_id = 18; // Exact canonical UUID echo of player_context.account_id. + string request_tenant_id = 19; // Exact canonical UUID echo of player_context.tenant_id. string request_id = 20; } diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index ece5fc66e7..80226e85d7 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -12,6 +12,15 @@ service TenantIdentityService { // Owner-approved cross-service legacy association; Account is the sole caller. rpc ResolveLegacyAccountTenantAssociation(ResolveLegacyAccountTenantAssociationRequest) returns (ResolveLegacyAccountTenantAssociationResponse); + // Exact immutable readback of a newly created tenant operation for Account. + rpc ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) + returns (ResolveFreshTenantCreationResponse); + // Exact owner-local read of one persisted runtime tenant identity for Game Session. + rpc ResolveRuntimeTenantIdentity(ResolveRuntimeTenantIdentityRequest) + returns (ResolveRuntimeTenantIdentityResponse); + // Exact immutable authored-selector source for Game Session; not catalog enrollment. + rpc ResolveAuthoredWorldSource(ResolveAuthoredWorldSourceRequest) + returns (ResolveAuthoredWorldSourceResponse); } message ResolveLegacyGameTenantIdentityRequest { @@ -46,3 +55,60 @@ message ResolveLegacyAccountTenantAssociationResponse { string manifest_signature = 14; int32 manifest_schema_version = 15; } + +message ResolveFreshTenantCreationRequest { + string creation_request_id = 1; + string expected_request_digest = 2; +} + +message ResolveFreshTenantCreationResponse { + int32 schema_version = 1; + string target_namespace = 2; + string creation_request_id = 3; + string operation_id = 4; + string request_digest = 5; + string canonical_tenant_id = 6; + int64 source_game_row_id = 7; + string source_game_tenant_key = 8; + string provenance_kind = 9; + string evidence_digest = 10; +} + +message ResolveRuntimeTenantIdentityRequest { + string canonical_tenant_id = 1; + string request_id = 2; +} + +message ResolveRuntimeTenantIdentityResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_tenant_id = 4; + int64 source_game_row_id = 5; + string source_game_tenant_key = 6; + string provenance_kind = 7; +} + +message ResolveAuthoredWorldSourceRequest { + string request_id = 1; + string operation_id = 2; + string canonical_tenant_id = 3; + string world_slug = 4; +} + +message ResolveAuthoredWorldSourceResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string registration_request_id = 4; + string operation_id = 5; + string request_digest = 6; + string canonical_tenant_id = 7; + string tenant_slug = 8; + string world_slug = 9; + string world_display_name = 10; + int64 source_game_row_id = 11; + string source_game_tenant_key = 12; + string provenance_kind = 13; + string evidence_digest = 14; +} 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 new file mode 100644 index 0000000000..9863b2b1a7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClient.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.accountservice.client; + +import io.grpc.ClientInterceptors; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +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.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; + +/** Caller-owned Account candidate for exact fresh-creation readback from Game Design. */ +public final class GameDesignFreshTenantIdentityClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String workloadNamespace; + private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + + public GameDesignFreshTenantIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireAccountMtls(tlsProps), + channelFactory, + GameDesignFreshTenantIdentityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Account workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.serverPeerIdentityInterceptor = + new GrpcServerPeerIdentityClientInterceptor(gameDesignServerPeerUri(workloadNamespace)); + } + + /** Initializes the normal Account workload TLS client when the owner explicitly enables it. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( + ManagedChannel channel) { + return TenantIdentityServiceGrpc.newBlockingStub( + ClientInterceptors.intercept(channel, serverPeerIdentityInterceptor)) + .withCompression("gzip"); + } + + private static String gameDesignServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/game-design-service"; + } + + /** Reads the exact operation for this namespace without invoking any retained-identity RPC. */ + public FreshTenantCreationEvidence resolveCreation( + UUID creationRequestId, String expectedRequestDigest) { + if (creationRequestId == null || NIL_UUID.equals(creationRequestId)) { + throw new IllegalArgumentException("Canonical nonnil creation request ID is required"); + } + if (!GameTenantCreationDigest.isDigest(expectedRequestDigest)) { + throw new IllegalArgumentException("Canonical expected request digest is required"); + } + + ResolveFreshTenantCreationResponse response = + stub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(creationRequestId.toString()) + .setExpectedRequestDigest(expectedRequestDigest) + .build()); + + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException("Game Design fresh tenant evidence contains unknown fields"); + } + + FreshTenantCreationEvidence evidence; + try { + evidence = + new FreshTenantCreationEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getCreationRequestId()), + parseCanonicalNonNilUuid(response.getOperationId()), + response.getRequestDigest(), + parseCanonicalNonNilUuid(response.getCanonicalTenantId()), + response.getSourceGameRowId(), + response.getSourceGameTenantKey(), + response.getProvenanceKind(), + response.getEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Game Design fresh tenant evidence is invalid", exception); + } + + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !creationRequestId.equals(evidence.creationRequestId()) + || !expectedRequestDigest.equals(evidence.requestDigest())) { + throw new IllegalStateException( + "Game Design fresh tenant evidence does not match the exact request"); + } + return evidence; + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + throw new IllegalArgumentException("UUID evidence is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("UUID evidence must be canonical lowercase", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("UUID evidence must be canonical and nonnil"); + } + return parsed; + } + + private static CommonGrpcClientProperties requireAccountMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Account gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require Account workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require Account certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require file-backed Account workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java index 520c70aae3..f5baf48f6e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.client; +import io.grpc.ClientInterceptors; import jakarta.annotation.PostConstruct; import java.io.IOException; import java.util.concurrent.TimeUnit; @@ -8,9 +9,12 @@ import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; @@ -20,14 +24,26 @@ prefix = "firemud.account-tenant-migration", name = "enabled", havingValue = "true") -public class GameDesignTenantIdentityClient +public final class GameDesignTenantIdentityClient extends AbstractReloadingBlockingGrpcClient< TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + public GameDesignTenantIdentityClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, - GrpcChannelFactory channelFactory) { - super(endpoints, tlsProps, channelFactory, GameDesignTenantIdentityClient.class); + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + super( + endpoints, + requireAccountMtls(tlsProps), + channelFactory, + GameDesignTenantIdentityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Account workload namespace must be one DNS label"); + } + this.serverPeerIdentityInterceptor = + new GrpcServerPeerIdentityClientInterceptor(gameDesignServerPeerUri(workloadNamespace)); } @PostConstruct @@ -48,7 +64,41 @@ protected String defaultTarget() { @Override protected TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( io.grpc.ManagedChannel channel) { - return TenantIdentityServiceGrpc.newBlockingStub(channel).withCompression("gzip"); + return TenantIdentityServiceGrpc.newBlockingStub( + ClientInterceptors.intercept(channel, serverPeerIdentityInterceptor)) + .withCompression("gzip"); + } + + private static String gameDesignServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/game-design-service"; + } + + private static CommonGrpcClientProperties requireAccountMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Account gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Retained tenant identity reads require Account workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Retained tenant identity reads require Account certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Retained tenant identity reads require file-backed Account workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); } public ResolveLegacyAccountTenantAssociationResponse resolveApprovedAssociation(long tenantId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java index 5a30374651..79a1a7dd26 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java @@ -12,8 +12,8 @@ /** Same-fence Account snapshot candidate for the denied runtime membership RPC. */ public record RuntimeMembershipSnapshotDto( - Long requestAccountId, - Long requestTenantId, + String requestAccountUuid, + String requestTenantUuid, String accountUuid, String tenantUuid, boolean membershipExists, @@ -27,15 +27,14 @@ public record RuntimeMembershipSnapshotDto( List outboxSourceEvidence, MembershipEvent sourceEvent) { public RuntimeMembershipSnapshotDto { - if (requestAccountId == null - || requestAccountId <= 0L - || requestTenantId == null - || requestTenantId <= 0L) { - throw new IllegalArgumentException( - "Runtime membership account and tenant IDs must be positive"); - } + requestAccountUuid = requireCanonicalUuid(requestAccountUuid, "requested Account UUID"); + requestTenantUuid = requireCanonicalUuid(requestTenantUuid, "requested tenant UUID"); accountUuid = requireCanonicalUuid(accountUuid, "Account UUID"); tenantUuid = requireCanonicalUuid(tenantUuid, "tenant UUID"); + if (!requestAccountUuid.equals(accountUuid) || !requestTenantUuid.equals(tenantUuid)) { + throw new IllegalArgumentException( + "Runtime membership request identity differs from its verified Account snapshot"); + } Objects.requireNonNull(membershipBaseline, "unchanged membership baseline is required"); roles = List.copyOf(roles); Objects.requireNonNull(authorityTuple, "complete membership authority tuple is required"); @@ -152,11 +151,13 @@ private static MembershipEvent requireConsistentSourceEvent( private static String requireCanonicalUuid(String value, String field) { Objects.requireNonNull(value, field + " is required"); try { - if (!java.util.UUID.fromString(value).toString().equals(value)) { - throw new IllegalArgumentException(field + " must be a canonical lowercase UUID"); + java.util.UUID parsed = java.util.UUID.fromString(value); + if (parsed.equals(new java.util.UUID(0L, 0L)) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil canonical lowercase UUID"); } } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(field + " must be a canonical lowercase UUID", exception); + throw new IllegalArgumentException( + field + " must be a non-nil canonical lowercase UUID", exception); } return value; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java index ff09941d56..eb5aa4c58d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java @@ -8,7 +8,7 @@ public record AccountBareLoginExchangeIdentity( UUID sourceConnectOperationId, long accountId, - long tenantId, + UUID tenantId, String connectScopeId, String requestId) { @@ -17,8 +17,9 @@ public record AccountBareLoginExchangeIdentity( public AccountBareLoginExchangeIdentity { Objects.requireNonNull(sourceConnectOperationId, "sourceConnectOperationId"); - if (accountId <= 0 || tenantId <= 0) { - throw new IllegalArgumentException("Bare LOGIN account and tenant IDs must be positive"); + if (accountId <= 0 || tenantId == null || tenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "Bare LOGIN account ID and non-nil canonical tenant UUID are required"); } connectScopeId = requireText(connectScopeId, "connectScopeId"); requestId = requireText(requestId, "requestId"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java index 4aec299355..3f6241b4d3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java @@ -11,7 +11,7 @@ public record AccountBareLoginExchangeOperation( UUID operationId, UUID sourceConnectOperationId, long accountId, - long tenantId, + UUID tenantId, String connectScopeHash, String requestId, int requestDigestVersion, @@ -48,7 +48,8 @@ static Lifecycle fromDatabase(String value) { if (operationId == null || sourceConnectOperationId == null || accountId <= 0 - || tenantId <= 0 + || tenantId == null + || tenantId.equals(new UUID(0L, 0L)) || connectScopeHash == null || !SCOPE_HASH_PATTERN.matcher(connectScopeHash).matches() || requestId == null @@ -128,7 +129,7 @@ public boolean equals(Object other) { return false; } return accountId == that.accountId - && tenantId == that.tenantId + && tenantId.equals(that.tenantId) && requestDigestVersion == that.requestDigestVersion && operationId.equals(that.operationId) && sourceConnectOperationId.equals(that.sourceConnectOperationId) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java index af4f769c7f..2e032ad8d0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java @@ -500,7 +500,7 @@ private void requireCommittedSource(AccountBareLoginExchangeIdentity identity) { "Bare LOGIN exchange source connect operation is not committed"); } if (requiredLong(source, "account_id") != identity.accountId() - || requiredLong(source, "tenant_id") != identity.tenantId() + || !requiredUuid(source, "tenant_id").equals(identity.tenantId()) || !identity.connectScopeHash().equals(requiredText(source, "connect_scope_hash"))) { throw new IdentityConflictException( "Bare LOGIN exchange source connect operation identity does not match"); @@ -512,7 +512,7 @@ private static AccountBareLoginExchangeOperation toOperation(Record row) { requiredUuid(row, "operation_id"), requiredUuid(row, "source_connect_operation_id"), requiredLong(row, "account_id"), - requiredLong(row, "tenant_id"), + requiredUuid(row, "tenant_id"), requiredText(row, "connect_scope_hash"), requiredText(row, "request_id"), requiredInt(row, "request_digest_version"), @@ -541,7 +541,7 @@ private static void requireEnvelopeIdentity( .sourceConnectOperationId() .equals(requiredUuid(row, "source_connect_operation_id")) || requiredLong(row, "account_id") != identity.accountId() - || requiredLong(row, "tenant_id") != identity.tenantId() + || !requiredUuid(row, "tenant_id").equals(identity.tenantId()) || !identity.connectScopeHash().equals(requiredText(row, "connect_scope_hash")) || !identity.requestId().equals(requiredText(row, "request_id")) || requiredInt(row, "request_digest_version") != REQUEST_DIGEST_VERSION @@ -569,7 +569,7 @@ private static void validateBinding( || !operation.operationId().toString().equals(binding.operationId()) || !identity.requestId().equals(binding.requestId()) || !Long.toString(identity.accountId()).equals(binding.accountId()) - || !Long.toString(identity.tenantId()).equals(binding.tenantId()) + || !identity.tenantId().toString().equals(binding.tenantId()) || !identity.connectScopeId().equals(binding.connectScopeId()) || !identity .sourceConnectOperationId() @@ -658,7 +658,7 @@ private static void assertIdentityMatches( AccountBareLoginExchangeOperation operation, AccountBareLoginExchangeIdentity identity) { if (!identity.sourceConnectOperationId().equals(operation.sourceConnectOperationId()) || identity.accountId() != operation.accountId() - || identity.tenantId() != operation.tenantId() + || !identity.tenantId().equals(operation.tenantId()) || !identity.connectScopeHash().equals(operation.connectScopeHash()) || !identity.requestId().equals(operation.requestId())) { throw new IdentityConflictException( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java index 928010f67e..d7fbf30cc4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java @@ -29,7 +29,7 @@ public record AccountCommittedConnectSource( || !operation.operationId().toString().equals(binding.operationId()) || !operation.requestId().equals(binding.requestId()) || !Long.toString(operation.accountId()).equals(binding.accountId()) - || !Long.toString(operation.tenantId()).equals(binding.tenantId()) + || !operation.tenantId().toString().equals(binding.tenantId()) || !operation .connectScopeHash() .equals(AccountJoinDigest.tokenHash(binding.connectScopeId())) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceIdentity.java index 2648fdb7b9..96f9760880 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceIdentity.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceIdentity.java @@ -2,17 +2,19 @@ import java.nio.charset.StandardCharsets; import java.util.Objects; +import java.util.UUID; /** Exact caller-supplied identity for one durable connect-token issuance attempt. */ public record AccountConnectTokenIssuanceIdentity( - long accountId, long tenantId, String connectScopeId, String requestId) { + long accountId, UUID tenantId, String connectScopeId, String requestId) { public static final int MAX_CONNECT_SCOPE_ID_UTF8_BYTES = 2048; public static final int MAX_REQUEST_ID_LENGTH = 128; public AccountConnectTokenIssuanceIdentity { - if (accountId <= 0 || tenantId <= 0) { - throw new IllegalArgumentException("Connect-token account and tenant IDs must be positive"); + if (accountId <= 0 || tenantId == null || tenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "Connect-token account ID and non-nil canonical tenant UUID are required"); } connectScopeId = requireText(connectScopeId, "connectScopeId"); requestId = requireText(requestId, "requestId"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceOperation.java index ebd9b1ab66..9d0a4e35de 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceOperation.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceOperation.java @@ -9,7 +9,7 @@ public record AccountConnectTokenIssuanceOperation( UUID operationId, long accountId, - long tenantId, + UUID tenantId, String connectScopeHash, String requestId, int requestDigestVersion, @@ -47,7 +47,8 @@ static Lifecycle fromDatabase(String value) { public AccountConnectTokenIssuanceOperation { if (operationId == null || accountId <= 0 - || tenantId <= 0 + || tenantId == null + || tenantId.equals(new UUID(0L, 0L)) || connectScopeHash == null || requestId == null || requestDigestVersion != 1 @@ -105,7 +106,7 @@ public boolean equals(Object other) { return false; } return accountId == that.accountId - && tenantId == that.tenantId + && tenantId.equals(that.tenantId) && requestDigestVersion == that.requestDigestVersion && reconciliationAttemptCount == that.reconciliationAttemptCount && operationId.equals(that.operationId) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java index 020f06680e..8fc49f0433 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java @@ -137,7 +137,7 @@ public Optional readCommittedResponseEnvelope( operation.operationId().toString(), identity.requestId(), Long.toString(identity.accountId()), - Long.toString(identity.tenantId()), + identity.tenantId().toString(), identity.connectScopeId(), null, operation.requestDigest(), @@ -671,11 +671,11 @@ private Optional readOperation( private static AccountConnectTokenIssuanceOperation toOperation( Record row, AccountConnectTokenIssuanceIdentity identity) { long accountId = requiredLong(row, "account_id"); - long tenantId = requiredLong(row, "tenant_id"); + UUID tenantId = requiredUuid(row, "tenant_id"); String scopeHash = requiredText(row, "connect_scope_hash"); String requestId = requiredText(row, "request_id"); if (accountId != identity.accountId() - || tenantId != identity.tenantId() + || !tenantId.equals(identity.tenantId()) || !scopeHash.equals(identity.connectScopeHash()) || !requestId.equals(identity.requestId())) { throw new IllegalStateException("Connect-token issuance readback identity does not match"); @@ -713,7 +713,7 @@ private static void requireEnvelopeIdentity( if (!operation.operationId().equals(requiredUuid(row, "operation_id")) || !"CONNECT_TOKEN_ISSUANCE".equals(requiredText(row, "operation_kind")) || requiredLong(row, "account_id") != identity.accountId() - || requiredLong(row, "tenant_id") != identity.tenantId() + || !requiredUuid(row, "tenant_id").equals(identity.tenantId()) || !identity.connectScopeHash().equals(requiredText(row, "connect_scope_hash")) || !identity.requestId().equals(requiredText(row, "request_id")) || requiredInt(row, "request_digest_version") != REQUEST_DIGEST_VERSION @@ -741,7 +741,7 @@ private static void validateBinding( || !operation.operationId().toString().equals(binding.operationId()) || !identity.requestId().equals(binding.requestId()) || !Long.toString(identity.accountId()).equals(binding.accountId()) - || !Long.toString(identity.tenantId()).equals(binding.tenantId()) + || !identity.tenantId().toString().equals(binding.tenantId()) || !identity.connectScopeId().equals(binding.connectScopeId()) || !MessageDigest.isEqual(digest, binding.requestDigest())) { throw new EvidenceMismatchException( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java index 0c6b377335..5e156a70ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java @@ -10,6 +10,7 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Stores the durable Account-owned authority state for one verified Account/tenant pair. @@ -47,6 +48,7 @@ public AccountMembershipPairAuthorityRepository(DSLContext dsl) { @Transactional(propagation = Propagation.MANDATORY) public PairAuthority enrollAbsence( UUID accountUuid, UUID tenantUuid, VerifiedTenantProvenance provenance) { + requireOwnerTransaction(); requireScope(accountUuid, tenantUuid); Objects.requireNonNull(provenance, "verified tenant provenance is required"); @@ -75,7 +77,7 @@ public PairAuthority enrollAbsence( Optional readback = readForUpdate(accountUuid, tenantUuid); if (readback.isEmpty()) { - if (readByLegacyScopeForUpdate(accountUuid, provenance.legacyTenantId()).isPresent()) { + if (hasRetainedLegacyScopeCollision(accountUuid, provenance)) { throw new IllegalStateException( "Verified Account tenant association conflicts with an existing pair authority"); } @@ -106,6 +108,7 @@ public PairAuthority enrollProvenPositive( UUID tenantUuid, VerifiedTenantProvenance provenance, ProvenPositiveCheckpoint checkpoint) { + requireOwnerTransaction(); requireScope(accountUuid, tenantUuid); Objects.requireNonNull(provenance, "verified tenant provenance is required"); Objects.requireNonNull(checkpoint, "verified positive membership checkpoint is required"); @@ -154,7 +157,7 @@ public PairAuthority enrollProvenPositive( Optional readback = readForUpdate(accountUuid, tenantUuid); if (readback.isEmpty()) { - if (readByLegacyScopeForUpdate(accountUuid, provenance.legacyTenantId()).isPresent()) { + if (hasRetainedLegacyScopeCollision(accountUuid, provenance)) { throw new IllegalStateException( "Verified Account tenant association conflicts with an existing pair authority"); } @@ -174,6 +177,7 @@ public PairAuthority enrollProvenPositive( */ @Transactional(propagation = Propagation.MANDATORY) public Optional readForUpdate(UUID accountUuid, UUID tenantUuid) { + requireOwnerTransaction(); requireScope(accountUuid, tenantUuid); Record row = dsl.fetchOne( @@ -198,6 +202,7 @@ public Optional readForUpdate(UUID accountUuid, UUID tenantUuid) */ @Transactional(propagation = Propagation.MANDATORY) public PairAuthority commitTransition(PairAuthority expected, PairTransition transition) { + requireOwnerTransaction(); Objects.requireNonNull(expected, "expected pair authority is required"); Objects.requireNonNull(transition, "pair authority transition is required"); long nextVersion = increment(expected.membershipVersion(), "membership version"); @@ -229,7 +234,8 @@ public PairAuthority commitTransition(PairAuthority expected, PairTransition tra + " SET membership_exists = ?, membership_version = ?, " + "membership_authority_generation = ?, last_event_sequence = ?, " + "last_event_id = ?, last_event_digest = ?, last_transition_invalidated = ? " - + "WHERE account_uuid = ? AND tenant_uuid = ? AND legacy_tenant_id = ? " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND legacy_tenant_id IS NOT DISTINCT FROM ? " + "AND tenant_provenance_kind = ? AND tenant_source_operation_id = ? " + "AND tenant_provenance_digest = ? AND membership_exists = ? " + "AND membership_version = ? AND membership_authority_generation = ? " @@ -286,7 +292,7 @@ public PairAuthority commitTransition(PairAuthority expected, PairTransition tra } private Optional readByLegacyScopeForUpdate( - UUID accountUuid, long legacyTenantId) { + UUID accountUuid, Long legacyTenantId) { Record row = dsl.fetchOne( "SELECT " @@ -300,6 +306,12 @@ private Optional readByLegacyScopeForUpdate( return Optional.ofNullable(row).map(this::mapRow); } + private boolean hasRetainedLegacyScopeCollision( + UUID accountUuid, VerifiedTenantProvenance provenance) { + return provenance.kind() == TenantProvenanceKind.APPROVED_RETAINED + && readByLegacyScopeForUpdate(accountUuid, provenance.legacyTenantId()).isPresent(); + } + private PairAuthority mapRow(Record row) { try { return new PairAuthority( @@ -338,6 +350,13 @@ private void requireScope(UUID accountUuid, UUID tenantUuid) { } } + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account membership pair authority access requires an active owner transaction"); + } + } + private long increment(long value, String label) { try { return Math.addExact(value, 1L); @@ -359,11 +378,20 @@ public enum TenantProvenanceKind { /** Immutable verified tenant-association facts supplied by the caller. */ public record VerifiedTenantProvenance( - long legacyTenantId, TenantProvenanceKind kind, UUID sourceOperationId, String digest) { + Long legacyTenantId, TenantProvenanceKind kind, UUID sourceOperationId, String digest) { public VerifiedTenantProvenance { - if (legacyTenantId <= 0L || kind == null || sourceOperationId == null) { + if (kind == null || sourceOperationId == null) { throw new IllegalArgumentException("Verified Account tenant provenance is incomplete"); } + if (kind == TenantProvenanceKind.APPROVED_RETAINED + && (legacyTenantId == null || legacyTenantId <= 0L)) { + throw new IllegalArgumentException( + "Approved retained tenant provenance requires a positive legacy tenant ID"); + } + if (kind == TenantProvenanceKind.FRESH_GAME_DESIGN && legacyTenantId != null) { + throw new IllegalArgumentException( + "Fresh Game Design tenant provenance must not carry a legacy tenant ID"); + } requireDigest(digest, "Tenant provenance digest"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolver.java index 261a856e26..d6132e1624 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolver.java @@ -2,15 +2,14 @@ import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -/** - * Resolves retained numeric tenant keys through an approved, provenance-backed UUID association. - */ +/** Resolves retained tenant identity through its approved, provenance-backed UUID association. */ @Repository public class AccountTenantIdentityResolver { private final ApprovedLegacyTenantAssociationRepository associations; @@ -59,4 +58,36 @@ public ApprovedAssociation resolve(long legacyTenantId) { } return association; } + + /** + * Resolves an exact canonical tenant UUID only through its approved retained association and + * current source-evidence digest. Fresh UUIDs are resolved by their separate V38.1 repository. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ApprovedAssociation resolve(UUID canonicalTenantId) { + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("non-nil canonical tenant UUID is required"); + } + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalStateException("Account workload namespace is not configured"); + } + + Optional stored = associations.findByCanonicalTenantId(canonicalTenantId); + if (stored.isEmpty()) { + throw new IllegalStateException("approved Account tenant association is absent"); + } + ApprovedAssociation association = stored.orElseThrow(); + if (association.legacyTenantId() <= 0L + || !canonicalTenantId.equals(association.canonicalTenantId()) + || !workloadNamespace.equals(association.targetNamespace())) { + throw new IllegalStateException("approved Account tenant association is mismatched"); + } + + String currentEvidenceDigest = sourceEvidence.digest(association.legacyTenantId()); + if (!Objects.equals(association.accountEvidenceDigest(), currentEvidenceDigest)) { + throw new IllegalStateException( + "approved Account source evidence differs from retained rows"); + } + return association; + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java index 7fe9d53d71..e2486b0e40 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java @@ -103,25 +103,45 @@ public Optional findByLegacyTenantId(long legacyTenantId) { + "manifest_schema_version " + "FROM account_approved_legacy_tenant_associations WHERE legacy_tenant_id = ?", legacyTenantId); - return Optional.ofNullable(row) - .map( - result -> - new ApprovedAssociation( - result.get(0, Long.class), - result.get(1, UUID.class), - result.get(2, String.class), - result.get(3, Long.class), - result.get(4, String.class), - result.get(5, UUID.class), - result.get(6, String.class), - result.get(7, String.class), - result.get(8, String.class), - result.get(9, String.class), - result.get(10, String.class), - result.get(11, String.class), - result.get(12, String.class), - result.get(13, Integer.class), - result.get(14, Integer.class))); + return Optional.ofNullable(row).map(this::toAssociation); + } + + /** Exact reverse lookup for an approved retained canonical tenant identity. */ + @Transactional(readOnly = true) + public Optional findByCanonicalTenantId(UUID canonicalTenantId) { + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + return Optional.empty(); + } + Record row = + dsl.fetchOne( + "SELECT legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, " + + "manifest_schema_version " + + "FROM account_approved_legacy_tenant_associations " + + "WHERE canonical_tenant_id = ? AND identity_kind = 'APPROVED_RETAINED'", + canonicalTenantId); + return Optional.ofNullable(row).map(this::toAssociation); + } + + private ApprovedAssociation toAssociation(Record result) { + return new ApprovedAssociation( + result.get(0, Long.class), + result.get(1, UUID.class), + result.get(2, String.class), + result.get(3, Long.class), + result.get(4, String.class), + result.get(5, UUID.class), + result.get(6, String.class), + result.get(7, String.class), + result.get(8, String.class), + result.get(9, String.class), + result.get(10, String.class), + result.get(11, String.class), + result.get(12, String.class), + result.get(13, Integer.class), + result.get(14, Integer.class)); } private ApprovedAssociation requireExactResponse( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationRepository.java new file mode 100644 index 0000000000..6c5ef0dd03 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationRepository.java @@ -0,0 +1,248 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Persists and reads back Account's immutable association for an authenticated fresh tenant. This + * primitive does not enroll membership or make the association a runtime selector. + */ +@Repository +public class FreshTenantIdentityAssociationRepository { + private final DSLContext dsl; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The injected owner DSLContext is retained privately, never exposed or copied.") + public FreshTenantIdentityAssociationRepository( + DSLContext dsl, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.dsl = dsl; + this.workloadNamespace = workloadNamespace; + } + + /** + * Stores one exact Game Design operation receipt and returns its immutable Account readback. + * + *

The caller owns the transaction boundary so association persistence can be composed with the + * subsequent Account tenant-generation initialization. A Spring proxy's mandatory propagation is + * supplemented by an explicit active-transaction check for direct construction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public FreshTenantCreationEvidence importVerified(FreshTenantCreationEvidence expected) { + requireExpectedNamespace(expected); + requireActiveTransaction(); + + int inserted = + dsl.execute( + "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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + expected.schemaVersion(), + expected.targetNamespace(), + expected.creationRequestId(), + expected.operationId(), + expected.requestDigest(), + expected.canonicalTenantId(), + expected.sourceGameRowId(), + expected.sourceGameTenantKey(), + expected.provenanceKind(), + expected.evidenceDigest()); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Fresh Account tenant association insert was ambiguous"); + } + + FreshTenantCreationEvidence committed = + readVerified(expected.canonicalTenantId()) + .orElseThrow( + () -> + new IdentityAssociationConflictException( + "Fresh Account tenant identity conflicts with an existing canonical claim")); + if (!committed.equals(expected)) { + throw new IdentityAssociationConflictException( + "Fresh Account tenant association conflicts with exact operation readback"); + } + return committed; + } + + /** Reads only a complete fresh association whose canonical UUID claim and source tuple agree. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional read(UUID canonicalTenantId) { + Objects.requireNonNull(canonicalTenantId, "Canonical tenant UUID is required"); + if (canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical tenant UUID must be non-nil"); + } + requireWorkloadNamespace(); + requireActiveTransaction(); + return readVerified(canonicalTenantId); + } + + private Optional readVerified(UUID canonicalTenantId) { + Record association = + dsl.fetchOne( + "SELECT 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 " + + "FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + Record claim = + dsl.fetchOne( + "SELECT canonical_tenant_id, identity_kind, source_operation_id, " + + "source_account_legacy_tenant_id, " + + "source_target_namespace, source_creation_request_id, source_request_digest, " + + "source_game_row_id, source_game_tenant_key, source_provenance_kind, " + + "source_evidence_digest, source_manifest_digest " + + "FROM account_canonical_tenant_identity_claims WHERE canonical_tenant_id = ?", + canonicalTenantId); + + if (association == null) { + if (claim != null && "FRESH_GAME_DESIGN".equals(claim.get("identity_kind", String.class))) { + throw new InvalidTenantIdentityEvidenceException( + "Fresh canonical tenant claim has no Account source association"); + } + return Optional.empty(); + } + + Integer schemaVersion = association.get("schema_version", Integer.class); + String targetNamespace = association.get("target_namespace", String.class); + UUID creationRequestId = association.get("creation_request_id", UUID.class); + UUID operationId = association.get("operation_id", UUID.class); + String requestDigest = association.get("request_digest", String.class); + UUID storedCanonicalTenantId = association.get("canonical_tenant_id", UUID.class); + Long sourceGameRowId = association.get("source_game_row_id", Long.class); + String sourceGameTenantKey = association.get("source_game_tenant_key", String.class); + String provenanceKind = association.get("provenance_kind", String.class); + String evidenceDigest = association.get("evidence_digest", String.class); + if (schemaVersion == null + || targetNamespace == null + || creationRequestId == null + || operationId == null + || requestDigest == null + || storedCanonicalTenantId == null + || sourceGameRowId == null + || sourceGameTenantKey == null + || provenanceKind == null + || evidenceDigest == null) { + throw new InvalidTenantIdentityEvidenceException( + "Fresh Account association is missing required operation evidence"); + } + if (claim == null || !claimMatches(association, claim)) { + throw new InvalidTenantIdentityEvidenceException( + "Fresh Account association does not match its canonical tenant claim"); + } + + try { + FreshTenantCreationEvidence evidence = + new FreshTenantCreationEvidence( + schemaVersion, + targetNamespace, + creationRequestId, + operationId, + requestDigest, + storedCanonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + if (!workloadNamespace.equals(evidence.targetNamespace())) { + throw new InvalidTenantIdentityEvidenceException( + "Fresh Account association namespace differs from the configured namespace"); + } + return Optional.of(evidence); + } catch (IllegalArgumentException exception) { + throw new InvalidTenantIdentityEvidenceException( + "Fresh Account association contains invalid operation evidence", exception); + } + } + + private boolean claimMatches(Record association, Record claim) { + return "FRESH_GAME_DESIGN".equals(claim.get("identity_kind", String.class)) + && Objects.equals( + association.get("canonical_tenant_id", UUID.class), + claim.get("canonical_tenant_id", UUID.class)) + && Objects.equals( + association.get("target_namespace", String.class), + claim.get("source_target_namespace", String.class)) + && Objects.equals( + association.get("creation_request_id", UUID.class), + claim.get("source_creation_request_id", UUID.class)) + && Objects.equals( + association.get("operation_id", UUID.class), + claim.get("source_operation_id", UUID.class)) + && Objects.equals( + association.get("request_digest", String.class), + claim.get("source_request_digest", String.class)) + && Objects.equals( + association.get("source_game_row_id", Long.class), + claim.get("source_game_row_id", Long.class)) + && Objects.equals( + association.get("source_game_tenant_key", String.class), + claim.get("source_game_tenant_key", String.class)) + && Objects.equals( + association.get("provenance_kind", String.class), + claim.get("source_provenance_kind", String.class)) + && Objects.equals( + association.get("evidence_digest", String.class), + claim.get("source_evidence_digest", String.class)) + && claim.get("source_account_legacy_tenant_id", Long.class) == null + && claim.get("source_manifest_digest", String.class) == null; + } + + private void requireExpectedNamespace(FreshTenantCreationEvidence expected) { + Objects.requireNonNull(expected, "Game Design creation evidence is required"); + requireWorkloadNamespace(); + if (!workloadNamespace.equals(expected.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design creation evidence namespace differs from the configured namespace"); + } + } + + private void requireWorkloadNamespace() { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException("Account workload namespace is missing or invalid"); + } + } + + private void requireActiveTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Fresh Account tenant association access requires an active owner transaction"); + } + if (dsl == null) { + throw new IllegalStateException("Fresh Account tenant association DSLContext is unavailable"); + } + } + + /** A conflicting identity/request/operation cannot be imported as a fresh association. */ + public static final class IdentityAssociationConflictException extends IllegalStateException { + public IdentityAssociationConflictException(String message) { + super(message); + } + } + + /** Stored association, source claim, or receipt evidence is corrupt or incomplete. */ + public static final class InvalidTenantIdentityEvidenceException extends IllegalStateException { + public InvalidTenantIdentityEvidenceException(String message) { + super(message); + } + + public InvalidTenantIdentityEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java index 3cf47cbf1c..cbc2bd00dc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Set; import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; import tools.jackson.core.StreamReadFeature; import tools.jackson.core.json.JsonFactory; import tools.jackson.databind.DeserializationFeature; @@ -105,13 +106,61 @@ public AccountGameplayConnectSourceVerifier( */ public Map verify(String compactJwt) { try { - return verifyInternal(compactJwt); + SignedCompactSource source = verifySignedCompactSource(compactJwt); + Instant now = clock.instant(); + validateIssuerAudienceAndTimeAt(source.claims(), now); + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + source.claims(), now.getEpochSecond(), SAFE_PROJECTION_CORRELATION_ID); + return deepImmutableObject(source.claims()); } catch (RuntimeException | GeneralSecurityException ex) { throw invalidToken(); } } - private Map verifyInternal(String compactJwt) throws GeneralSecurityException { + /** + * Verifies an Account gameplay-connect source only as historical evidence for an already + * signature-verified Gateway assertion. The Gateway assertion's signed {@code verifiedAt} is the + * source-time anchor; this method does not change or backdate this verifier's clock. + * + *

The returned value is deliberately distinct from the current source claim map. It proves the + * Account signature and closed source profile, plus exact correspondence to the supplied + * historical Gateway projection. It does not prove that Gateway accepted the assertion, that the + * source was durably issued, or that any current authority, registry, recovery, or admission + * condition holds. The compact Account JWT is not retained. + * + *

Every verification failure has the same sanitized exception message. Neither the source + * token nor detailed parser or cryptographic failures are retained. + * + * @param compactJwt compact Account-signed JWT + * @param historicalGatewayEvidence Gateway evidence produced by the historical Gateway codec + * @return immutable Account source claims and their historical Gateway correspondence + * @throws IllegalArgumentException if either assertion is malformed, untrusted, or mismatched + */ + public HistoricalAccountGameplayConnectEvidence verifyHistorical( + String compactJwt, HistoricalGatewayConnectEvidence historicalGatewayEvidence) { + try { + if (historicalGatewayEvidence == null) { + throw invalidToken(); + } + SignedCompactSource source = verifySignedCompactSource(compactJwt); + BigInteger gatewayVerifiedAt = historicalGatewayEvidence.integer("verifiedAt"); + if (gatewayVerifiedAt == null || gatewayVerifiedAt.signum() <= 0) { + throw invalidToken(); + } + Instant originalGatewayVerificationTime = + Instant.ofEpochSecond(gatewayVerifiedAt.longValueExact()); + validateIssuerAudienceAndTimeAt(source.claims(), originalGatewayVerificationTime); + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesHistoricalGatewayEvidence( + source.claims(), historicalGatewayEvidence); + return new HistoricalAccountGameplayConnectEvidence( + source.keyId(), deepImmutableObject(source.claims()), historicalGatewayEvidence); + } catch (RuntimeException | GeneralSecurityException ex) { + throw invalidToken(); + } + } + + private SignedCompactSource verifySignedCompactSource(String compactJwt) + throws GeneralSecurityException { String[] segments = splitCanonicalCompactJwt(compactJwt); byte[] protectedHeaderBytes = decodeCanonicalBase64Url(segments[0]); byte[] payloadBytes = decodeCanonicalBase64Url(segments[1]); @@ -133,12 +182,7 @@ private Map verifyInternal(String compactJwt) throws GeneralSecu verifySignature(segments[0], segments[1], signatureBytes, key, jcaAlgorithm); Map sourceClaims = parseJsonObject(payloadBytes); - Instant now = clock.instant(); - validateIssuerAudienceAndTime(sourceClaims, now); - - GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( - sourceClaims, now.getEpochSecond(), SAFE_PROJECTION_CORRELATION_ID); - return deepImmutableObject(sourceClaims); + return new SignedCompactSource(kid, sourceClaims); } private String[] splitCanonicalCompactJwt(String compactJwt) { @@ -246,7 +290,7 @@ private void verifySignature( } } - private void validateIssuerAudienceAndTime(Map claims, Instant now) { + private void validateIssuerAudienceAndTimeAt(Map claims, Instant validationTime) { if (!exactIssuer.equals(claims.get("iss")) || !(claims.get("iss") instanceof String) || !"gameplay-connect".equals(claims.get("aud"))) { @@ -260,9 +304,9 @@ private void validateIssuerAudienceAndTime(Map claims, Instant n try { Instant issuedAtInstant = Instant.ofEpochSecond(issuedAt.longValueExact()); Instant expiresAtInstant = Instant.ofEpochSecond(expiresAt.longValueExact()); - if (!now.isBefore(expiresAtInstant) + if (!validationTime.isBefore(expiresAtInstant) || issuedAt - .subtract(BigInteger.valueOf(now.getEpochSecond())) + .subtract(BigInteger.valueOf(validationTime.getEpochSecond())) .compareTo(BigInteger.valueOf(MAX_FUTURE_ISSUED_AT_SECONDS)) > 0) { throw invalidToken(); @@ -334,4 +378,6 @@ private static boolean isSupportedKey(PublicKey key) { private static IllegalArgumentException invalidToken() { return new IllegalArgumentException(INVALID_TOKEN_MESSAGE); } + + private record SignedCompactSource(String keyId, Map claims) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayload.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayload.java new file mode 100644 index 0000000000..7bce98a427 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayload.java @@ -0,0 +1,174 @@ +package net.firedevops.firemud.accountservice.security; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; + +/** + * Bounded storage framing for the exact original bare-LOGIN Gateway assertion and result bytes. + * + *

This payload is intended only for encryption with {@link + * AccountEnvelopePurpose#BARE_LOGIN_RESPONSE} and the matching durable operation binding. It does + * not verify either signature, establish current authorization, or determine recovery eligibility. + */ +public final class BareLoginRecoveryPayload { + private static final byte[] MAGIC = new byte[] {'F', 'M', 'B', 'R'}; + private static final int VERSION = 1; + private static final int HEADER_BYTES = Integer.BYTES * 4; + + private final byte[] originalGatewayContextUtf8; + private final byte[] originalResultBytes; + + private BareLoginRecoveryPayload(byte[] originalGatewayContextUtf8, byte[] originalResultBytes) { + this.originalGatewayContextUtf8 = + Objects.requireNonNull(originalGatewayContextUtf8, "original Gateway context is required") + .clone(); + this.originalResultBytes = + Objects.requireNonNull(originalResultBytes, "original result is required").clone(); + validateContext(this.originalGatewayContextUtf8); + validateResult(this.originalResultBytes); + requireFrameWithinLimit( + this.originalGatewayContextUtf8.length, this.originalResultBytes.length); + } + + /** Creates a frame from the exact compact Gateway envelope and exact opaque result bytes. */ + public static BareLoginRecoveryPayload of( + String exactOriginalGatewayContext, byte[] exactOriginalResultBytes) { + Objects.requireNonNull(exactOriginalGatewayContext, "original Gateway context is required"); + if (exactOriginalGatewayContext.isEmpty() + || exactOriginalGatewayContext.chars().anyMatch(character -> character > 0x7f)) { + throw invalid("Original Gateway context must be non-empty ASCII compact data"); + } + return new BareLoginRecoveryPayload( + exactOriginalGatewayContext.getBytes(StandardCharsets.UTF_8), exactOriginalResultBytes); + } + + /** Decodes one complete version-1 frame, rejecting truncation and trailing data. */ + public static BareLoginRecoveryPayload decode(byte[] encodedFrame) { + Objects.requireNonNull(encodedFrame, "encoded frame is required"); + if (encodedFrame.length < HEADER_BYTES || encodedFrame.length > maxFrameBytes()) { + throw invalid("Bare LOGIN recovery payload length is invalid"); + } + + ByteBuffer input = ByteBuffer.wrap(encodedFrame).order(ByteOrder.BIG_ENDIAN); + byte[] magic = new byte[MAGIC.length]; + input.get(magic); + if (!Arrays.equals(MAGIC, magic)) { + throw invalid("Bare LOGIN recovery payload header is invalid"); + } + if (input.getInt() != VERSION) { + throw invalid("Bare LOGIN recovery payload version is unsupported"); + } + + int contextLength = input.getInt(); + if (contextLength <= 0 || contextLength > input.remaining() - Integer.BYTES) { + throw invalid("Bare LOGIN recovery payload context length is invalid"); + } + byte[] context = new byte[contextLength]; + input.get(context); + + int resultLength = input.getInt(); + if (resultLength <= 0 || resultLength != input.remaining()) { + throw invalid("Bare LOGIN recovery payload result length is invalid"); + } + byte[] result = new byte[resultLength]; + input.get(result); + return new BareLoginRecoveryPayload(context, result); + } + + /** Returns a newly encoded, versioned frame suitable for Account envelope encryption. */ + public byte[] encode() { + int frameLength = + Math.addExact( + HEADER_BYTES, + Math.addExact(originalGatewayContextUtf8.length, originalResultBytes.length)); + requireFrameWithinLimit(originalGatewayContextUtf8.length, originalResultBytes.length); + ByteBuffer output = ByteBuffer.allocate(frameLength).order(ByteOrder.BIG_ENDIAN); + output.put(MAGIC); + output.putInt(VERSION); + output.putInt(originalGatewayContextUtf8.length); + output.put(originalGatewayContextUtf8); + output.putInt(originalResultBytes.length); + output.put(originalResultBytes); + return output.array(); + } + + /** Returns the exact original ASCII compact envelope as UTF-8 bytes. */ + public byte[] originalGatewayContextUtf8() { + return originalGatewayContextUtf8.clone(); + } + + /** Returns the exact compact envelope text, without parsing or verifying its JWS. */ + public String originalGatewayContext() { + return new String(originalGatewayContextUtf8, StandardCharsets.UTF_8); + } + + /** Returns the exact opaque result bytes without text decoding or normalization. */ + public byte[] originalResultBytes() { + return originalResultBytes.clone(); + } + + @Override + public String toString() { + return "BareLoginRecoveryPayload[version=" + + VERSION + + ", gatewayContextBytes=" + + originalGatewayContextUtf8.length + + ", resultBytes=" + + originalResultBytes.length + + ", contents=]"; + } + + private static void validateContext(byte[] context) { + final String decoded; + try { + decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(context)) + .toString(); + } catch (CharacterCodingException exception) { + throw invalid("Original Gateway context is not valid UTF-8"); + } + if (decoded.chars().anyMatch(character -> character > 0x7f)) { + throw invalid("Original Gateway context must be ASCII compact data"); + } + int firstDot = decoded.indexOf('.'); + int secondDot = firstDot < 0 ? -1 : decoded.indexOf('.', firstDot + 1); + if (firstDot <= 0 + || secondDot <= firstDot + 1 + || secondDot == decoded.length() - 1 + || decoded.indexOf('.', secondDot + 1) >= 0) { + throw invalid("Original Gateway context must contain three non-empty compact segments"); + } + } + + private static void validateResult(byte[] result) { + if (result.length == 0) { + throw invalid("Original bare LOGIN result must not be empty"); + } + } + + private static void requireFrameWithinLimit(int contextLength, int resultLength) { + long frameLength = (long) HEADER_BYTES + contextLength + resultLength; + if (contextLength <= 0 + || resultLength <= 0 + || frameLength > AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES) { + throw invalid("Bare LOGIN recovery payload exceeds its storage bound"); + } + } + + private static int maxFrameBytes() { + return AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES; + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/HistoricalAccountGameplayConnectEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/HistoricalAccountGameplayConnectEvidence.java new file mode 100644 index 0000000000..35631d6cba --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/HistoricalAccountGameplayConnectEvidence.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.accountservice.security; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; + +/** + * Immutable Account source claims verified against a previously signed Gateway assertion. + * + *

This is historical provenance only. It does not prove original durable issuance, past Gateway + * acceptance, current authority, registry state, recovery eligibility, or gameplay admission. It is + * not a current source claim or a {@code GatewayConnectContext}, and it never retains the compact + * Account JWT. + */ +public final class HistoricalAccountGameplayConnectEvidence { + private final String accountKeyId; + private final Map sourceClaims; + private final HistoricalGatewayConnectEvidence gatewayEvidence; + + HistoricalAccountGameplayConnectEvidence( + String accountKeyId, + Map sourceClaims, + HistoricalGatewayConnectEvidence gatewayEvidence) { + if (accountKeyId == null || accountKeyId.isBlank()) { + throw new IllegalArgumentException("Account source key identifier is required"); + } + this.accountKeyId = accountKeyId; + this.sourceClaims = immutableObject(sourceClaims); + this.gatewayEvidence = Objects.requireNonNull(gatewayEvidence, "Gateway evidence is required"); + } + + public String accountKeyId() { + return accountKeyId; + } + + /** Returns an immutable, recursively copied view of the verified Account source claims. */ + public Map sourceClaims() { + return immutableObject(sourceClaims); + } + + /** Returns the distinct historical Gateway evidence used for exact source correspondence. */ + public HistoricalGatewayConnectEvidence gatewayEvidence() { + return gatewayEvidence; + } + + @Override + public String toString() { + return "HistoricalAccountGameplayConnectEvidence[accountKeyId=" + + accountKeyId + + ", gatewayKeyId=" + + gatewayEvidence.kid() + + ", historical=true]"; + } + + private static Map immutableObject(Map source) { + Objects.requireNonNull(source, "source claims are required"); + Map copy = new LinkedHashMap<>(); + source.forEach((key, value) -> copy.put(key, immutableValue(value))); + return Collections.unmodifiableMap(copy); + } + + private static Object immutableValue(Object value) { + if (value == null + || value instanceof String + || value instanceof Boolean + || value instanceof BigInteger + || value instanceof BigDecimal) { + return value; + } + if (value instanceof Map source) { + Map copy = new LinkedHashMap<>(); + source.forEach( + (key, nested) -> { + if (!(key instanceof String text)) { + throw new IllegalArgumentException("source claim object keys must be strings"); + } + copy.put(text, immutableValue(nested)); + }); + return Collections.unmodifiableMap(copy); + } + if (value instanceof List source) { + List copy = new ArrayList<>(source.size()); + source.forEach(nested -> copy.add(immutableValue(nested))); + return Collections.unmodifiableList(copy); + } + throw new IllegalArgumentException("unsupported verified source claim value"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java index 7f3f21d132..8a40264a6e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; @@ -25,13 +26,17 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.security.HistoricalAccountGameplayConnectEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.GatewayConnectContext; import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -45,17 +50,20 @@ public final class AccountCommittedConnectSourceReader { private final AccountConnectTokenIssuanceRepository issuanceRepository; private final AccountRepository accountRepository; private final AccountTenantIdentityResolver tenantIdentityResolver; + private final FreshTenantIdentityAssociationRepository freshTenantIdentityRepository; private final AccountJoinOperationRepository joinOperationRepository; private final AccountEnvelopeCrypto envelopeCrypto; private final AccountGameplayConnectSourceVerifier sourceVerifier; private final Map gatewayVerificationKeys; private final Clock clock; + private final String workloadNamespace; private final String expectedGameSessionPeerUri; public AccountCommittedConnectSourceReader( AccountConnectTokenIssuanceRepository issuanceRepository, AccountRepository accountRepository, AccountTenantIdentityResolver tenantIdentityResolver, + FreshTenantIdentityAssociationRepository freshTenantIdentityRepository, AccountJoinOperationRepository joinOperationRepository, AccountEnvelopeCrypto envelopeCrypto, AccountGameplayConnectSourceVerifier sourceVerifier, @@ -66,6 +74,8 @@ public AccountCommittedConnectSourceReader( this.accountRepository = Objects.requireNonNull(accountRepository, "accountRepository"); this.tenantIdentityResolver = Objects.requireNonNull(tenantIdentityResolver, "tenantIdentityResolver"); + this.freshTenantIdentityRepository = + Objects.requireNonNull(freshTenantIdentityRepository, "freshTenantIdentityRepository"); this.joinOperationRepository = Objects.requireNonNull(joinOperationRepository, "joinOperationRepository"); this.envelopeCrypto = Objects.requireNonNull(envelopeCrypto, "envelopeCrypto"); @@ -78,6 +88,7 @@ public AccountCommittedConnectSourceReader( if (workloadNamespace == null || workloadNamespace.isBlank()) { throw new IllegalArgumentException("Account workload namespace is required"); } + this.workloadNamespace = workloadNamespace; this.expectedGameSessionPeerUri = GrpcPeerIdentity.parseUri( "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") @@ -89,7 +100,7 @@ public AccountCommittedConnectSourceReader( /** * Reads and verifies one original committed source in the caller's owner transaction. The exact - * Game Session peer, Gateway assertion, account fence, retained tenant association, source + * Game Session peer, Gateway assertion, account fence, canonical tenant association, source * envelope, Account JWT signature/profile, and complete source/context correspondence are all * checked before returning immutable evidence. */ @@ -107,7 +118,8 @@ public OriginalSourceEvidence read( // The same Account row fence serializes this identity/provenance read with JOIN and other // fenced Account work. The retained tenant association resolver separately verifies its - // approved row and exact current source-evidence digest in this owner transaction. + // exact fresh source claim or approved retained row and current source-evidence digest in this + // owner transaction. joinOperationRepository.lockAccount(identity.accountId()); Account account = accountRepository @@ -116,12 +128,8 @@ public OriginalSourceEvidence read( UUID accountUuid = requireAccountIdentity(account, identity.accountId()); requireContextValue(initialContext, "accountId", accountUuid.toString()); - ApprovedAssociation tenantAssociation = tenantIdentityResolver.resolve(identity.tenantId()); - if (tenantAssociation.legacyTenantId() != identity.tenantId()) { - throw new IllegalStateException("Account source tenant identity is mismatched"); - } - requireContextValue( - initialContext, "tenantId", tenantAssociation.canonicalTenantId().toString()); + UUID canonicalTenantId = requireTenantIdentity(identity.tenantId()); + requireContextValue(initialContext, "tenantId", canonicalTenantId.toString()); AccountCommittedConnectSource committedSource = issuanceRepository @@ -173,6 +181,78 @@ public OriginalSourceEvidence read( } } + /** + * Reads one exact, already-committed V35 Account source as historical provenance, using the + * caller-supplied signed original Gateway assertion to anchor source-time verification. This + * proves the committed source and its correspondence to that supplied assertion only. It does not + * prove that a V37 frame retained the original Gateway context, that Gateway accepted it, fresh + * authorization, current authority, registry readiness, result recovery eligibility, or + * admission. It cannot be used in place of {@link #read} or a current Gateway context. + */ + @Transactional(propagation = Propagation.MANDATORY) + public HistoricalCommittedSourceEvidence readHistorical( + AccountConnectTokenIssuanceIdentity identity, String signedOriginalGatewayAssertion) { + Objects.requireNonNull(identity, "identity"); + requireGameSessionPeer(); + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Committed Account source readback requires an active owner transaction"); + } + HistoricalGatewayConnectEvidence historicalGatewayEvidence = + GatewayConnectContextCodec.verifyHistoricalEvidence( + signedOriginalGatewayAssertion, gatewayVerificationKeys); + requireContextRequestIdentity(identity, historicalGatewayEvidence); + + // Keep the same Account row fence, canonical UUID provenance, and fresh-or-retained tenant + // resolver as strict-current source readback. The historical assertion changes neither the + // source identity nor the transaction/data-access boundary. + joinOperationRepository.lockAccount(identity.accountId()); + Account account = + accountRepository + .findById(identity.accountId()) + .orElseThrow(() -> new IllegalStateException("Account source identity is absent")); + UUID accountUuid = requireAccountIdentity(account, identity.accountId()); + requireContextValue(historicalGatewayEvidence, "accountId", accountUuid.toString()); + + UUID canonicalTenantId = requireTenantIdentity(identity.tenantId()); + requireContextValue(historicalGatewayEvidence, "tenantId", canonicalTenantId.toString()); + + AccountCommittedConnectSource committedSource = + issuanceRepository + .readCommittedResponseEnvelope(identity) + .orElseThrow(() -> new IllegalStateException("Committed Account source is absent")); + byte[] compactJwtBytes = + envelopeCrypto.decrypt( + committedSource.responseEnvelope().envelope(), + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + committedSource.responseEnvelope().binding()); + try { + String compactJwt = decodeStrictUtf8(compactJwtBytes); + byte[] actualTokenHash = sha256(compactJwtBytes); + if (!MessageDigest.isEqual(committedSource.operation().tokenHash(), actualTokenHash)) { + throw new IllegalStateException("Committed Account source token hash does not match"); + } + + HistoricalAccountGameplayConnectEvidence historicalSourceEvidence = + sourceVerifier.verifyHistorical(compactJwt, historicalGatewayEvidence); + Map sourceClaims = historicalSourceEvidence.sourceClaims(); + if (!Objects.equals(sourceClaims.get("jti"), committedSource.operation().tokenIdentity())) { + throw new IllegalStateException("Committed Account source token identity does not match"); + } + + return new HistoricalCommittedSourceEvidence( + committedSource.operation().operationId(), + committedSource.responseEnvelope().envelope().keyId(), + actualTokenHash, + historicalSourceEvidence.accountKeyId(), + historicalGatewayEvidence.kid(), + sourceClaims, + historicalGatewayEvidence.claims()); + } finally { + java.util.Arrays.fill(compactJwtBytes, (byte) 0); + } + } + private GatewayConnectContext verifyGatewayContext(String signedGatewayContext) { return GatewayConnectContextCodec.verifyAndDecode( signedGatewayContext, gatewayVerificationKeys, clock); @@ -186,6 +266,26 @@ private void requireGameSessionPeer() { } } + private UUID requireTenantIdentity(UUID canonicalTenantId) { + Optional fresh = + freshTenantIdentityRepository.read(canonicalTenantId); + if (fresh.isPresent()) { + FreshTenantCreationEvidence evidence = fresh.orElseThrow(); + if (!canonicalTenantId.equals(evidence.canonicalTenantId()) + || !workloadNamespace.equals(evidence.targetNamespace())) { + throw new IllegalStateException("Fresh Account tenant identity evidence is mismatched"); + } + return evidence.canonicalTenantId(); + } + + ApprovedAssociation retained = tenantIdentityResolver.resolve(canonicalTenantId); + if (!canonicalTenantId.equals(retained.canonicalTenantId()) + || !workloadNamespace.equals(retained.targetNamespace())) { + throw new IllegalStateException("Retained Account tenant identity evidence is mismatched"); + } + return retained.canonicalTenantId(); + } + private static void requireContextRequestIdentity( AccountConnectTokenIssuanceIdentity identity, GatewayConnectContext context) { if (!identity.connectScopeId().equals(context.text("connectScopeId")) @@ -195,6 +295,16 @@ private static void requireContextRequestIdentity( } } + private static void requireContextRequestIdentity( + AccountConnectTokenIssuanceIdentity identity, + HistoricalGatewayConnectEvidence historicalContext) { + if (!identity.connectScopeId().equals(historicalContext.text("connectScopeId")) + || !identity.requestId().equals(historicalContext.text("connectRequestId"))) { + throw new IllegalArgumentException( + "Gateway context does not match the exact Account source request identity"); + } + } + private static UUID requireAccountIdentity(Account account, long numericAccountId) { if (account.getId() == null || account.getId() != numericAccountId @@ -211,7 +321,15 @@ private static void requireContextValue( GatewayConnectContext context, String field, String expectedValue) { if (!expectedValue.equals(context.text(field))) { throw new IllegalArgumentException( - "Gateway context does not match the retained Account " + field); + "Gateway context does not match the Account " + field + " identity"); + } + } + + private static void requireContextValue( + HistoricalGatewayConnectEvidence historicalContext, String field, String expectedValue) { + if (!expectedValue.equals(historicalContext.text(field))) { + throw new IllegalArgumentException( + "Gateway context does not match the Account " + field + " identity"); } } @@ -309,4 +427,49 @@ private static Object immutableValue(Object value) { throw new IllegalArgumentException("unsupported verified claim value"); } } + + /** + * Immutable readback of a committed V35 source matched to a caller-supplied historical Gateway + * assertion. This is source/correspondence provenance only; it does not establish retained V37 + * context, past Gateway acceptance, fresh or current authorization, registry state, recovery + * eligibility, or admission. It retains neither compact Account JWT nor signed Gateway envelope. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Verified claim maps and nested JSON values are deeply copied into immutable containers " + + "by the canonical constructor before record accessors expose them") + public record HistoricalCommittedSourceEvidence( + UUID operationId, + String responseEnvelopeKeyId, + byte[] sourceTokenHash, + String accountSourceKeyId, + String gatewayKeyId, + Map originalSourceClaims, + Map historicalGatewayClaims) { + public HistoricalCommittedSourceEvidence { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(accountSourceKeyId, "accountSourceKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + if (sourceTokenHash == null || sourceTokenHash.length != 32) { + throw new IllegalArgumentException("source token hash must be 32 bytes"); + } + sourceTokenHash = sourceTokenHash.clone(); + originalSourceClaims = OriginalSourceEvidence.immutableObject(originalSourceClaims); + historicalGatewayClaims = OriginalSourceEvidence.immutableObject(historicalGatewayClaims); + } + + @Override + public byte[] sourceTokenHash() { + return sourceTokenHash.clone(); + } + + @Override + public String toString() { + return "HistoricalCommittedSourceEvidence[operationId=" + + operationId + + ", committedSource=, historicalGateway=]"; + } + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 32aac78520..e0da0f7d3c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -41,15 +41,18 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; 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.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Produces the Account-owned V33 authority event for an explicit public-production JOIN. */ +/** Coordinates Account-owned membership authority events and fenced snapshot evidence. */ @Service @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -64,6 +67,7 @@ public class AccountMembershipAuthorityEventProducer { private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; private final AccountRepository accountRepository; private final AccountTenantIdentityResolver tenantIdentityResolver; + private final FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository; private final AccountAuthorityGenerationRepository authorityGenerationRepository; private final AccountAuthorityOutboxRepository authorityOutboxRepository; private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; @@ -75,6 +79,7 @@ public AccountMembershipAuthorityEventProducer( AccountMembershipPairAuthorityRepository pairAuthorityRepository, AccountRepository accountRepository, AccountTenantIdentityResolver tenantIdentityResolver, + FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository, AccountAuthorityGenerationRepository authorityGenerationRepository, AccountAuthorityOutboxRepository authorityOutboxRepository, AccountMembershipTransitionReceiptRepository transitionReceiptRepository, @@ -84,6 +89,7 @@ public AccountMembershipAuthorityEventProducer( this.pairAuthorityRepository = pairAuthorityRepository; this.accountRepository = accountRepository; this.tenantIdentityResolver = tenantIdentityResolver; + this.freshTenantIdentityAssociationRepository = freshTenantIdentityAssociationRepository; this.authorityGenerationRepository = authorityGenerationRepository; this.authorityOutboxRepository = authorityOutboxRepository; this.transitionReceiptRepository = transitionReceiptRepository; @@ -302,6 +308,100 @@ public PositiveMembershipSnapshot readCurrentPairBoundPositiveMembershipSnapshot return positive; } + /** + * Reads only an already-existing positive membership for exact canonical Account and tenant + * UUIDs, under the Account owner transaction and row fence. + * + *

This is membership evidence, not complete current authorization or terminal-recovery + * eligibility. It never prepares, enrolls, initializes, or transitions membership authority. + * Fresh tenant associations currently have only non-admitting membership state and are denied; + * retained membership must have complete exact current row, role, receipt, event, pair, and + * generation/fence readback. Missing, inactive, incomplete, or contradictory state fails closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PositiveMembershipSnapshot readExistingPairBoundPositiveMembershipSnapshot( + UUID accountUuid, UUID tenantUuid) { + requireActiveOwnerTransaction(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + + Account initialAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> new IllegalStateException("Membership snapshot Account row is absent")); + requirePersistedAccountIdentity(initialAccount, accountUuid); + long accountId = initialAccount.getId(); + + // Match JOIN's lock order: the numeric Account row is private fence provenance, never a + // request identity or tenant alias. Re-read its immutable UUID mapping after acquiring it. + joinOperationRepository.lockAccount(accountId); + Account fencedAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Membership snapshot Account row disappeared at its fence")); + requirePersistedAccountIdentity(fencedAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), fencedAccount.getId()) + || initialAccount.getAccountUuidProvenance() != fencedAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + fencedAccount.getAccountUuidSourceNumericId())) { + throw new IllegalStateException( + "Membership snapshot Account identity changed at its row fence"); + } + + Optional freshAssociation = + freshTenantIdentityAssociationRepository.read(tenantUuid); + if (freshAssociation.isPresent()) { + if (!tenantUuid.equals(freshAssociation.orElseThrow().canonicalTenantId())) { + throw new IllegalStateException( + "Fresh tenant association differs from its canonical UUID scope"); + } + throw new IllegalStateException( + "Fresh tenant membership has no positive current Account membership readback"); + } + + ApprovedAssociation retainedAssociation = tenantIdentityResolver.resolve(tenantUuid); + if (retainedAssociation.legacyTenantId() <= 0L + || !tenantUuid.equals(retainedAssociation.canonicalTenantId())) { + throw new IllegalStateException( + "Retained tenant UUID has no exact approved private-row association"); + } + + PositiveMembershipSnapshot positive = + readCurrentPairBoundPositiveMembershipSnapshot( + accountId, retainedAssociation.legacyTenantId()); + if (!accountUuid.toString().equals(positive.accountId()) + || !tenantUuid.toString().equals(positive.tenantId())) { + throw new IllegalStateException( + "Current Account membership differs from its canonical UUID request"); + } + + // Recheck both identity sources after reading membership history. The Account lock remains + // held, and the resolver repeats its current retained-row digest check. + Account finalAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Membership snapshot Account row disappeared before readback")); + requirePersistedAccountIdentity(finalAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), finalAccount.getId()) + || initialAccount.getAccountUuidProvenance() != finalAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + finalAccount.getAccountUuidSourceNumericId()) + || !retainedAssociation.equals(tenantIdentityResolver.resolve(tenantUuid))) { + throw new IllegalStateException( + "Canonical Account or retained tenant identity changed during membership readback"); + } + return positive; + } + /** * Reads one same-fence runtime membership result from the proved active-positive or never-joined * sequence-zero path. @@ -321,8 +421,8 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( PositiveMembershipSnapshot positive = readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId); return new RuntimeMembershipSnapshotDto( - accountId, - legacyTenantId, + positive.accountId(), + positive.tenantId(), positive.accountId(), positive.tenantId(), positive.membershipExists(), @@ -343,8 +443,8 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( NeverJoinedMembershipSnapshot absent = readNeverJoinedMembershipSnapshot(accountId, legacyTenantId); return new RuntimeMembershipSnapshotDto( - accountId, - legacyTenantId, + absent.accountId(), + absent.tenantId(), absent.accountId(), absent.tenantId(), absent.membershipExists(), @@ -362,6 +462,91 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( null); } + /** + * Resolves canonical Account and tenant UUIDs to one owner-fenced runtime membership snapshot. + * Fresh tenants use only their immutable V38.1 association and never receive a numeric alias; + * retained tenants must resolve through the exact approved UUID association and source digest. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( + UUID accountUuid, UUID tenantUuid) { + requireActiveOwnerTransaction(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + + Account initialAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Runtime snapshot Account row is absent")); + requirePersistedAccountIdentity(initialAccount, accountUuid); + long accountId = initialAccount.getId(); + + // The persisted Account row is the owner fence for every subsequent identity/history read. + joinOperationRepository.lockAccount(accountId); + Account fencedAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Runtime snapshot Account row disappeared at its fence")); + requirePersistedAccountIdentity(fencedAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), fencedAccount.getId()) + || initialAccount.getAccountUuidProvenance() != fencedAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + fencedAccount.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Runtime snapshot Account identity changed at its row fence"); + } + + Optional freshAssociation = + freshTenantIdentityAssociationRepository.read(tenantUuid); + if (freshAssociation.isPresent()) { + NeverJoinedMembershipSnapshot absent = + readFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid); + return toRuntimeMembershipSnapshot(absent); + } + + ApprovedAssociation retainedAssociation = tenantIdentityResolver.resolve(tenantUuid); + if (retainedAssociation.legacyTenantId() <= 0L + || !tenantUuid.equals(retainedAssociation.canonicalTenantId())) { + throw new IllegalStateException( + "Retained tenant UUID has no exact private numeric association"); + } + RuntimeMembershipSnapshotDto retained = + readRuntimeMembershipSnapshot(accountId, retainedAssociation.legacyTenantId()); + if (!accountUuid.toString().equals(retained.accountUuid()) + || !tenantUuid.toString().equals(retained.tenantUuid()) + || !accountUuid.toString().equals(retained.requestAccountUuid()) + || !tenantUuid.toString().equals(retained.requestTenantUuid())) { + throw new IllegalStateException( + "Retained numeric membership readback differs from its exact canonical UUID request"); + } + return retained; + } + + private RuntimeMembershipSnapshotDto toRuntimeMembershipSnapshot( + NeverJoinedMembershipSnapshot absent) { + return new RuntimeMembershipSnapshotDto( + absent.accountId(), + absent.tenantId(), + absent.accountId(), + absent.tenantId(), + false, + false, + new RuntimeMembershipSnapshotDto.MembershipBaseline( + absent.membershipLifecycleState(), + absent.membershipVersion(), + absent.membershipAuthorityGeneration()), + List.of(), + absent.authorityTuple(), + absent.issuanceFence(), + absent.evaluatedAt(), + absent.outboxCheckpoints(), + absent.outboxSourceEvidence(), + null); + } + /** * Reads an explicit sequence-zero checkpoint only from a durable verified pair baseline, after * the no-membership and no-committed-history proof under one Account-row fence. It never admits @@ -379,19 +564,114 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( throw new IllegalStateException("Never-joined Account membership row is not absent"); } transitionReceiptRepository.assertNewMembershipTransitionCanStart(accountId, legacyTenantId); + return assembleNeverJoinedMembershipSnapshot( + identity.accountUuid(), identity.tenantUuid(), verifiedProvenance(identity)); + } + + /** + * Enrolls and reads the non-admitting baseline for one exact Game Design-issued tenant UUID. + * + *

The Account row is the transaction fence. The UUID-to-UUID fresh association is read only + * after that row is locked and reread, and no numeric tenant selector or alias is accepted or + * derived. This prepares local authority evidence only; it does not create membership, an event, + * a credential, or an enabled runtime RPC. + */ + @Transactional(propagation = Propagation.MANDATORY) + public NeverJoinedMembershipSnapshot readFreshNeverJoinedMembershipSnapshot( + UUID accountUuid, UUID tenantUuid) { + requireActiveOwnerTransaction(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + + Account initialAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Fresh snapshot Account row is absent")); + requirePersistedAccountIdentity(initialAccount, accountUuid); + long accountId = initialAccount.getId(); + + // Preserve the JOIN lock order: acquire the numeric Account-row lock before consulting tenant + // provenance, pair authority, or any membership-snapshot input. + joinOperationRepository.lockAccount(accountId); + Account fencedAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh snapshot Account row disappeared at fence")); + requirePersistedAccountIdentity(fencedAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), fencedAccount.getId()) + || initialAccount.getAccountUuidProvenance() != fencedAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + fencedAccount.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Fresh snapshot Account identity changed at its row fence"); + } + + FreshTenantCreationEvidence evidence = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh Game Design tenant association is absent")); + if (!tenantUuid.equals(evidence.canonicalTenantId())) { + throw new IllegalStateException( + "Fresh Game Design tenant association differs from its canonical UUID scope"); + } + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + evidence.operationId(), + evidence.evidenceDigest()); + + // Take upstream generation/fence locks in the composite reader's canonical order before the + // membership initializer takes its Account/tenant locks. The Account entity row remains the + // outer owner fence, and the full composite snapshot is reread below after enrollment. + CompositeSnapshot upstream = lockUpstreamAuthorityScopes(accountUuid, tenantUuid); + requireFreshUpstreamSequenceZeroBaseline(accountUuid, tenantUuid, upstream); + + String membershipStreamKey = membershipStreamKey(accountUuid, tenantUuid); + Optional existingPair = + pairAuthorityRepository.readForUpdate(accountUuid, tenantUuid); + if (existingPair.isEmpty()) { + if (authorityOutboxRepository.readCheckpoint(membershipStreamKey).isPresent()) { + throw new IllegalStateException( + "Absent fresh Account membership has retained authority-event history"); + } + ScopeState generation = + authorityGenerationRepository.initialize( + AuthorityScope.membership(accountUuid, tenantUuid)); + if (generation.generation() != 1L || generation.sourceVersion() != 1L) { + throw new IllegalStateException( + "Fresh never-joined Account membership generation did not initialize at one"); + } + } + + PairAuthority pair = pairAuthorityRepository.enrollAbsence(accountUuid, tenantUuid, provenance); + if (!provenance.equals(pair.provenance()) + || pair.membershipExists() + || pair.membershipVersion() != 1L + || pair.lastEventSequence() != 0L) { + throw new IllegalStateException( + "Fresh never-joined Account membership differs from its positive pair baseline"); + } + return assembleNeverJoinedMembershipSnapshot(accountUuid, tenantUuid, provenance); + } + + private NeverJoinedMembershipSnapshot assembleNeverJoinedMembershipSnapshot( + UUID accountUuid, UUID tenantUuid, VerifiedTenantProvenance provenance) { PairAuthority pair = pairAuthorityRepository - .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .readForUpdate(accountUuid, tenantUuid) .orElseThrow(() -> new IllegalStateException("Never-joined pair baseline is absent")); - CompositeSnapshot authority = readSnapshot(identity); + CompositeSnapshot authority = readSnapshot(accountUuid, tenantUuid); ScopeState member = only(authority.memberships(), "membership"); - requireMatchingFence(authority, member, identity.accountUuid()); + requireMatchingFence(authority, member, accountUuid); List upstreamCheckpoints = - readBaselineUpstreamCheckpoints(identity, authority); - String streamKey = membershipStreamKey(identity); + readBaselineUpstreamCheckpoints(accountUuid, tenantUuid, authority); + String streamKey = membershipStreamKey(accountUuid, tenantUuid); OutboxCheckpointEntry membershipCheckpoint = requireSequenceZeroCheckpoint(streamKey, member, "membership"); - if (!verifiedProvenance(identity).equals(pair.provenance()) + if (!provenance.equals(pair.provenance()) || pair.membershipExists() || pair.lastEventSequence() != 0L || pair.membershipVersion() != 1L @@ -404,9 +684,8 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( decimal(authority.issuer().generation()), decimal(authority.account().generation()), Map.of( - identity.tenantUuid().toString(), - decimal(only(authority.tenants(), "tenant").generation())), - Map.of(identity.tenantUuid().toString(), decimal(member.generation())), + tenantUuid.toString(), decimal(only(authority.tenants(), "tenant").generation())), + Map.of(tenantUuid.toString(), decimal(member.generation())), List.of(), Optional.empty(), Optional.empty()); @@ -414,9 +693,9 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( checkpoints.add(membershipCheckpoint); checkpoints = orderedCheckpoints(checkpoints); return new NeverJoinedMembershipSnapshot( - identity.accountUuid().toString(), - identity.tenantUuid().toString(), - Map.of(identity.tenantUuid().toString(), decimal(pair.membershipVersion())), + accountUuid.toString(), + tenantUuid.toString(), + Map.of(tenantUuid.toString(), decimal(pair.membershipVersion())), decimal(pair.membershipAuthorityGeneration()), tuple, decimal(authority.issuanceFence().value()), @@ -426,6 +705,29 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( List.of()); } + private void requireFreshUpstreamSequenceZeroBaseline( + UUID accountUuid, UUID tenantUuid, CompositeSnapshot snapshot) { + ScopeState tenant = only(snapshot.tenants(), "tenant"); + if (!AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER) + .equals(snapshot.issuer().scope()) + || !AuthorityScope.account(accountUuid).equals(snapshot.account().scope()) + || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) + || !snapshot.memberships().isEmpty() + || !accountUuid.equals(snapshot.issuanceFence().accountId()) + || !snapshot.issuanceFence().equals(snapshot.account().issuanceFence())) { + throw new IllegalStateException( + "Fresh Account authority snapshot does not cover its exact issuer/account/tenant scopes"); + } + requireSequenceZeroCheckpoint(accountStreamKey(accountUuid), snapshot.account(), "account"); + requireSequenceZeroCheckpoint(issuerStreamKey(), snapshot.issuer(), "issuer"); + requireSequenceZeroCheckpoint(tenantStreamKey(tenantUuid), tenant, "tenant"); + } + + private CompositeSnapshot lockUpstreamAuthorityScopes(UUID accountUuid, UUID tenantUuid) { + return authorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, accountUuid, List.of(tenantUuid), List.of()); + } + /** * Establishes a committed never-joined baseline before a separate JOIN transaction may consume * it. A retained active row is enrolled only from its exact current positive event/receipt proof; @@ -441,6 +743,7 @@ public void preparePairAuthorityForJoin(long accountId, long legacyTenantId) { return; } + lockUpstreamAuthorityScopes(identity.accountUuid(), identity.tenantUuid()); transitionReceiptRepository.assertNewMembershipTransitionCanStart(accountId, legacyTenantId); if (authorityOutboxRepository.readCheckpoint(membershipStreamKey(identity)).isPresent()) { throw new IllegalStateException( @@ -1109,12 +1412,17 @@ private static int compareUnsignedUtf8(String left, String right) { private List readBaselineUpstreamCheckpoints( Identity identity, CompositeSnapshot snapshot) { + return readBaselineUpstreamCheckpoints(identity.accountUuid(), identity.tenantUuid(), snapshot); + } + + private List readBaselineUpstreamCheckpoints( + UUID accountUuid, UUID tenantUuid, CompositeSnapshot snapshot) { ScopeState tenant = only(snapshot.tenants(), "tenant"); if (!AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER) .equals(snapshot.issuer().scope()) - || !AuthorityScope.account(identity.accountUuid()).equals(snapshot.account().scope()) - || !AuthorityScope.tenant(identity.tenantUuid()).equals(tenant.scope()) - || !AuthorityScope.membership(identity.accountUuid(), identity.tenantUuid()) + || !AuthorityScope.account(accountUuid).equals(snapshot.account().scope()) + || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) + || !AuthorityScope.membership(accountUuid, tenantUuid) .equals(only(snapshot.memberships(), "membership").scope())) { throw new IllegalStateException( "Account authority snapshot does not cover the exact issuer/account/tenant scopes"); @@ -1123,10 +1431,9 @@ private List readBaselineUpstreamCheckpoints( return orderedCheckpoints( List.of( requireSequenceZeroCheckpoint( - accountStreamKey(identity.accountUuid()), snapshot.account(), "account"), + accountStreamKey(accountUuid), snapshot.account(), "account"), requireSequenceZeroCheckpoint(issuerStreamKey(), snapshot.issuer(), "issuer"), - requireSequenceZeroCheckpoint( - tenantStreamKey(identity.tenantUuid()), tenant, "tenant"))); + requireSequenceZeroCheckpoint(tenantStreamKey(tenantUuid), tenant, "tenant"))); } private OutboxCheckpointEntry requireSequenceZeroCheckpoint( @@ -1199,11 +1506,15 @@ private RoleSnapshot requireRoleSnapshot(Identity identity, AccountTenantMembers } private CompositeSnapshot readSnapshot(Identity identity) { + return readSnapshot(identity.accountUuid(), identity.tenantUuid()); + } + + private CompositeSnapshot readSnapshot(UUID accountUuid, UUID tenantUuid) { return authorityGenerationRepository.readCompositeSnapshot( AccountServiceImpl.ACCOUNT_JWT_ISSUER, - identity.accountUuid(), - List.of(identity.tenantUuid()), - List.of(identity.tenantUuid())); + accountUuid, + List.of(tenantUuid), + List.of(tenantUuid)); } private void requireMatchingFence( @@ -1253,6 +1564,31 @@ private Identity resolveIdentity(long accountId, long legacyTenantId) { association); } + private void requirePersistedAccountIdentity(Account account, UUID expectedAccountUuid) { + if (account == null + || account.getId() == null + || account.getId() <= 0L + || !expectedAccountUuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { + throw new IllegalStateException( + "Fresh snapshot Account UUID does not exactly identify its persisted row"); + } + } + + private void requireCanonicalUuidInput(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil canonical UUID"); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Fresh Account membership snapshot requires an active owner transaction"); + } + } + private VerifiedTenantProvenance verifiedProvenance(Identity identity) { ApprovedAssociation association = identity.association(); return new VerifiedTenantProvenance( @@ -1286,11 +1622,15 @@ private void requireActiveMembership(AccountTenantMembership membership) { } private String membershipStreamKey(Identity identity) { + return membershipStreamKey(identity.accountUuid(), identity.tenantUuid()); + } + + private String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "membership/" - + identity.accountUuid() + + accountUuid + "/" - + identity.tenantUuid(); + + tenantUuid; } private String issuerStreamKey() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReader.java new file mode 100644 index 0000000000..4ca9f0bce7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReader.java @@ -0,0 +1,592 @@ +package net.firedevops.firemud.accountservice.service; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeOperation; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginResponseEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.BareLoginRecoveryPayload; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.HistoricalCommittedSourceEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired, non-authorizing readback of one committed bare-LOGIN response frame and its original + * committed connect source. It never releases or retains the opaque original result, compact JWT, + * or original signed Gateway context. + */ +public final class AccountStoredBareLoginRecoveryReader { + private final AccountBareLoginExchangeRepository exchangeRepository; + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountEnvelopeCrypto envelopeCrypto; + private final AccountCommittedConnectSourceReader committedSourceReader; + private final Map gatewayVerificationKeys; + private final String expectedGameSessionPeerUri; + + public AccountStoredBareLoginRecoveryReader( + AccountBareLoginExchangeRepository exchangeRepository, + AccountJoinOperationRepository joinOperationRepository, + AccountEnvelopeCrypto envelopeCrypto, + AccountCommittedConnectSourceReader committedSourceReader, + Map gatewayVerificationKeys, + String workloadNamespace) { + this.exchangeRepository = Objects.requireNonNull(exchangeRepository, "exchangeRepository"); + this.joinOperationRepository = + Objects.requireNonNull(joinOperationRepository, "joinOperationRepository"); + this.envelopeCrypto = Objects.requireNonNull(envelopeCrypto, "envelopeCrypto"); + this.committedSourceReader = + Objects.requireNonNull(committedSourceReader, "committedSourceReader"); + this.gatewayVerificationKeys = Map.copyOf(gatewayVerificationKeys); + if (this.gatewayVerificationKeys.isEmpty()) { + throw new IllegalArgumentException("Gateway verification keys are required"); + } + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Account workload namespace is required"); + } + this.expectedGameSessionPeerUri = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .filter(identity -> workloadNamespace.equals(identity.namespace())) + .map(GrpcPeerIdentity::uri) + .orElseThrow( + () -> new IllegalArgumentException("Account workload namespace is invalid")); + } + + /** + * Verifies committed encrypted V37/V35 provenance for an exact bare-LOGIN exchange identity and + * its caller-supplied immutable request digest. The stored frame is decoded only to verify its + * result hash and original historical Gateway/source correspondence; result bytes are never + * returned. + * + *

This proves stored framed provenance only. It does not prove prior Gateway acceptance, + * current authority, freshness, the original result expiry or recovery horizon, registry state, + * admission postconditions, recovery eligibility, or authorization. It does not release a + * credential or enable the bare-LOGIN runtime path. + */ + @Transactional(propagation = Propagation.MANDATORY) + public HistoricalStoredBareLoginEvidence readHistorical( + AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + Objects.requireNonNull(identity, "identity"); + requireGameSessionPeer(); + requireOwnerTransaction(); + return readHistoricalStored(identity, requestDigest).evidence(); + } + + /** + * Correlates exact stored original exchange/source history with a separately committed, strictly + * current Account connect source and its independently valid current Gateway context. This is + * only immutable source/target correspondence evidence: it does not prove current authority or + * membershipVersion, original result expiry, registry state, admission postconditions, recovery + * eligibility, or authorization, and releases no result, credential, JWT, or signed context. + */ + @Transactional(propagation = Propagation.MANDATORY) + public HistoricalStoredBareLoginCorrelationEvidence readCorrelation( + AccountBareLoginExchangeIdentity originalIdentity, + byte[] originalRequestDigest, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext) { + Objects.requireNonNull(originalIdentity, "originalIdentity"); + Objects.requireNonNull(freshIdentity, "freshIdentity"); + Objects.requireNonNull(signedFreshGatewayContext, "signedFreshGatewayContext"); + requireGameSessionPeer(); + requireOwnerTransaction(); + if (originalIdentity.accountId() != freshIdentity.accountId() + || !originalIdentity.tenantId().equals(freshIdentity.tenantId())) { + throw new IllegalArgumentException( + "Original and fresh source identities must belong to the same Account and tenant"); + } + + // Establish the independent strict-current source first. Its Account reader checks the signed + // Gateway deadline again after any Account-fence wait, before this component reads the opaque + // stored original result frame. + var fresh = committedSourceReader.read(freshIdentity, signedFreshGatewayContext); + if (originalIdentity.sourceConnectOperationId().equals(fresh.operationId())) { + throw new IllegalStateException( + "Fresh connect proof must be a separate committed Account source operation"); + } + HistoricalReadback original = readHistoricalStored(originalIdentity, originalRequestDigest); + + SelectedTargetEvidence originalTarget = + selectedTarget(original.source().originalSourceClaims()); + SelectedTargetEvidence freshTarget = selectedTarget(fresh.originalSourceClaims()); + if (!originalTarget.equals(freshTarget)) { + throw new IllegalStateException( + "Fresh connect source does not select the exact original Account target"); + } + + // The original encrypted frame read can itself take time after the strict source reader's + // fence recheck. Re-run the unchanged strict-current path immediately before returning so an + // assertion that expires during history work cannot yield correlation evidence. + var finalFresh = committedSourceReader.read(freshIdentity, signedFreshGatewayContext); + requireSameCurrentReadback(fresh, finalFresh); + + return new HistoricalStoredBareLoginCorrelationEvidence( + original.evidence(), + connectSourceIdentity(original.source()), + connectSourceIdentity(freshIdentity, finalFresh), + originalTarget); + } + + private HistoricalReadback readHistoricalStored( + AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + byte[] checkedRequestDigest = requireDigest(requestDigest, "request digest"); + byte[] frameBytes = null; + byte[] originalGatewayContextBytes = null; + byte[] originalResultBytes = null; + byte[] originalResultHash = null; + byte[] storedResultHash = null; + byte[] sourceConnectTokenHash = null; + try { + // This is the same Account row fence used by the original-source reader. No operation, + // envelope, key-ring or signed-context access happens before the exact caller guard above. + joinOperationRepository.lockAccount(identity.accountId()); + + AccountBareLoginExchangeOperation operation = + exchangeRepository + .find(identity, checkedRequestDigest) + .orElseThrow(() -> new IllegalStateException("Bare LOGIN exchange source is absent")); + if (operation.lifecycle() != AccountBareLoginExchangeOperation.Lifecycle.COMMITTED + || !"SUCCESS".equals(operation.outcomeCode()) + || !operation.sourceConnectOperationId().equals(identity.sourceConnectOperationId()) + || operation.accountId() != identity.accountId() + || !operation.tenantId().equals(identity.tenantId()) + || !operation + .connectScopeHash() + .equals(AccountJoinDigest.tokenHash(identity.connectScopeId())) + || !operation.requestId().equals(identity.requestId()) + || !MessageDigest.isEqual(operation.requestDigest(), checkedRequestDigest)) { + throw new IllegalStateException("Bare LOGIN exchange is not the exact committed success"); + } + + AccountEnvelopeBinding binding = bindingFor(operation, identity); + AccountBareLoginResponseEnvelope responseEnvelope = + exchangeRepository + .readResponseEnvelope(identity, checkedRequestDigest, binding) + .orElseThrow( + () -> new IllegalStateException("Committed bare LOGIN response is absent")); + if (!operation.operationId().equals(responseEnvelope.operationId()) + || !binding.equals(responseEnvelope.binding()) + || responseEnvelope.envelope().purpose() != AccountEnvelopePurpose.BARE_LOGIN_RESPONSE) { + throw new IllegalStateException( + "Bare LOGIN response envelope does not match its operation"); + } + + frameBytes = + envelopeCrypto.decrypt( + responseEnvelope.envelope(), + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + responseEnvelope.binding()); + BareLoginRecoveryPayload payload = BareLoginRecoveryPayload.decode(frameBytes); + originalResultBytes = payload.originalResultBytes(); + originalResultHash = sha256(originalResultBytes); + storedResultHash = operation.tokenHash(); + if (!MessageDigest.isEqual(storedResultHash, originalResultHash)) { + throw new IllegalStateException( + "Stored bare LOGIN result hash does not match its operation"); + } + + originalGatewayContextBytes = payload.originalGatewayContextUtf8(); + String originalGatewayContext = + new String(originalGatewayContextBytes, StandardCharsets.UTF_8); + HistoricalGatewayConnectEvidence gatewayEvidence = + GatewayConnectContextCodec.verifyHistoricalEvidence( + originalGatewayContext, gatewayVerificationKeys); + if (!identity.connectScopeId().equals(gatewayEvidence.text("connectScopeId"))) { + throw new IllegalArgumentException( + "Stored original Gateway context does not match the bare LOGIN connect scope"); + } + String sourceConnectRequestId = gatewayEvidence.text("connectRequestId"); + if (sourceConnectRequestId == null || sourceConnectRequestId.isBlank()) { + throw new IllegalArgumentException( + "Stored original Gateway context has no source connect request identity"); + } + + HistoricalCommittedSourceEvidence sourceEvidence = + committedSourceReader.readHistorical( + new AccountConnectTokenIssuanceIdentity( + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + sourceConnectRequestId), + originalGatewayContext); + if (!identity.sourceConnectOperationId().equals(sourceEvidence.operationId()) + || !gatewayEvidence.kid().equals(sourceEvidence.gatewayKeyId()) + || !gatewayEvidence.claims().equals(sourceEvidence.historicalGatewayClaims())) { + throw new IllegalStateException( + "Stored bare LOGIN source does not match its original Gateway context"); + } + sourceConnectTokenHash = sourceEvidence.sourceTokenHash(); + + HistoricalStoredBareLoginEvidence storedEvidence = + new HistoricalStoredBareLoginEvidence( + operation.operationId(), + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + operation.requestId(), + operation.connectScopeHash(), + operation.requestDigestVersion(), + checkedRequestDigest, + originalResultHash, + sourceConnectTokenHash, + responseEnvelope.envelope().keyId(), + sourceEvidence.responseEnvelopeKeyId(), + sourceEvidence.accountSourceKeyId(), + sourceEvidence.gatewayKeyId(), + gatewayEvidence.integer("verifiedAt"), + gatewayEvidence.integer("expiresAt")); + return new HistoricalReadback(storedEvidence, sourceEvidence); + } finally { + Arrays.fill(checkedRequestDigest, (byte) 0); + wipe(frameBytes); + wipe(originalGatewayContextBytes); + wipe(originalResultBytes); + wipe(originalResultHash); + wipe(storedResultHash); + wipe(sourceConnectTokenHash); + } + } + + private AccountEnvelopeBinding bindingFor( + AccountBareLoginExchangeOperation operation, AccountBareLoginExchangeIdentity identity) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operation.operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + identity.tenantId().toString(), + identity.connectScopeId(), + identity.sourceConnectOperationId().toString(), + operation.requestDigest(), + operation.contextEvidenceDigest(), + operation.authorityTupleDigest(), + operation.issuanceFenceDigest(), + operation.postconditionDigest()); + } + + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Stored bare LOGIN history readback requires an active owner transaction"); + } + } + + private static ConnectSourceIdentityEvidence connectSourceIdentity( + HistoricalCommittedSourceEvidence evidence) { + Map claims = evidence.originalSourceClaims(); + Map gateway = evidence.historicalGatewayClaims(); + return new ConnectSourceIdentityEvidence( + evidence.operationId(), + requireText(claims, "requestId"), + AccountJoinDigest.tokenHash(requireText(claims, "connectScopeId")), + requireText(claims, "jti"), + evidence.sourceTokenHash(), + evidence.responseEnvelopeKeyId(), + evidence.accountSourceKeyId(), + evidence.gatewayKeyId(), + requireInteger(claims, "iat"), + requireInteger(claims, "exp"), + requireInteger(gateway, "verifiedAt"), + requireInteger(gateway, "expiresAt")); + } + + private static ConnectSourceIdentityEvidence connectSourceIdentity( + AccountConnectTokenIssuanceIdentity identity, + AccountCommittedConnectSourceReader.OriginalSourceEvidence evidence) { + Map claims = evidence.originalSourceClaims(); + Map gateway = evidence.gatewayContextClaims(); + return new ConnectSourceIdentityEvidence( + evidence.operationId(), + identity.requestId(), + AccountJoinDigest.tokenHash(identity.connectScopeId()), + requireText(claims, "jti"), + evidence.sourceTokenHash(), + evidence.responseEnvelopeKeyId(), + null, + evidence.gatewayKeyId(), + requireInteger(claims, "iat"), + requireInteger(claims, "exp"), + requireInteger(gateway, "verifiedAt"), + requireInteger(gateway, "expiresAt")); + } + + private static SelectedTargetEvidence selectedTarget(Map claims) { + return new SelectedTargetEvidence( + requireText(claims, "accountId"), + requireText(claims, "tenantId"), + requireText(claims, "realmId"), + requireText(claims, "worldSlug"), + requireText(claims, "realmSlug"), + requireText(claims, "playableStateNamespaceId"), + requireText(claims, "playableStateScope"), + requireText(claims, "gameInstanceId"), + requireInteger(claims, "catalogRevision"), + requireInteger(claims, "pointerVersion"), + optionalText(claims, "playtestLifecycleId"), + optionalInteger(claims, "playtestStateGeneration")); + } + + private static void requireSameCurrentReadback( + AccountCommittedConnectSourceReader.OriginalSourceEvidence first, + AccountCommittedConnectSourceReader.OriginalSourceEvidence last) { + if (!first.operationId().equals(last.operationId()) + || !first.responseEnvelopeKeyId().equals(last.responseEnvelopeKeyId()) + || !MessageDigest.isEqual(first.sourceTokenHash(), last.sourceTokenHash()) + || !first.gatewayKeyId().equals(last.gatewayKeyId()) + || !first.originalSourceClaims().equals(last.originalSourceClaims()) + || !first.gatewayContextClaims().equals(last.gatewayContextClaims())) { + throw new IllegalStateException("Fresh Account source changed during history correlation"); + } + } + + private static String requireText(Map claims, String field) { + Object value = claims.get(field); + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalStateException("Verified connect source is missing a required target fact"); + } + return text; + } + + private static String optionalText(Map claims, String field) { + if (!claims.containsKey(field)) { + return null; + } + return requireText(claims, field); + } + + private static BigInteger requireInteger(Map claims, String field) { + Object value = claims.get(field); + if (!(value instanceof BigInteger integer)) { + throw new IllegalStateException("Verified connect source is missing a required time fact"); + } + return integer; + } + + private static BigInteger optionalInteger(Map claims, String field) { + if (!claims.containsKey(field)) { + return null; + } + return requireInteger(claims, field); + } + + private void requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !expectedGameSessionPeerUri.equals(peer.uri())) { + throw new AdminAuthorizationException( + "Stored bare LOGIN history readback requires the exact Game Session workload identity"); + } + } + + private static byte[] requireDigest(byte[] value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.length != 32) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return value.clone(); + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + private record HistoricalReadback( + HistoricalStoredBareLoginEvidence evidence, HistoricalCommittedSourceEvidence source) {} + + /** Immutable provenance facts only; no original result, JWT, Gateway context, or claims. */ + public record HistoricalStoredBareLoginEvidence( + UUID exchangeOperationId, + UUID sourceConnectOperationId, + long accountId, + UUID tenantId, + String requestId, + String connectScopeHash, + int requestDigestVersion, + byte[] requestDigest, + byte[] originalResultHash, + byte[] sourceConnectTokenHash, + String responseEnvelopeKeyId, + String sourceResponseEnvelopeKeyId, + String accountSourceKeyId, + String gatewayKeyId, + java.math.BigInteger signedGatewayVerifiedAt, + java.math.BigInteger signedGatewayExpiresAt) { + public HistoricalStoredBareLoginEvidence { + Objects.requireNonNull(exchangeOperationId, "exchangeOperationId"); + Objects.requireNonNull(sourceConnectOperationId, "sourceConnectOperationId"); + if (accountId <= 0 + || tenantId == null + || tenantId.equals(new UUID(0L, 0L)) + || requestDigestVersion != 1) { + throw new IllegalArgumentException("Stored bare LOGIN provenance identity is invalid"); + } + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(connectScopeHash, "connectScopeHash"); + requestDigest = requireDigest(requestDigest, "request digest"); + originalResultHash = requireDigest(originalResultHash, "original result hash"); + sourceConnectTokenHash = requireDigest(sourceConnectTokenHash, "source connect-token hash"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(sourceResponseEnvelopeKeyId, "sourceResponseEnvelopeKeyId"); + Objects.requireNonNull(accountSourceKeyId, "accountSourceKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + Objects.requireNonNull(signedGatewayVerifiedAt, "signedGatewayVerifiedAt"); + Objects.requireNonNull(signedGatewayExpiresAt, "signedGatewayExpiresAt"); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] originalResultHash() { + return originalResultHash.clone(); + } + + @Override + public byte[] sourceConnectTokenHash() { + return sourceConnectTokenHash.clone(); + } + + @Override + public String toString() { + return "HistoricalStoredBareLoginEvidence[exchangeOperationId=" + + exchangeOperationId + + ", sourceConnectOperationId=" + + sourceConnectOperationId + + ", requestId=, result=, originalGateway=]"; + } + } + + /** Separate original/fresh V35 identities and selected target; not an authorization result. */ + public record HistoricalStoredBareLoginCorrelationEvidence( + HistoricalStoredBareLoginEvidence originalExchange, + ConnectSourceIdentityEvidence originalConnectSource, + ConnectSourceIdentityEvidence freshConnectSource, + SelectedTargetEvidence selectedTarget) { + public HistoricalStoredBareLoginCorrelationEvidence { + Objects.requireNonNull(originalExchange, "originalExchange"); + Objects.requireNonNull(originalConnectSource, "originalConnectSource"); + Objects.requireNonNull(freshConnectSource, "freshConnectSource"); + Objects.requireNonNull(selectedTarget, "selectedTarget"); + if (!originalExchange.sourceConnectOperationId().equals(originalConnectSource.operationId()) + || originalConnectSource.operationId().equals(freshConnectSource.operationId())) { + throw new IllegalArgumentException("Historical/fresh source identities are not distinct"); + } + } + + @Override + public String toString() { + return "HistoricalStoredBareLoginCorrelationEvidence[originalExchange=, " + + "originalConnectSource=, freshConnectSource=, " + + "selectedTarget=]"; + } + } + + /** Immutable source identity facts; connect scope is represented only by its digest. */ + public record ConnectSourceIdentityEvidence( + UUID operationId, + String requestId, + String connectScopeHash, + String tokenIdentity, + byte[] sourceTokenHash, + String responseEnvelopeKeyId, + String accountSourceKeyId, + String gatewayKeyId, + BigInteger sourceIssuedAt, + BigInteger sourceExpiresAt, + BigInteger gatewayVerifiedAt, + BigInteger gatewayExpiresAt) { + public ConnectSourceIdentityEvidence { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(connectScopeHash, "connectScopeHash"); + Objects.requireNonNull(tokenIdentity, "tokenIdentity"); + sourceTokenHash = requireDigest(sourceTokenHash, "source token hash"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + Objects.requireNonNull(sourceIssuedAt, "sourceIssuedAt"); + Objects.requireNonNull(sourceExpiresAt, "sourceExpiresAt"); + Objects.requireNonNull(gatewayVerifiedAt, "gatewayVerifiedAt"); + Objects.requireNonNull(gatewayExpiresAt, "gatewayExpiresAt"); + } + + @Override + public byte[] sourceTokenHash() { + return sourceTokenHash.clone(); + } + + @Override + public String toString() { + return "ConnectSourceIdentityEvidence[operationId=" + + operationId + + ", request=, scope=, tokenIdentity=, " + + "sourceToken=, gatewayContext=]"; + } + } + + /** The complete canonical selected-target projection, excluding per-issuance identity/time. */ + public record SelectedTargetEvidence( + String accountId, + String tenantId, + String realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + String gameInstanceId, + BigInteger catalogRevision, + BigInteger pointerVersion, + String playtestLifecycleId, + BigInteger playtestStateGeneration) { + public SelectedTargetEvidence { + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + Objects.requireNonNull(gameInstanceId, "gameInstanceId"); + Objects.requireNonNull(catalogRevision, "catalogRevision"); + Objects.requireNonNull(pointerVersion, "pointerVersion"); + if ((playtestLifecycleId == null) != (playtestStateGeneration == null)) { + throw new IllegalArgumentException("Playtest target lifecycle and generation differ"); + } + } + + @Override + public String toString() { + return "SelectedTargetEvidence[account=, tenant=, realm=, " + + "world=, runtime=, revision=]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java new file mode 100644 index 0000000000..e904116f9d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.GameDesignFreshTenantIdentityClient; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired internal Account composition for fresh Game Design tenant identity enrollment. It + * persists and reads back Account identity before initializing the tenant generation only; it does + * not create membership, credentials, admission, or runtime authority. + */ +public final class FreshTenantIdentityEnrollmentService { + private final GameDesignFreshTenantIdentityClient gameDesignClient; + private final FreshTenantIdentityAssociationRepository associationRepository; + private final AccountAuthorityGenerationRepository generationRepository; + private final TransactionTemplate transactionTemplate; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Trusted internal client, repository, generation, and transaction collaborators are " + + "retained privately and never exposed by this unwired service.") + public FreshTenantIdentityEnrollmentService( + GameDesignFreshTenantIdentityClient gameDesignClient, + FreshTenantIdentityAssociationRepository associationRepository, + AccountAuthorityGenerationRepository generationRepository, + TransactionTemplate transactionTemplate) { + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + this.associationRepository = Objects.requireNonNull(associationRepository); + this.generationRepository = Objects.requireNonNull(generationRepository); + this.transactionTemplate = Objects.requireNonNull(transactionTemplate); + } + + /** + * Resolves authenticated owner evidence before opening the single Account write transaction, then + * imports, reads back, and initializes the UUID tenant generation without resetting it. + */ + public FreshTenantCreationEvidence enroll(UUID creationRequestId, String expectedDigest) { + if (creationRequestId == null + || creationRequestId.equals(new UUID(0L, 0L)) + || !GameTenantCreationDigest.isDigest(expectedDigest)) { + throw new IllegalArgumentException("Fresh tenant request identity or digest is invalid"); + } + + FreshTenantCreationEvidence ownerEvidence = + Objects.requireNonNull( + gameDesignClient.resolveCreation(creationRequestId, expectedDigest), + "Game Design creation evidence is required"); + if (!creationRequestId.equals(ownerEvidence.creationRequestId()) + || !expectedDigest.equals(ownerEvidence.requestDigest())) { + throw new IllegalStateException( + "Game Design creation evidence differs from the requested operation"); + } + + FreshTenantCreationEvidence committed = + transactionTemplate.execute( + status -> { + FreshTenantCreationEvidence imported = + associationRepository.importVerified(ownerEvidence); + FreshTenantCreationEvidence readback = + associationRepository + .read(ownerEvidence.canonicalTenantId()) + .orElseThrow( + () -> + new IllegalStateException( + "Fresh Account tenant association readback is absent")); + if (!ownerEvidence.equals(imported) || !ownerEvidence.equals(readback)) { + throw new IllegalStateException( + "Fresh Account tenant association readback differs from owner evidence"); + } + generationRepository.initializeTenantIfAbsent(readback.canonicalTenantId()); + return readback; + }); + return Objects.requireNonNull( + committed, "Fresh tenant enrollment transaction returned no result"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 49ef1c028c..3b60f34206 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -486,10 +486,8 @@ static GetTenantMembershipForRuntimeResponse encodeRuntimeMembershipCandidate( net.firedevops.firemud.shared.v1.PlayerExecutionContext playerContext, RuntimeMembershipSnapshotDto snapshot) { requireCompleteRuntimePlayerContext(playerContext); - long requestAccountId = parseCanonicalPositiveId(playerContext.getAccountId(), "account ID"); - long requestTenantId = parseCanonicalPositiveId(playerContext.getTenantId(), "tenant ID"); - if (requestAccountId != snapshot.requestAccountId() - || requestTenantId != snapshot.requestTenantId()) { + if (!playerContext.getAccountId().equals(snapshot.requestAccountUuid()) + || !playerContext.getTenantId().equals(snapshot.requestTenantUuid())) { throw new IllegalArgumentException( "Runtime membership producer result differs from its caller target"); } @@ -554,9 +552,11 @@ private static void requireCompleteRuntimePlayerContext( && !"ISOLATED".equals(playerContext.getPlayableStateScope())) { throw new IllegalArgumentException("Runtime membership target scope is invalid"); } - parseCanonicalPositiveId(playerContext.getAccountId(), "account ID"); - parseCanonicalPositiveId(playerContext.getTenantId(), "tenant ID"); - parseCanonicalPositiveId(playerContext.getGameInstanceId(), "game instance ID"); + requireCanonicalUuid(playerContext.getAccountId(), "account UUID"); + requireCanonicalUuid(playerContext.getTenantId(), "tenant UUID"); + requireCanonicalUuid( + playerContext.getPlayableStateNamespaceId(), "playable-state namespace UUID"); + requireCanonicalUuid(playerContext.getGameInstanceId(), "game instance UUID"); parseCanonicalPositiveId(playerContext.getSessionId(), "session ID"); } @@ -737,9 +737,17 @@ private static long parseCanonicalPositiveId(String value, String field) { } private static void requireCanonicalUuid(String value, String field) { - if (!hasText(value) || !UUID.fromString(value).toString().equals(value)) { + if (!hasText(value)) { throw new IllegalArgumentException("Runtime membership " + field + " is invalid"); } + try { + UUID uuid = UUID.fromString(value); + if (uuid.equals(new UUID(0L, 0L)) || !uuid.toString().equals(value)) { + throw new IllegalArgumentException("Runtime membership " + field + " is invalid"); + } + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Runtime membership " + field + " is invalid", exception); + } } private static boolean hasText(String value) { diff --git a/services/account-service/src/main/resources/db/migration/V38.1__fresh_tenant_identity_associations.sql b/services/account-service/src/main/resources/db/migration/V38.1__fresh_tenant_identity_associations.sql new file mode 100644 index 0000000000..8d1e0cca55 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V38.1__fresh_tenant_identity_associations.sql @@ -0,0 +1,234 @@ +-- Account stores this distinct Game Design-issued fresh identity only after +-- authenticated creation-operation evidence has been resolved and verified. +CREATE TABLE account_fresh_tenant_identity_associations ( + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + target_namespace VARCHAR(128) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + creation_request_id UUID NOT NULL + CHECK (creation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + operation_id UUID NOT NULL UNIQUE + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL UNIQUE + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + source_game_row_id BIGINT NOT NULL CHECK (source_game_row_id > 0), + source_game_tenant_key VARCHAR(36) NOT NULL + CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + provenance_kind VARCHAR(32) NOT NULL CHECK (provenance_kind = 'NEW_GAME_ROW'), + evidence_digest VARCHAR(71) NOT NULL, + identity_kind VARCHAR(32) NOT NULL DEFAULT 'FRESH_GAME_DESIGN' + CHECK (identity_kind = 'FRESH_GAME_DESIGN'), + associated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_fresh_tenant_request_digest_shape + CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT account_fresh_tenant_evidence_digest_shape + CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT account_fresh_tenant_request_unique + UNIQUE (target_namespace, creation_request_id), + CONSTRAINT account_fresh_tenant_source_unique + UNIQUE (source_game_row_id, source_game_tenant_key, provenance_kind), + CONSTRAINT account_fresh_tenant_identity_kind_unique + UNIQUE (canonical_tenant_id, identity_kind) +); + +-- A single canonical UUID claim serializes retained and fresh owner identities. +-- The source tuple is retained here so insertion can be checked against the exact +-- immutable owner association before the deferred source-to-claim FKs are checked. +ALTER TABLE account_approved_legacy_tenant_associations + ADD COLUMN identity_kind VARCHAR(32) NOT NULL DEFAULT 'APPROVED_RETAINED' + CHECK (identity_kind = 'APPROVED_RETAINED'), + ADD CONSTRAINT account_approved_tenant_identity_kind_unique + UNIQUE (canonical_tenant_id, identity_kind); + +CREATE TABLE account_canonical_tenant_identity_claims ( + canonical_tenant_id UUID PRIMARY KEY + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + identity_kind VARCHAR(32) NOT NULL + CHECK (identity_kind IN ('APPROVED_RETAINED', 'FRESH_GAME_DESIGN')), + source_operation_id UUID NOT NULL, + source_account_legacy_tenant_id BIGINT, + source_target_namespace VARCHAR(128) NOT NULL, + source_creation_request_id UUID, + source_request_digest VARCHAR(71), + source_game_row_id BIGINT NOT NULL CHECK (source_game_row_id > 0), + source_game_tenant_key VARCHAR(36) NOT NULL + CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + source_provenance_kind VARCHAR(32), + source_evidence_digest VARCHAR(71) NOT NULL, + source_manifest_digest VARCHAR(71), + claimed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_canonical_identity_claim_pair_unique + UNIQUE (canonical_tenant_id, identity_kind), + CONSTRAINT account_canonical_identity_claim_source_shape + CHECK ( + (identity_kind = 'APPROVED_RETAINED' + AND source_account_legacy_tenant_id > 0 + AND source_creation_request_id IS NULL + AND source_request_digest IS NULL + AND source_provenance_kind IS NULL + AND source_manifest_digest IS NOT NULL + AND source_manifest_digest ~ '^sha256:[0-9a-f]{64}$') + OR + (identity_kind = 'FRESH_GAME_DESIGN' + AND source_account_legacy_tenant_id IS NULL + AND source_creation_request_id IS NOT NULL + AND source_request_digest IS NOT NULL + AND source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_provenance_kind = 'NEW_GAME_ROW' + AND source_manifest_digest IS NULL) + ), + CONSTRAINT account_canonical_identity_claim_request_digest_shape + CHECK (source_request_digest IS NULL + OR source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT account_canonical_identity_claim_evidence_digest_shape + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION validate_account_canonical_tenant_identity_claim() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Account canonical tenant identity claims are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.identity_kind = 'APPROVED_RETAINED' THEN + SELECT EXISTS ( + SELECT 1 + FROM account_approved_legacy_tenant_associations retained + WHERE retained.canonical_tenant_id = NEW.canonical_tenant_id + AND retained.identity_kind = NEW.identity_kind + AND retained.operation_id = NEW.source_operation_id + AND retained.legacy_tenant_id = NEW.source_account_legacy_tenant_id + AND retained.target_namespace = NEW.source_target_namespace + AND retained.source_game_row_id = NEW.source_game_row_id + AND retained.source_legacy_game_tenant_id = NEW.source_game_tenant_key + AND retained.account_evidence_digest = NEW.source_evidence_digest + AND retained.manifest_digest = NEW.source_manifest_digest + ) INTO source_matches; + ELSIF NEW.identity_kind = 'FRESH_GAME_DESIGN' THEN + SELECT EXISTS ( + SELECT 1 + FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = NEW.canonical_tenant_id + AND fresh.identity_kind = NEW.identity_kind + AND fresh.target_namespace = NEW.source_target_namespace + AND fresh.creation_request_id = NEW.source_creation_request_id + AND fresh.operation_id = NEW.source_operation_id + AND fresh.request_digest = NEW.source_request_digest + AND fresh.source_game_row_id = NEW.source_game_row_id + AND fresh.source_game_tenant_key = NEW.source_game_tenant_key + AND fresh.provenance_kind = NEW.source_provenance_kind + AND fresh.evidence_digest = NEW.source_evidence_digest + ) INTO source_matches; + END IF; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Account canonical tenant identity claim has no exact source association' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION reject_account_canonical_tenant_identity_mutation() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Account canonical tenant identity evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION claim_approved_retained_canonical_tenant_identity() RETURNS trigger AS $$ +BEGIN + INSERT INTO account_canonical_tenant_identity_claims ( + canonical_tenant_id, identity_kind, source_operation_id, + source_account_legacy_tenant_id, source_target_namespace, + source_creation_request_id, source_request_digest, source_game_row_id, + source_game_tenant_key, source_provenance_kind, source_evidence_digest, + source_manifest_digest + ) VALUES ( + NEW.canonical_tenant_id, NEW.identity_kind, NEW.operation_id, + NEW.legacy_tenant_id, NEW.target_namespace, NULL, NULL, + NEW.source_game_row_id, NEW.source_legacy_game_tenant_id, NULL, + NEW.account_evidence_digest, NEW.manifest_digest + ); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION claim_fresh_canonical_tenant_identity() RETURNS trigger AS $$ +BEGIN + INSERT INTO account_canonical_tenant_identity_claims ( + canonical_tenant_id, identity_kind, source_operation_id, + source_account_legacy_tenant_id, source_target_namespace, + source_creation_request_id, source_request_digest, source_game_row_id, + source_game_tenant_key, source_provenance_kind, source_evidence_digest, + source_manifest_digest + ) VALUES ( + NEW.canonical_tenant_id, NEW.identity_kind, NEW.operation_id, + NULL, NEW.target_namespace, NEW.creation_request_id, NEW.request_digest, + NEW.source_game_row_id, NEW.source_game_tenant_key, NEW.provenance_kind, + NEW.evidence_digest, NULL + ); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_canonical_tenant_identity_claim_immutable + BEFORE INSERT OR UPDATE OR DELETE ON account_canonical_tenant_identity_claims + FOR EACH ROW EXECUTE FUNCTION validate_account_canonical_tenant_identity_claim(); + +CREATE TRIGGER account_canonical_tenant_identity_claim_no_truncate + BEFORE TRUNCATE ON account_canonical_tenant_identity_claims + FOR EACH STATEMENT EXECUTE FUNCTION reject_account_canonical_tenant_identity_mutation(); + +-- Backfill only the exact Account-owned approved retained associations already +-- present in V30. No Game Design source row is inferred or rewritten here. +INSERT INTO account_canonical_tenant_identity_claims ( + canonical_tenant_id, identity_kind, source_operation_id, + source_account_legacy_tenant_id, source_target_namespace, + source_creation_request_id, source_request_digest, source_game_row_id, + source_game_tenant_key, source_provenance_kind, source_evidence_digest, + source_manifest_digest +) +SELECT canonical_tenant_id, identity_kind, operation_id, legacy_tenant_id, + target_namespace, NULL, NULL, source_game_row_id, + source_legacy_game_tenant_id, NULL, account_evidence_digest, manifest_digest +FROM account_approved_legacy_tenant_associations; + +CREATE TRIGGER account_approved_tenant_identity_claim_after_insert + AFTER INSERT ON account_approved_legacy_tenant_associations + FOR EACH ROW EXECUTE FUNCTION claim_approved_retained_canonical_tenant_identity(); + +CREATE TRIGGER account_fresh_tenant_identity_claim_after_insert + AFTER INSERT ON account_fresh_tenant_identity_associations + FOR EACH ROW EXECUTE FUNCTION claim_fresh_canonical_tenant_identity(); + +CREATE TRIGGER account_fresh_tenant_identity_immutable + BEFORE UPDATE OR DELETE ON account_fresh_tenant_identity_associations + FOR EACH ROW EXECUTE FUNCTION reject_account_canonical_tenant_identity_mutation(); + +CREATE TRIGGER account_fresh_tenant_identity_no_truncate + BEFORE TRUNCATE ON account_fresh_tenant_identity_associations + FOR EACH STATEMENT EXECUTE FUNCTION reject_account_canonical_tenant_identity_mutation(); + +-- V30's existing update/delete guard remains unchanged; truncation must also be +-- denied so its paired canonical UUID claim can never outlive its source row. +CREATE TRIGGER account_approved_tenant_identity_no_truncate + BEFORE TRUNCATE ON account_approved_legacy_tenant_associations + FOR EACH STATEMENT EXECUTE FUNCTION reject_account_canonical_tenant_identity_mutation(); +-- [jooq ignore stop] + +ALTER TABLE account_approved_legacy_tenant_associations + ADD CONSTRAINT account_approved_tenant_claim_fk + FOREIGN KEY (canonical_tenant_id, identity_kind) + REFERENCES account_canonical_tenant_identity_claims (canonical_tenant_id, identity_kind) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE account_fresh_tenant_identity_associations + ADD CONSTRAINT account_fresh_tenant_claim_fk + FOREIGN KEY (canonical_tenant_id, identity_kind) + REFERENCES account_canonical_tenant_identity_claims (canonical_tenant_id, identity_kind) + DEFERRABLE INITIALLY DEFERRED; diff --git a/services/account-service/src/main/resources/db/migration/V39.1__migrate_empty_account_connect_storage_to_uuid.sql b/services/account-service/src/main/resources/db/migration/V39.1__migrate_empty_account_connect_storage_to_uuid.sql new file mode 100644 index 0000000000..5c67c6d940 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V39.1__migrate_empty_account_connect_storage_to_uuid.sql @@ -0,0 +1,101 @@ +-- V35 and V37 are already published with numeric tenant IDs. Preserve those +-- migration definitions and move only the provably empty storage shape forward. +-- No retained operation or encrypted response envelope may be reinterpreted. +-- [jooq ignore start] +LOCK TABLE account_connect_token_issuance_operations, + account_connect_token_response_envelopes, + account_bare_login_exchange_operations, + account_bare_login_response_envelopes + IN ACCESS EXCLUSIVE MODE; +-- [jooq ignore stop] + +-- [jooq ignore start] +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_connect_token_issuance_operations) + OR EXISTS (SELECT 1 FROM account_connect_token_response_envelopes) + OR EXISTS (SELECT 1 FROM account_bare_login_exchange_operations) + OR EXISTS (SELECT 1 FROM account_bare_login_response_envelopes) THEN + RAISE EXCEPTION 'Account connect storage UUID migration requires all four operation and envelope tables to be empty' + USING ERRCODE = '23514', + CONSTRAINT = 'account_connect_storage_uuid_requires_empty_tables'; + END IF; +END; +$$; +-- [jooq ignore stop] + +ALTER TABLE account_connect_token_issuance_operations + DROP CONSTRAINT account_connect_token_issuance_identity_check; +ALTER TABLE account_connect_token_response_envelopes + DROP CONSTRAINT account_connect_token_response_envelope_identity_check; +ALTER TABLE account_bare_login_exchange_operations + DROP CONSTRAINT account_bare_login_exchange_identity_check; +ALTER TABLE account_bare_login_response_envelopes + DROP CONSTRAINT account_bare_login_response_envelope_identity_check; + +-- The locked empty-table precondition makes NULL a non-persisted cast expression; +-- no tenant identity, provenance, ciphertext, or replay evidence is synthesized. +-- jOOQ's DDL parser does not support PostgreSQL's USING clause. Keep the real +-- conversion below and mirror its resulting type with simple no-op declarations. +-- [jooq ignore start] +ALTER TABLE account_connect_token_issuance_operations + ALTER COLUMN tenant_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE account_connect_token_response_envelopes + ALTER COLUMN tenant_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE account_bare_login_exchange_operations + ALTER COLUMN tenant_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE account_bare_login_response_envelopes + ALTER COLUMN tenant_id TYPE UUID USING CAST(NULL AS UUID); +-- [jooq ignore stop] + +ALTER TABLE account_connect_token_issuance_operations + ALTER COLUMN tenant_id TYPE UUID; +ALTER TABLE account_connect_token_response_envelopes + ALTER COLUMN tenant_id TYPE UUID; +ALTER TABLE account_bare_login_exchange_operations + ALTER COLUMN tenant_id TYPE UUID; +ALTER TABLE account_bare_login_response_envelopes + ALTER COLUMN tenant_id TYPE UUID; + +ALTER TABLE account_connect_token_issuance_operations + ADD CONSTRAINT account_connect_token_issuance_identity_check + CHECK (account_id > 0 + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND request_digest_version = 1 + AND octet_length(request_digest) = 32); + +ALTER TABLE account_connect_token_response_envelopes + ADD CONSTRAINT account_connect_token_response_envelope_identity_check + CHECK (operation_kind = 'CONNECT_TOKEN_ISSUANCE' + AND account_id > 0 + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND request_digest_version = 1 + AND octet_length(request_digest) = 32); + +ALTER TABLE account_bare_login_exchange_operations + ADD CONSTRAINT account_bare_login_exchange_identity_check + CHECK (account_id > 0 + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND request_digest_version = 1 + AND octet_length(request_digest) = 32); + +ALTER TABLE account_bare_login_response_envelopes + ADD CONSTRAINT account_bare_login_response_envelope_identity_check + CHECK (operation_kind = 'BARE_LOGIN_EXCHANGE' + AND source_connect_operation_id IS NOT NULL + AND account_id > 0 + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND request_digest_version = 1 + AND octet_length(request_digest) = 32); diff --git a/services/account-service/src/main/resources/db/migration/V39__fresh_uuid_membership_pair_authority.sql b/services/account-service/src/main/resources/db/migration/V39__fresh_uuid_membership_pair_authority.sql new file mode 100644 index 0000000000..e252171d01 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V39__fresh_uuid_membership_pair_authority.sql @@ -0,0 +1,45 @@ +-- The canonical tenant UUID is sufficient identity for fresh Game Design tenants. +-- Only retained associations have a private legacy numeric bridge; never invent one for fresh rows. +-- Fail before changing the table if an earlier candidate write fabricated a fresh numeric key. +-- [jooq ignore start] +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM account_membership_pair_authority + WHERE tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND legacy_tenant_id IS NOT NULL + ) THEN + RAISE EXCEPTION 'Fresh Account membership pair must not carry a legacy tenant ID' + USING ERRCODE = '23514', + CONSTRAINT = 'account_membership_pair_authority_fresh_legacy_id_migration'; + END IF; +END; +$$; +-- [jooq ignore stop] + +ALTER TABLE account_membership_pair_authority + ALTER COLUMN legacy_tenant_id DROP NOT NULL; + +-- jOOQ's H2 simulator assigns a different generated name to the V36 inline CHECK. +-- Keep the PostgreSQL drop active; skip only this name-specific operation in simulation. +-- [jooq ignore start] +ALTER TABLE account_membership_pair_authority + DROP CONSTRAINT account_membership_pair_authority_legacy_tenant_id_check; +-- [jooq ignore stop] + +ALTER TABLE account_membership_pair_authority + ADD CONSTRAINT account_membership_pair_authority_provenance_legacy_id_check CHECK ( + (tenant_provenance_kind = 'APPROVED_RETAINED' + AND legacy_tenant_id IS NOT NULL + AND legacy_tenant_id > 0) + OR (tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND legacy_tenant_id IS NULL) + ); + +DROP INDEX account_membership_pair_authority_legacy_scope_uq; + +-- Preserve one-to-one legacy association checks only for retained pairs. +CREATE UNIQUE INDEX account_membership_pair_authority_legacy_scope_uq + ON account_membership_pair_authority (account_uuid, legacy_tenant_id) + WHERE tenant_provenance_kind = 'APPROVED_RETAINED'; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java index 51241ec70f..8623e750a5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java @@ -585,7 +585,7 @@ void directSqlExchangeInsertRequiresCommittedMatchingSourceIdentity() { UUID.randomUUID(), committedIdentity.sourceConnectOperationId(), committedIdentity.accountId(), - committedIdentity.tenantId() + 1, + UUID.randomUUID(), committedIdentity.connectScopeId(), "wrong-tenant-" + UUID.randomUUID(), digest(71)))) @@ -758,7 +758,7 @@ private Source createSource( TestContext context, long accountId, String connectScopeId, boolean commitSource) { AccountConnectTokenIssuanceIdentity sourceIdentity = new AccountConnectTokenIssuanceIdentity( - accountId, 77L, connectScopeId, "connect-request-" + UUID.randomUUID()); + accountId, UUID.randomUUID(), connectScopeId, "connect-request-" + UUID.randomUUID()); byte[] sourceDigest = digest(commitSource ? 60 : 61); var sourceClaim = inTransaction( @@ -771,7 +771,7 @@ private Source createSource( sourceClaim.operation().operationId().toString(), sourceIdentity.requestId(), Long.toString(sourceIdentity.accountId()), - Long.toString(sourceIdentity.tenantId()), + sourceIdentity.tenantId().toString(), sourceIdentity.connectScopeId(), null, sourceDigest, @@ -841,7 +841,7 @@ private int insertBareOperationDirect( UUID operationId, UUID sourceOperationId, long accountId, - long tenantId, + UUID tenantId, String connectScopeId, String requestId, byte[] requestDigest) { @@ -881,7 +881,7 @@ private AccountEnvelopeBinding binding( operationId.toString(), identity.requestId(), Long.toString(identity.accountId()), - Long.toString(identity.tenantId()), + identity.tenantId().toString(), identity.connectScopeId(), identity.sourceConnectOperationId().toString(), requestDigest, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java index 97f37affea..1bfe40f8f3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java @@ -33,6 +33,10 @@ import java.util.function.Supplier; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeOperation; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginResponseEnvelope; import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; @@ -41,6 +45,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; 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.security.AccountEncryptedEnvelope; import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; @@ -49,12 +54,20 @@ import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.security.BareLoginRecoveryPayload; import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.HistoricalCommittedSourceEvidence; import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.OriginalSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader.HistoricalStoredBareLoginCorrelationEvidence; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader.HistoricalStoredBareLoginEvidence; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader.SelectedTargetEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.GatewayConnectContextCodec; import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -130,6 +143,653 @@ void readsExactCommittedOriginalSourceAndLostResultWithoutMutation() throws Exce assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); } + @Test + void readsFreshUuidCommittedSourceAndStoredHistoricalFrameWithoutMutation() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newFreshSource(prepared, SourceTarget.NORMAL); + assertThat(source.identity().tenantId()).isEqualTo(prepared.freshTenantUuid()); + FreshTenantCreationEvidence imported = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .freshTenantIdentityRepository() + .read(prepared.freshTenantUuid()) + .orElseThrow()); + assertThat(imported.canonicalTenantId()).isEqualTo(source.identity().tenantId()); + assertThat(imported.targetNamespace()).isEqualTo(WORKLOAD_NAMESPACE); + assertThat( + prepared + .db() + .dsl() + .resultQuery( + "SELECT source_account_legacy_tenant_id " + + "FROM account_canonical_tenant_identity_claims " + + "WHERE canonical_tenant_id = ? AND identity_kind = 'FRESH_GAME_DESIGN'", + imported.canonicalTenantId()) + .fetchOne(0, Long.class)) + .isNull(); + + Snapshot sourceBefore = sourceSnapshot(prepared, source.identity()); + OriginalSourceEvidence current = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> prepared.reader().read(source.identity(), source.gatewayEnvelope()))); + assertThat(current.originalSourceClaims().get("tenantId")) + .isEqualTo(prepared.freshTenantUuid().toString()); + + byte[] originalResult = "fresh-tenant-opaque-result".getBytes(StandardCharsets.UTF_8); + StoredBareLoginFixture stored = + storeBareLoginFrame(prepared, source, source.gatewayEnvelope(), originalResult, null); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + prepared.clock().advance(Duration.ofSeconds(21)); + HistoricalStoredBareLoginEvidence historical = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + storedReader(prepared) + .readHistorical(stored.identity(), stored.requestDigest()))); + + assertThat(historical.tenantId()).isEqualTo(prepared.freshTenantUuid()); + assertThat(historical.sourceConnectOperationId()) + .isEqualTo(stored.identity().sourceConnectOperationId()); + assertThat(historical.originalResultHash()).containsExactly(sha256(originalResult)); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(sourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + @Test + void readsExpiredCommittedSourceOnlyThroughHistoricalEvidenceWithoutMutation() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + AccountCommittedConnectSource committed = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .issuanceRepository() + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow()); + Snapshot before = sourceSnapshot(prepared, source.identity()); + + // Both the Account token and its projected Gateway context expire after twenty seconds. + prepared.clock().advance(Duration.ofSeconds(21)); + HistoricalCommittedSourceEvidence historical = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .readHistorical(source.identity(), source.gatewayEnvelope()))); + + assertThat(historical.operationId()).isEqualTo(committed.operation().operationId()); + assertThat(historical.responseEnvelopeKeyId()) + .isEqualTo(committed.responseEnvelope().envelope().keyId()); + assertThat(historical.sourceTokenHash()).containsExactly(committed.operation().tokenHash()); + assertThat(historical.accountSourceKeyId()).isEqualTo(ACCOUNT_KEY_ID); + assertThat(historical.gatewayKeyId()).isEqualTo(GATEWAY_KEY_ID); + assertThat(historical.originalSourceClaims()).isEqualTo(source.sourceClaims()); + assertThat(historical.historicalGatewayClaims()).isEqualTo(source.gatewayClaims()); + assertThat(historical.originalSourceClaims().get("jti")).isEqualTo(source.tokenIdentity()); + assertThat(historical.toString()) + .doesNotContain(source.identity().connectScopeId()) + .doesNotContain(source.tokenIdentity()) + .doesNotContain(source.gatewayEnvelope()); + byte[] modifiedHash = historical.sourceTokenHash(); + modifiedHash[0] ^= 0x01; + assertThat(historical.sourceTokenHash()).containsExactly(committed.operation().tokenHash()); + assertThatThrownBy(() -> historical.originalSourceClaims().put("extra", "value")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + ((Map) historical.originalSourceClaims().get("authorityTuple")) + .put("extra", BigInteger.ONE)) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gateway context is expired"); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + } + + @Test + void readsCommittedStoredFrameAndOriginalSourceAfterGatewayContextExpiryWithoutMutation() + throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + byte[] originalResult = "opaque-original-bare-login-result".getBytes(StandardCharsets.UTF_8); + StoredBareLoginFixture stored = + storeBareLoginFrame(prepared, source, source.gatewayEnvelope(), originalResult, null); + AccountCommittedConnectSource committedSource = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .issuanceRepository() + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow()); + Snapshot sourceBefore = sourceSnapshot(prepared, source.identity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + AccountStoredBareLoginRecoveryReader reader = storedReader(prepared); + + prepared.clock().advance(Duration.ofSeconds(21)); + HistoricalStoredBareLoginEvidence first = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> reader.readHistorical(stored.identity(), stored.requestDigest()))); + HistoricalStoredBareLoginEvidence reread = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> reader.readHistorical(stored.identity(), stored.requestDigest()))); + + assertThat(first.exchangeOperationId()).isEqualTo(stored.operationId()); + assertThat(first.sourceConnectOperationId()) + .isEqualTo(stored.identity().sourceConnectOperationId()); + assertThat(first.accountId()).isEqualTo(source.identity().accountId()); + assertThat(first.tenantId()).isEqualTo(source.identity().tenantId()); + assertThat(first.requestId()).isEqualTo(stored.identity().requestId()); + assertThat(first.requestDigestVersion()).isEqualTo(1); + assertThat(first.connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(source.identity().connectScopeId())); + assertThat(first.requestDigest()).containsExactly(stored.requestDigest()); + assertThat(first.originalResultHash()).containsExactly(sha256(originalResult)); + assertThat(first.sourceConnectTokenHash()) + .containsExactly(committedSource.operation().tokenHash()); + assertThat(first.responseEnvelopeKeyId()).isEqualTo("test-key"); + assertThat(first.sourceResponseEnvelopeKeyId()).isEqualTo("test-key"); + assertThat(first.accountSourceKeyId()).isEqualTo(ACCOUNT_KEY_ID); + assertThat(first.gatewayKeyId()).isEqualTo(GATEWAY_KEY_ID); + assertThat(first.signedGatewayVerifiedAt()).isEqualTo(source.gatewayClaims().get("verifiedAt")); + assertThat(first.signedGatewayExpiresAt()).isEqualTo(source.gatewayClaims().get("expiresAt")); + assertThat(first.exchangeOperationId()).isEqualTo(reread.exchangeOperationId()); + assertThat(first.sourceConnectOperationId()).isEqualTo(reread.sourceConnectOperationId()); + assertThat(first.originalResultHash()).containsExactly(reread.originalResultHash()); + byte[] changedRequestDigest = first.requestDigest(); + changedRequestDigest[0] ^= 0x01; + assertThat(first.requestDigest()).containsExactly(stored.requestDigest()); + byte[] changedSourceHash = first.sourceConnectTokenHash(); + changedSourceHash[0] ^= 0x01; + assertThat(first.sourceConnectTokenHash()) + .containsExactly(committedSource.operation().tokenHash()); + assertThat(first.toString()) + .doesNotContain(new String(originalResult, StandardCharsets.UTF_8)) + .doesNotContain(source.gatewayEnvelope()) + .doesNotContain(source.identity().connectScopeId()); + byte[] changedHash = first.originalResultHash(); + changedHash[0] ^= 0x01; + assertThat(first.originalResultHash()).containsExactly(sha256(originalResult)); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(sourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + @Test + void correlatesExpiredOriginalFrameWithSeparateFreshCommittedSourceWithoutMutation() + throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceTarget target = + new SourceTarget( + "world", + "realm", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + BigInteger.valueOf(3)); + SourceFixture original = newSourceWithTarget(prepared, target); + byte[] originalResult = "opaque-original-result".getBytes(StandardCharsets.UTF_8); + StoredBareLoginFixture stored = + storeBareLoginFrame(prepared, original, original.gatewayEnvelope(), originalResult, null); + Snapshot originalSourceBefore = sourceSnapshot(prepared, original.identity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + + prepared.clock().advance(Duration.ofSeconds(21)); + long now = prepared.clock().instant().getEpochSecond(); + assertThat(((BigInteger) original.gatewayClaims().get("expiresAt")).longValue()) + .isLessThan(now); + SourceFixture fresh = newSourceWithTarget(prepared, target); + Snapshot freshSourceBefore = sourceSnapshot(prepared, fresh.identity()); + + AccountStoredBareLoginRecoveryReader reader = storedReader(prepared); + HistoricalStoredBareLoginCorrelationEvidence first = + readCorrelation(reader, prepared, stored, fresh.identity(), fresh.gatewayEnvelope()); + HistoricalStoredBareLoginCorrelationEvidence reread = + readCorrelation(reader, prepared, stored, fresh.identity(), fresh.gatewayEnvelope()); + + assertThat(first.originalExchange().exchangeOperationId()).isEqualTo(stored.operationId()); + assertThat(first.originalExchange().requestId()).isEqualTo(stored.identity().requestId()); + assertThat(first.originalExchange().requestDigest()).containsExactly(stored.requestDigest()); + assertThat(first.originalExchange().connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(stored.identity().connectScopeId())); + assertThat(first.originalExchange().originalResultHash()) + .containsExactly(sha256(originalResult)); + assertThat(first.originalConnectSource().operationId()) + .isEqualTo(stored.identity().sourceConnectOperationId()); + assertThat(first.freshConnectSource().operationId()).isEqualTo(freshSourceBefore.operationId()); + assertThat(first.freshConnectSource().operationId()) + .isNotEqualTo(first.originalConnectSource().operationId()); + assertThat(first.originalConnectSource().requestId()) + .isEqualTo(original.identity().requestId()); + assertThat(first.freshConnectSource().requestId()).isEqualTo(fresh.identity().requestId()); + assertThat(first.originalConnectSource().requestId()) + .isNotEqualTo(first.freshConnectSource().requestId()); + assertThat(first.originalConnectSource().connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(original.identity().connectScopeId())); + assertThat(first.freshConnectSource().connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(fresh.identity().connectScopeId())); + assertThat(first.originalConnectSource().connectScopeHash()) + .isNotEqualTo(first.freshConnectSource().connectScopeHash()); + assertThat(first.originalConnectSource().tokenIdentity()).isEqualTo(original.tokenIdentity()); + assertThat(first.freshConnectSource().tokenIdentity()).isEqualTo(fresh.tokenIdentity()); + assertThat(first.originalConnectSource().sourceExpiresAt()).isLessThan(BigInteger.valueOf(now)); + assertThat(first.freshConnectSource().gatewayExpiresAt()) + .isGreaterThan(BigInteger.valueOf(now)); + assertThat(first.selectedTarget()) + .isEqualTo( + new SelectedTargetEvidence( + (String) original.sourceClaims().get("accountId"), + (String) original.sourceClaims().get("tenantId"), + (String) original.sourceClaims().get("realmId"), + (String) original.sourceClaims().get("worldSlug"), + (String) original.sourceClaims().get("realmSlug"), + (String) original.sourceClaims().get("playableStateNamespaceId"), + (String) original.sourceClaims().get("playableStateScope"), + (String) original.sourceClaims().get("gameInstanceId"), + (BigInteger) original.sourceClaims().get("catalogRevision"), + (BigInteger) original.sourceClaims().get("pointerVersion"), + (String) original.sourceClaims().get("playtestLifecycleId"), + (BigInteger) original.sourceClaims().get("playtestStateGeneration"))); + assertThat(first.selectedTarget()).isEqualTo(reread.selectedTarget()); + assertThat(first.originalConnectSource().sourceTokenHash()) + .containsExactly(reread.originalConnectSource().sourceTokenHash()); + byte[] mutatedHash = first.freshConnectSource().sourceTokenHash(); + mutatedHash[0] ^= 0x01; + assertThat(first.freshConnectSource().sourceTokenHash()) + .containsExactly(reread.freshConnectSource().sourceTokenHash()); + assertThat(first.toString()) + .doesNotContain(new String(originalResult, StandardCharsets.UTF_8)) + .doesNotContain(original.gatewayEnvelope()) + .doesNotContain(fresh.gatewayEnvelope()); + assertThat(sourceSnapshot(prepared, original.identity())).isEqualTo(originalSourceBefore); + assertThat(sourceSnapshot(prepared, fresh.identity())).isEqualTo(freshSourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + + assertReadRejected( + prepared.reader(), + prepared, + original, + IllegalArgumentException.class, + "Gateway context is expired"); + } + + @Test + void correlationRejectsExpiredFreshContextAndReissuedContextForOriginalSource() throws Exception { + PreparedAccount expiredPrepared = newPreparedAccount(); + SourceFixture expiredOriginal = newSource(expiredPrepared, SourceState.COMMITTED); + StoredBareLoginFixture expiredStored = + storeBareLoginFrame( + expiredPrepared, + expiredOriginal, + expiredOriginal.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + SourceFixture expiredFresh = newSource(expiredPrepared, SourceState.COMMITTED); + expiredPrepared.clock().advance(Duration.ofSeconds(21)); + assertCorrelationReadRejected( + expiredPrepared, + storedReader(expiredPrepared), + expiredStored, + expiredFresh.identity(), + expiredFresh.gatewayEnvelope(), + IllegalArgumentException.class, + "Gateway context is expired"); + + PreparedAccount samePrepared = newPreparedAccount(); + SourceFixture sameSource = + newSource( + samePrepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, false, true, false)); + StoredBareLoginFixture sameStored = + storeBareLoginFrame( + samePrepared, + sameSource, + sameSource.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + samePrepared.clock().advance(Duration.ofSeconds(3)); + String currentContextForSameSource = resignCurrentGatewayContext(samePrepared, sameSource); + assertCorrelationReadRejected( + samePrepared, + storedReader(samePrepared), + sameStored, + sameSource.identity(), + currentContextForSameSource, + IllegalStateException.class, + "separate committed Account source operation"); + } + + @Test + void correlationRequiresExactAccountTenantAndCompleteSelectedTarget() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceTarget originalTarget = + new SourceTarget( + "world", + "realm", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + BigInteger.valueOf(3)); + SourceFixture original = newSourceWithTarget(prepared, originalTarget); + StoredBareLoginFixture stored = + storeBareLoginFrame( + prepared, + original, + original.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + AccountStoredBareLoginRecoveryReader reader = storedReader(prepared); + + SourceFixture freshMatchingTarget = newSourceWithTarget(prepared, originalTarget); + byte[] changedDigest = stored.requestDigest(); + changedDigest[0] ^= 0x01; + assertCorrelationReadRejected( + prepared, + reader, + stored, + changedDigest, + freshMatchingTarget.identity(), + freshMatchingTarget.gatewayEnvelope(), + AccountBareLoginExchangeRepository.IdempotencyConflictException.class, + "different digest"); + + AccountBareLoginExchangeIdentity changedRequest = + new AccountBareLoginExchangeIdentity( + stored.identity().sourceConnectOperationId(), + stored.identity().accountId(), + stored.identity().tenantId(), + stored.identity().connectScopeId(), + stored.identity().requestId() + "-different"); + assertCorrelationReadRejected( + prepared, + reader, + stored, + changedRequest, + stored.requestDigest(), + freshMatchingTarget.identity(), + freshMatchingTarget.gatewayEnvelope(), + IllegalStateException.class, + "exchange identity was reused with different source or binding"); + + SourceFixture changedWorld = + newSourceWithTarget(prepared, new SourceTarget("other-world", "realm", null, null)); + assertCorrelationReadRejected( + prepared, + reader, + stored, + stored.requestDigest(), + changedWorld.identity(), + changedWorld.gatewayEnvelope(), + IllegalStateException.class, + "exact original Account target"); + + AccountConnectTokenIssuanceIdentity wrongPlayer = + new AccountConnectTokenIssuanceIdentity( + original.identity().accountId() + 1, + original.identity().tenantId(), + "fresh-scope-player", + "fresh-request-player"); + assertCorrelationIdentityRejected(prepared, reader, stored, wrongPlayer); + AccountConnectTokenIssuanceIdentity wrongTenant = + new AccountConnectTokenIssuanceIdentity( + original.identity().accountId(), + UUID.randomUUID(), + "fresh-scope-tenant", + "fresh-request-tenant"); + assertCorrelationIdentityRejected(prepared, reader, stored, wrongTenant); + + SourceFixture changedLifecycle = + newSourceWithTarget( + prepared, + new SourceTarget( + "world", + "realm", + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + BigInteger.valueOf(3))); + assertCorrelationReadRejected( + prepared, + reader, + stored, + changedLifecycle.identity(), + changedLifecycle.gatewayEnvelope(), + IllegalStateException.class, + "exact original Account target"); + + SourceFixture changedGeneration = + newSourceWithTarget( + prepared, + new SourceTarget( + "world", "realm", originalTarget.playtestLifecycleId(), BigInteger.valueOf(4))); + assertCorrelationReadRejected( + prepared, + reader, + stored, + changedGeneration.identity(), + changedGeneration.gatewayEnvelope(), + IllegalStateException.class, + "exact original Account target"); + } + + @Test + void storedHistoryRejectsChangedDigestSourceContextResultHashAndKey() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + byte[] result = "opaque-original-result".getBytes(StandardCharsets.UTF_8); + StoredBareLoginFixture stored = + storeBareLoginFrame(prepared, source, source.gatewayEnvelope(), result, null); + byte[] wrongRequestDigest = stored.requestDigest(); + wrongRequestDigest[0] ^= 0x01; + assertStoredReadRejected( + storedReader(prepared), + prepared, + stored, + wrongRequestDigest, + AccountBareLoginExchangeRepository.IdempotencyConflictException.class, + "different digest"); + + SourceFixture linkedSource = newSource(prepared, SourceState.COMMITTED); + SourceFixture sameScopeOtherSource = + newSource( + prepared, + SourceState.COMMITTED, + SourceOptions.NORMAL, + linkedSource.identity().connectScopeId()); + Snapshot contextSourceBefore = sourceSnapshot(prepared, sameScopeOtherSource.identity()); + StoredBareLoginFixture linkedToWrongSource = + storeBareLoginFrame( + prepared, linkedSource, sameScopeOtherSource.gatewayEnvelope(), result, null); + assertStoredReadRejected( + storedReader(prepared), + prepared, + linkedToWrongSource, + linkedToWrongSource.requestDigest(), + IllegalStateException.class, + "does not match its original Gateway context"); + assertThat(sourceSnapshot(prepared, sameScopeOtherSource.identity())) + .isEqualTo(contextSourceBefore); + + SourceFixture changedContextSource = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, true, false, false, false)); + StoredBareLoginFixture changedContext = + storeBareLoginFrame( + prepared, changedContextSource, changedContextSource.gatewayEnvelope(), result, null); + assertStoredReadRejected( + storedReader(prepared), + prepared, + changedContext, + changedContext.requestDigest(), + IllegalArgumentException.class, + "invalid Account gameplay-connect source JWT"); + + byte[] differentStoredHash = sha256("different-result".getBytes(StandardCharsets.UTF_8)); + SourceFixture resultHashSource = newSource(prepared, SourceState.COMMITTED); + StoredBareLoginFixture changedResultHash = + storeBareLoginFrame( + prepared, + resultHashSource, + resultHashSource.gatewayEnvelope(), + result, + differentStoredHash); + assertStoredReadRejected( + storedReader(prepared), + prepared, + changedResultHash, + changedResultHash.requestDigest(), + IllegalStateException.class, + "result hash does not match"); + + SourceFixture oldPayloadSource = newSource(prepared, SourceState.COMMITTED); + StoredBareLoginFixture oldOpaquePayload = + storeOpaqueBareLoginPayload( + prepared, + oldPayloadSource, + "legacy unframed response payload".getBytes(StandardCharsets.UTF_8)); + assertStoredReadRejected( + storedReader(prepared), + prepared, + oldOpaquePayload, + oldOpaquePayload.requestDigest(), + IllegalArgumentException.class, + "payload header is invalid"); + + assertStoredReadRejected( + storedReader(prepared, differentConnectPurposeKey()), + prepared, + stored, + stored.requestDigest(), + AccountEnvelopeCryptoException.class, + "AUTHENTICATION_FAILED"); + } + + @Test + void historicalReadRejectsRequestTargetHashAndTokenIdentityMismatches() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + SourceFixture wrongHash = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, true, false, false, false, false, false)); + SourceFixture wrongJti = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, true, false, false, false, false)); + SourceFixture wrongTarget = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, true, false, false, false)); + + assertHistoricalReadRejected(prepared, wrongHash, IllegalStateException.class, "token hash"); + assertHistoricalReadRejected(prepared, wrongJti, IllegalStateException.class, "token identity"); + // Source verification deliberately sanitizes signature/profile/projection failure details. + assertHistoricalReadRejected( + prepared, + wrongTarget, + IllegalArgumentException.class, + "invalid Account gameplay-connect source JWT"); + + Snapshot before = sourceSnapshot(prepared, source.identity()); + AccountConnectTokenIssuanceIdentity wrongRequestIdentity = + new AccountConnectTokenIssuanceIdentity( + source.identity().accountId(), + source.identity().tenantId(), + source.identity().connectScopeId() + "-different", + source.identity().requestId()); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .readHistorical( + wrongRequestIdentity, source.gatewayEnvelope())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request identity"); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + } + + @Test + void historicalReadRequiresCommittedSuccess() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture absent = newSource(prepared, SourceState.ABSENT); + SourceFixture pending = newSource(prepared, SourceState.PENDING); + SourceFixture failed = newSource(prepared, SourceState.FAILED); + + assertHistoricalReadRejected( + prepared, absent, IllegalStateException.class, "Committed Account source is absent"); + assertHistoricalReadRejected( + prepared, pending, IllegalStateException.class, "not a complete committed success"); + assertHistoricalReadRejected( + prepared, failed, IllegalStateException.class, "not a complete committed success"); + } + + @Test + void historicalReadRequiresRegisteredGatewayAndAccountSigningKeys() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture unknownGateway = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, true, false, false)); + SourceFixture unknownAccount = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(true, false, false, false, false, false, false)); + + assertHistoricalReadRejected( + prepared, + unknownGateway, + IllegalArgumentException.class, + "unknown Gateway verification key"); + assertHistoricalReadRejected( + prepared, + unknownAccount, + IllegalArgumentException.class, + "invalid Account gameplay-connect source JWT"); + } + @Test void requiresExactGameSessionCallerAndRegisteredGatewayAndAccountKeys() throws Exception { PreparedAccount prepared = newPreparedAccount(); @@ -278,6 +938,11 @@ void rejectsUnmappedAndChangedRetainedTenantEvidence() throws Exception { unmappedTenant, IllegalStateException.class, "approved Account tenant association is absent"); + assertHistoricalReadRejected( + prepared, + unmappedTenant, + IllegalStateException.class, + "approved Account tenant association is absent"); SourceFixture changedRetainedEvidence = newSource(prepared, SourceState.COMMITTED); inTransaction( @@ -296,6 +961,11 @@ void rejectsUnmappedAndChangedRetainedTenantEvidence() throws Exception { changedRetainedEvidence, IllegalStateException.class, "approved Account source evidence differs from retained rows"); + assertHistoricalReadRejected( + prepared, + changedRetainedEvidence, + IllegalStateException.class, + "approved Account source evidence differs from retained rows"); } @Test @@ -311,13 +981,73 @@ void rejectsWrongPurposeAndWrongPurposeKeyForStoredEnvelope() throws Exception { .issuanceRepository() .readCommittedResponseEnvelope(source.identity()) .orElseThrow()); + assertThat(stored.responseEnvelope().binding().tenantId()) + .isEqualTo(source.identity().tenantId().toString()); + AccountEnvelopeBinding wrongConnectTenantBinding = + withTenantId(stored.responseEnvelope().binding(), UUID.randomUUID().toString()); + assertThatThrownBy( + () -> + prepared + .db() + .envelopeCrypto() + .decrypt( + stored.responseEnvelope().envelope(), + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + wrongConnectTenantBinding)) + .isInstanceOf(AccountEnvelopeCryptoException.class) + .extracting(exception -> ((AccountEnvelopeCryptoException) exception).failure()) + .isEqualTo(Failure.AUTHENTICATION_FAILED); + + StoredBareLoginFixture storedBareLogin = + storeBareLoginFrame( + prepared, + source, + source.gatewayEnvelope(), + "uuid-bound-bare-login-frame".getBytes(StandardCharsets.UTF_8), + null); + AccountBareLoginResponseEnvelope bareEnvelope = + inTransaction( + prepared.db().transaction(), + () -> { + AccountBareLoginExchangeOperation operation = + prepared + .db() + .bareLoginExchangeRepository() + .find(storedBareLogin.identity(), storedBareLogin.requestDigest()) + .orElseThrow(); + AccountEnvelopeBinding binding = + bareLoginBinding(operation, storedBareLogin.identity()); + return prepared + .db() + .bareLoginExchangeRepository() + .readResponseEnvelope( + storedBareLogin.identity(), storedBareLogin.requestDigest(), binding) + .orElseThrow(); + }); + assertThat(bareEnvelope.binding().tenantId()) + .isEqualTo(source.identity().tenantId().toString()); + AccountEnvelopeBinding wrongBareLoginTenantBinding = + withTenantId(bareEnvelope.binding(), UUID.randomUUID().toString()); + assertThatThrownBy( + () -> + prepared + .db() + .envelopeCrypto() + .decrypt( + bareEnvelope.envelope(), + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + wrongBareLoginTenantBinding)) + .isInstanceOf(AccountEnvelopeCryptoException.class) + .extracting(exception -> ((AccountEnvelopeCryptoException) exception).failure()) + .isEqualTo(Failure.AUTHENTICATION_FAILED); + AccountEnvelopeBinding otherPurposeBinding = new AccountEnvelopeBinding( AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, UUID.randomUUID().toString(), "other-request", Long.toString(source.identity().accountId()), - Long.toString(source.identity().tenantId()), + source.identity().tenantId().toString(), source.identity().connectScopeId(), UUID.randomUUID().toString(), digest("other-request"), @@ -346,18 +1076,150 @@ void rejectsWrongPurposeAndWrongPurposeKeyForStoredEnvelope() throws Exception { source, AccountEnvelopeCryptoException.class, "AUTHENTICATION_FAILED"); + assertHistoricalReadRejected( + wrongKeyReader, + prepared, + source, + AccountEnvelopeCryptoException.class, + "AUTHENTICATION_FAILED"); + + AccountCommittedConnectSourceReader missingRingReader = + readerWithCrypto(prepared, missingKeyRingCrypto()); + assertHistoricalReadRejected( + missingRingReader, + prepared, + source, + AccountEnvelopeCryptoException.class, + "KEY_RING_UNAVAILABLE"); + } + + @Test + void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture original = newSource(prepared, SourceState.COMMITTED); + StoredBareLoginFixture stored = + storeBareLoginFrame( + prepared, + original, + original.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + SourceFixture source = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, false, true, false)); + CountDownLatch accountRowLocked = new CountDownLatch(1); + CountDownLatch releaseAccountRow = new CountDownLatch(1); + CountDownLatch readerBackendIdentified = new CountDownLatch(1); + AtomicInteger blockerBackendPid = new AtomicInteger(); + AtomicInteger readerBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blocker = + executor.submit( + () -> + inTransaction( + prepared.db().transaction(), + () -> { + blockerBackendPid.set(requirePositiveBackendPid(prepared.db().dsl())); + prepared + .db() + .dsl() + .resultQuery( + "SELECT id FROM accounts WHERE id = ? FOR UPDATE", + prepared.accountId()) + .fetchOne(); + accountRowLocked.countDown(); + if (!await(releaseAccountRow, 20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Account fence holder was not released"); + } + return null; + })); + try { + assertThat(accountRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future reader = + executor.submit( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> { + readerBackendPid.set( + requirePositiveBackendPid(prepared.db().dsl())); + readerBackendIdentified.countDown(); + return storedReader(prepared) + .readCorrelation( + stored.identity(), + stored.requestDigest(), + source.identity(), + source.gatewayEnvelope()); + }))); + if (!readerBackendIdentified.await(5, TimeUnit.SECONDS)) { + try { + reader.get(0, TimeUnit.MILLISECONDS); + } catch (java.util.concurrent.ExecutionException failure) { + throw new AssertionError( + "Reader failed before identifying its backend", failure.getCause()); + } catch (java.util.concurrent.TimeoutException stillRunning) { + // The bounded identity wait elapsed while the worker was still running. + } + throw new AssertionError( + "Reader backend PID was not identified before the bounded deadline"); + } + assertThat( + awaitAccountFenceBlock( + prepared.db().dsl(), + readerBackendPid.get(), + blockerBackendPid.get(), + Duration.ofSeconds(5))) + .as("the exact reader backend is blocked by the exact Account row fence backend") + .isTrue(); + + // The source token remains valid; only the Gateway's signed, shortened deadline expires. + prepared.clock().advance(Duration.ofSeconds(3)); + releaseAccountRow.countDown(); + assertThatThrownBy(() -> reader.get(10, TimeUnit.SECONDS)) + .satisfies( + thrown -> { + Throwable cause = thrown; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gateway context is expired"); + }); + } finally { + releaseAccountRow.countDown(); + blocker.get(10, TimeUnit.SECONDS); + executor.shutdownNow(); + } } @Test - void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() throws Exception { + void correlationRechecksFreshDeadlineAfterStoredFrameReadWait() throws Exception { PreparedAccount prepared = newPreparedAccount(); - SourceFixture source = + SourceFixture original = newSource(prepared, SourceState.COMMITTED); + StoredBareLoginFixture stored = + storeBareLoginFrame( + prepared, + original, + original.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + SourceFixture fresh = newSource( prepared, SourceState.COMMITTED, new SourceOptions(false, false, false, false, false, true, false)); - CountDownLatch accountRowLocked = new CountDownLatch(1); - CountDownLatch releaseAccountRow = new CountDownLatch(1); + Snapshot originalBefore = sourceSnapshot(prepared, original.identity()); + Snapshot freshBefore = sourceSnapshot(prepared, fresh.identity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + + CountDownLatch envelopeTableLocked = new CountDownLatch(1); + CountDownLatch releaseEnvelopeTable = new CountDownLatch(1); CountDownLatch readerBackendIdentified = new CountDownLatch(1); AtomicInteger blockerBackendPid = new AtomicInteger(); AtomicInteger readerBackendPid = new AtomicInteger(); @@ -372,19 +1234,19 @@ void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() thro prepared .db() .dsl() - .resultQuery( - "SELECT id FROM accounts WHERE id = ? FOR UPDATE", - prepared.accountId()) - .fetchOne(); - accountRowLocked.countDown(); - if (!await(releaseAccountRow, 20, TimeUnit.SECONDS)) { - throw new IllegalStateException("Account fence holder was not released"); + .execute( + "LOCK TABLE account_bare_login_response_envelopes " + + "IN ACCESS EXCLUSIVE MODE"); + envelopeTableLocked.countDown(); + if (!await(releaseEnvelopeTable, 20, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "V37 envelope-table blocker was not released"); } return null; })); try { - assertThat(accountRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); - Future reader = + assertThat(envelopeTableLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future reader = executor.submit( () -> withPeer( @@ -396,34 +1258,26 @@ void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() thro readerBackendPid.set( requirePositiveBackendPid(prepared.db().dsl())); readerBackendIdentified.countDown(); - return prepared - .reader() - .read(source.identity(), source.gatewayEnvelope()); + return storedReader(prepared) + .readCorrelation( + stored.identity(), + stored.requestDigest(), + fresh.identity(), + fresh.gatewayEnvelope()); }))); - if (!readerBackendIdentified.await(5, TimeUnit.SECONDS)) { - try { - reader.get(0, TimeUnit.MILLISECONDS); - } catch (java.util.concurrent.ExecutionException failure) { - throw new AssertionError( - "Reader failed before identifying its backend", failure.getCause()); - } catch (java.util.concurrent.TimeoutException stillRunning) { - // The bounded identity wait elapsed while the worker was still running. - } - throw new AssertionError( - "Reader backend PID was not identified before the bounded deadline"); - } + assertThat(readerBackendIdentified.await(5, TimeUnit.SECONDS)).isTrue(); assertThat( - awaitAccountFenceBlock( + awaitRelationLockBlock( prepared.db().dsl(), readerBackendPid.get(), blockerBackendPid.get(), Duration.ofSeconds(5))) - .as("the exact reader backend is blocked by the exact Account row fence backend") + .as( + "correlation passed its first strict source read and reached stored-envelope readback") .isTrue(); - // The source token remains valid; only the Gateway's signed, shortened deadline expires. prepared.clock().advance(Duration.ofSeconds(3)); - releaseAccountRow.countDown(); + releaseEnvelopeTable.countDown(); assertThatThrownBy(() -> reader.get(10, TimeUnit.SECONDS)) .satisfies( thrown -> { @@ -435,8 +1289,11 @@ void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() thro .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Gateway context is expired"); }); + assertThat(sourceSnapshot(prepared, original.identity())).isEqualTo(originalBefore); + assertThat(sourceSnapshot(prepared, fresh.identity())).isEqualTo(freshBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); } finally { - releaseAccountRow.countDown(); + releaseEnvelopeTable.countDown(); blocker.get(10, TimeUnit.SECONDS); executor.shutdownNow(); } @@ -493,6 +1350,12 @@ private PreparedAccount newPreparedAccount() throws Exception { () -> associations.importApproved( LEGACY_TENANT_ID, approvedAssociation(retainedEvidenceDigest, tenantUuid))); + UUID freshTenantUuid = UUID.randomUUID(); + FreshTenantIdentityAssociationRepository freshTenantIdentityRepository = + new FreshTenantIdentityAssociationRepository(dsl, WORKLOAD_NAMESPACE); + FreshTenantCreationEvidence freshTenantEvidence = freshTenantEvidence(freshTenantUuid); + inTransaction( + transaction, () -> freshTenantIdentityRepository.importVerified(freshTenantEvidence)); byte[] bareLoginKey = new byte[32]; byte[] connectTokenKey = new byte[32]; @@ -522,6 +1385,8 @@ private PreparedAccount newPreparedAccount() throws Exception { Map.of(GATEWAY_KEY_ID, gatewayKeyPair.getPublic()); AccountConnectTokenIssuanceRepository issuanceRepository = new AccountConnectTokenIssuanceRepository(dsl); + AccountBareLoginExchangeRepository bareLoginExchangeRepository = + new AccountBareLoginExchangeRepository(dsl); AccountRepository accountRepository = new AccountRepository(dsl); AccountTenantIdentityResolver tenantResolver = new AccountTenantIdentityResolver(associations, sourceEvidence, WORKLOAD_NAMESPACE); @@ -531,19 +1396,23 @@ private PreparedAccount newPreparedAccount() throws Exception { issuanceRepository, accountRepository, tenantResolver, + freshTenantIdentityRepository, joinRepository, envelopeCrypto, verifier, gatewayKeys, clock, WORKLOAD_NAMESPACE); - TestContext db = new TestContext(dsl, transaction, issuanceRepository, envelopeCrypto); + TestContext db = + new TestContext( + dsl, transaction, issuanceRepository, bareLoginExchangeRepository, envelopeCrypto); return new PreparedAccount( db, accountId, LEGACY_TENANT_ID, accountUuid, tenantUuid, + freshTenantUuid, accountKeyPair, unknownAccountKeyPair, gatewayKeyPair, @@ -552,6 +1421,7 @@ private PreparedAccount newPreparedAccount() throws Exception { gatewayKeys, accountRepository, tenantResolver, + freshTenantIdentityRepository, joinRepository, reader, clock); @@ -565,16 +1435,82 @@ private SourceFixture newSource( PreparedAccount prepared, SourceState state, SourceOptions options) throws Exception { String requestId = "source-request-" + UUID.randomUUID(); String connectScopeId = "source-scope-" + UUID.randomUUID(); - long sourceTenantId = - options.unmappedTenant() ? prepared.tenantId() + 1000L : prepared.tenantId(); + return newSource(prepared, state, options, requestId, connectScopeId); + } + + private SourceFixture newSource( + PreparedAccount prepared, SourceState state, SourceOptions options, String connectScopeId) + throws Exception { + String requestId = "source-request-" + UUID.randomUUID(); + return newSource(prepared, state, options, requestId, connectScopeId); + } + + private SourceFixture newSource( + PreparedAccount prepared, + SourceState state, + SourceOptions options, + String requestId, + String connectScopeId) + throws Exception { + return newSource(prepared, state, options, requestId, connectScopeId, SourceTarget.NORMAL); + } + + private SourceFixture newSourceWithTarget(PreparedAccount prepared, SourceTarget target) + throws Exception { + return newSource( + prepared, + SourceState.COMMITTED, + SourceOptions.NORMAL, + "source-request-" + UUID.randomUUID(), + "source-scope-" + UUID.randomUUID(), + target); + } + + private SourceFixture newFreshSource(PreparedAccount prepared, SourceTarget target) + throws Exception { + return newSource( + prepared, + SourceState.COMMITTED, + SourceOptions.NORMAL, + "source-request-" + UUID.randomUUID(), + "source-scope-" + UUID.randomUUID(), + target, + prepared.freshTenantUuid()); + } + + private SourceFixture newSource( + PreparedAccount prepared, + SourceState state, + SourceOptions options, + String requestId, + String connectScopeId, + SourceTarget target) + throws Exception { UUID sourceTenantUuid = options.unmappedTenant() ? UUID.randomUUID() : prepared.tenantUuid(); + return newSource(prepared, state, options, requestId, connectScopeId, target, sourceTenantUuid); + } + + private SourceFixture newSource( + PreparedAccount prepared, + SourceState state, + SourceOptions options, + String requestId, + String connectScopeId, + SourceTarget target, + UUID sourceTenantUuid) + throws Exception { AccountConnectTokenIssuanceIdentity identity = new AccountConnectTokenIssuanceIdentity( - prepared.accountId(), sourceTenantId, connectScopeId, requestId); + prepared.accountId(), sourceTenantUuid, connectScopeId, requestId); String tokenIdentity = "source-jti-" + UUID.randomUUID(); Map sourceClaims = sourceClaims( - prepared.accountUuid(), sourceTenantUuid, identity, tokenIdentity, prepared.clock()); + prepared.accountUuid(), + sourceTenantUuid, + identity, + tokenIdentity, + prepared.clock(), + target); KeyPair tokenSigner = options.unknownSourceKey() ? prepared.unknownAccountKeyPair() : prepared.accountKeyPair(); String tokenKeyId = options.unknownSourceKey() ? "unregistered-account-key" : ACCOUNT_KEY_ID; @@ -622,7 +1558,7 @@ private SourceFixture newSource( claim.operation().operationId().toString(), identity.requestId(), Long.toString(identity.accountId()), - Long.toString(identity.tenantId()), + identity.tenantId().toString(), identity.connectScopeId(), null, requestDigest, @@ -676,12 +1612,152 @@ private AccountEnvelopeCrypto differentConnectPurposeKey() throws Exception { return new AccountEnvelopeCrypto(manifest); } + private StoredBareLoginFixture storeBareLoginFrame( + PreparedAccount prepared, + SourceFixture source, + String originalGatewayContext, + byte[] originalResult, + byte[] operationResultHash) + throws Exception { + byte[] encodedFrame = + BareLoginRecoveryPayload.of(originalGatewayContext, originalResult).encode(); + byte[] storedResultHash = + operationResultHash == null ? sha256(originalResult) : operationResultHash.clone(); + try { + return storeBareLoginResponse(prepared, source, encodedFrame, storedResultHash); + } finally { + java.util.Arrays.fill(encodedFrame, (byte) 0); + java.util.Arrays.fill(storedResultHash, (byte) 0); + } + } + + private StoredBareLoginFixture storeOpaqueBareLoginPayload( + PreparedAccount prepared, SourceFixture source, byte[] opaquePayload) throws Exception { + byte[] resultHash = sha256(opaquePayload); + try { + return storeBareLoginResponse(prepared, source, opaquePayload, resultHash); + } finally { + java.util.Arrays.fill(resultHash, (byte) 0); + } + } + + private StoredBareLoginFixture storeBareLoginResponse( + PreparedAccount prepared, + SourceFixture source, + byte[] encryptedPlaintext, + byte[] storedResultHash) + throws Exception { + AccountCommittedConnectSource committedSource = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .issuanceRepository() + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow()); + AccountBareLoginExchangeIdentity identity = + new AccountBareLoginExchangeIdentity( + committedSource.operation().operationId(), + source.identity().accountId(), + source.identity().tenantId(), + source.identity().connectScopeId(), + "exchange-request-" + UUID.randomUUID()); + byte[] requestDigest = randomDigest(); + byte[] contextEvidenceDigest = randomDigest(); + byte[] authorityTupleDigest = randomDigest(); + byte[] issuanceFenceDigest = randomDigest(); + byte[] postconditionDigest = randomDigest(); + String resultTokenIdentity = "stored-result-jti-" + UUID.randomUUID(); + try { + AccountBareLoginResponseEnvelope stored = + inTransaction( + prepared.db().transaction(), + () -> { + var claim = + prepared.db().bareLoginExchangeRepository().claim(identity, requestDigest); + prepared + .db() + .bareLoginExchangeRepository() + .recordPendingEvidence( + claim, + requestDigest, + resultTokenIdentity, + storedResultHash, + contextEvidenceDigest, + authorityTupleDigest, + issuanceFenceDigest, + postconditionDigest); + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + claim.operation().operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + identity.tenantId().toString(), + identity.connectScopeId(), + identity.sourceConnectOperationId().toString(), + requestDigest, + contextEvidenceDigest, + authorityTupleDigest, + issuanceFenceDigest, + postconditionDigest); + AccountEncryptedEnvelope encrypted = + prepared + .db() + .envelopeCrypto() + .encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + binding, + encryptedPlaintext); + return prepared + .db() + .bareLoginExchangeRepository() + .completeWithEnvelope( + claim, + requestDigest, + resultTokenIdentity, + storedResultHash, + binding, + encrypted); + }); + return new StoredBareLoginFixture( + identity, requestDigest, source.identity(), stored.operationId()); + } finally { + java.util.Arrays.fill(contextEvidenceDigest, (byte) 0); + java.util.Arrays.fill(authorityTupleDigest, (byte) 0); + java.util.Arrays.fill(issuanceFenceDigest, (byte) 0); + java.util.Arrays.fill(postconditionDigest, (byte) 0); + } + } + + private static AccountStoredBareLoginRecoveryReader storedReader(PreparedAccount prepared) { + return storedReader(prepared, prepared.db().envelopeCrypto()); + } + + private static AccountStoredBareLoginRecoveryReader storedReader( + PreparedAccount prepared, AccountEnvelopeCrypto crypto) { + return new AccountStoredBareLoginRecoveryReader( + prepared.db().bareLoginExchangeRepository(), + prepared.joinRepository(), + crypto, + prepared.reader(), + prepared.gatewayKeys(), + WORKLOAD_NAMESPACE); + } + + private AccountEnvelopeCrypto missingKeyRingCrypto() { + return new AccountEnvelopeCrypto( + tempDir.resolve("missing-account-response-ring-" + UUID.randomUUID() + ".v1")); + } + private static AccountCommittedConnectSourceReader readerWithCrypto( PreparedAccount prepared, AccountEnvelopeCrypto crypto) { return new AccountCommittedConnectSourceReader( prepared.db().issuanceRepository(), prepared.accountRepository(), prepared.tenantResolver(), + prepared.freshTenantIdentityRepository(), prepared.joinRepository(), crypto, prepared.verifier(), @@ -695,7 +1771,8 @@ private static Map sourceClaims( UUID tenantUuid, AccountConnectTokenIssuanceIdentity identity, String tokenIdentity, - Clock clock) { + Clock clock, + SourceTarget target) { BigInteger one = BigInteger.ONE; BigInteger now = BigInteger.valueOf(clock.instant().getEpochSecond()); Map tenantGeneration = Map.of(tenantUuid.toString(), one); @@ -715,13 +1792,28 @@ private static Map sourceClaims( "account:auth-authority:v1:tenant/" + tenantUuid, "outboxSequence", one); + List privateRealmGrantVersions = + target.playtestLifecycleId() == null + ? List.of() + : List.of( + Map.of( + "tenantId", + tenantUuid.toString(), + "worldSlug", + target.worldSlug(), + "realmSlug", + target.realmSlug(), + "playtestLifecycleId", + target.playtestLifecycleId().toString(), + "grantVersion", + one)); Map authorityTuple = Map.of( "issuerAuthGeneration", one, "accountAuthorityGeneration", one, "tenantAuthorityGeneration", tenantGeneration, "membershipAuthorityGeneration", tenantGeneration, - "privateRealmGrantVersions", List.of(), + "privateRealmGrantVersions", privateRealmGrantVersions, "accountSecurityCutoff", accountSecurityCutoff, "tenantBillingCutoff", Map.of(tenantUuid.toString(), tenantBillingCutoffEntry)); Map claims = new LinkedHashMap<>(); @@ -733,8 +1825,8 @@ private static Map sourceClaims( claims.put("accountId", accountUuid.toString()); claims.put("tenantId", tenantUuid.toString()); claims.put("realmId", UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb").toString()); - claims.put("worldSlug", "world"); - claims.put("realmSlug", "realm"); + claims.put("worldSlug", target.worldSlug()); + claims.put("realmSlug", target.realmSlug()); claims.put( "playableStateNamespaceId", UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc").toString()); @@ -748,6 +1840,10 @@ private static Map sourceClaims( claims.put("authorityTuple", authorityTuple); claims.put("membershipVersion", membershipVersion); claims.put("replayAdmissionFence", one); + if (target.playtestLifecycleId() != null) { + claims.put("playtestLifecycleId", target.playtestLifecycleId().toString()); + claims.put("playtestStateGeneration", target.playtestStateGeneration()); + } return claims; } @@ -785,6 +1881,75 @@ private static ResolveLegacyAccountTenantAssociationResponse approvedAssociation .build(); } + private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + long sourceGameRowId = 9001L; + String sourceGameTenantKey = UUID.randomUUID().toString(); + String requestDigest = + GameTenantCreationDigest.requestDigest( + WORKLOAD_NAMESPACE, + creationRequestId, + sourceGameTenantKey, + "Fresh source reader test tenant", + null); + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + WORKLOAD_NAMESPACE, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + WORKLOAD_NAMESPACE, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static AccountEnvelopeBinding bareLoginBinding( + AccountBareLoginExchangeOperation operation, AccountBareLoginExchangeIdentity identity) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operation.operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + identity.tenantId().toString(), + identity.connectScopeId(), + identity.sourceConnectOperationId().toString(), + operation.requestDigest(), + operation.contextEvidenceDigest(), + operation.authorityTupleDigest(), + operation.issuanceFenceDigest(), + operation.postconditionDigest()); + } + + private static AccountEnvelopeBinding withTenantId( + AccountEnvelopeBinding binding, String tenantId) { + return new AccountEnvelopeBinding( + binding.operationKind(), + binding.operationId(), + binding.requestId(), + binding.accountId(), + tenantId, + binding.connectScopeId(), + binding.sourceConnectOperationId(), + binding.requestDigest(), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + } + private static long insertRetainedRows(DSLContext dsl, long tenantId, String username) { Number inserted = Objects.requireNonNull( @@ -847,6 +2012,27 @@ private static Snapshot sourceSnapshot( row.get(3, Long.class)); } + private static BareLoginSnapshot bareLoginSnapshot(PreparedAccount prepared, UUID operationId) { + Record row = + prepared + .db() + .dsl() + .resultQuery( + "SELECT operation_id, status, updated_at::text, " + + "(SELECT count(*) FROM account_bare_login_response_envelopes e " + + "WHERE e.operation_id = o.operation_id) " + + "FROM account_bare_login_exchange_operations o WHERE operation_id = ?", + operationId) + .fetchOne(); + return row == null + ? new BareLoginSnapshot(null, null, null, 0L) + : new BareLoginSnapshot( + row.get(0, UUID.class), + row.get(1, String.class), + row.get(2, String.class), + row.get(3, Long.class)); + } + private static boolean awaitAccountFenceBlock( DSLContext dsl, int readerBackendPid, int blockerBackendPid, Duration timeout) throws InterruptedException { @@ -869,6 +2055,29 @@ private static boolean awaitAccountFenceBlock( return false; } + private static boolean awaitRelationLockBlock( + DSLContext dsl, int readerBackendPid, int blockerBackendPid, Duration timeout) + throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + dsl.resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity waiting " + + "JOIN pg_locks waiting_lock ON waiting_lock.pid = waiting.pid " + + "WHERE waiting.pid = ? AND waiting.wait_event_type = 'Lock' " + + "AND waiting_lock.locktype = 'relation' AND NOT waiting_lock.granted " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)))", + readerBackendPid, + blockerBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + private static boolean await(CountDownLatch latch, long timeout, TimeUnit unit) { try { return latch.await(timeout, unit); @@ -904,6 +2113,194 @@ private static void assertReadRejected( .hasMessageContaining(messageFragment); } + private static void assertHistoricalReadRejected( + PreparedAccount prepared, + SourceFixture source, + Class exceptionType, + String messageFragment) { + assertHistoricalReadRejected( + prepared.reader(), prepared, source, exceptionType, messageFragment); + } + + private static void assertHistoricalReadRejected( + AccountCommittedConnectSourceReader reader, + PreparedAccount prepared, + SourceFixture source, + Class exceptionType, + String messageFragment) { + Snapshot before = sourceSnapshot(prepared, source.identity()); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + reader.readHistorical( + source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(exceptionType) + .hasMessageContaining(messageFragment); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + } + + private static void assertStoredReadRejected( + AccountStoredBareLoginRecoveryReader reader, + PreparedAccount prepared, + StoredBareLoginFixture stored, + byte[] requestDigest, + Class exceptionType, + String messageFragment) { + Snapshot sourceBefore = sourceSnapshot(prepared, stored.sourceIdentity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> reader.readHistorical(stored.identity(), requestDigest)))) + .isInstanceOf(exceptionType) + .hasMessageContaining(messageFragment); + assertThat(sourceSnapshot(prepared, stored.sourceIdentity())).isEqualTo(sourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + private static HistoricalStoredBareLoginCorrelationEvidence readCorrelation( + AccountStoredBareLoginRecoveryReader reader, + PreparedAccount prepared, + StoredBareLoginFixture stored, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext) { + return readCorrelation( + reader, + prepared, + stored.identity(), + stored.requestDigest(), + freshIdentity, + signedFreshGatewayContext); + } + + private static HistoricalStoredBareLoginCorrelationEvidence readCorrelation( + AccountStoredBareLoginRecoveryReader reader, + PreparedAccount prepared, + AccountBareLoginExchangeIdentity originalIdentity, + byte[] originalRequestDigest, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext) { + return withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + reader.readCorrelation( + originalIdentity, + originalRequestDigest, + freshIdentity, + signedFreshGatewayContext))); + } + + private static void assertCorrelationReadRejected( + PreparedAccount prepared, + AccountStoredBareLoginRecoveryReader reader, + StoredBareLoginFixture stored, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext, + Class exceptionType, + String messageFragment) { + assertCorrelationReadRejected( + prepared, + reader, + stored, + stored.identity(), + stored.requestDigest(), + freshIdentity, + signedFreshGatewayContext, + exceptionType, + messageFragment); + } + + private static void assertCorrelationReadRejected( + PreparedAccount prepared, + AccountStoredBareLoginRecoveryReader reader, + StoredBareLoginFixture stored, + byte[] originalRequestDigest, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext, + Class exceptionType, + String messageFragment) { + assertCorrelationReadRejected( + prepared, + reader, + stored, + stored.identity(), + originalRequestDigest, + freshIdentity, + signedFreshGatewayContext, + exceptionType, + messageFragment); + } + + private static void assertCorrelationReadRejected( + PreparedAccount prepared, + AccountStoredBareLoginRecoveryReader reader, + StoredBareLoginFixture stored, + AccountBareLoginExchangeIdentity originalIdentity, + byte[] originalRequestDigest, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext, + Class exceptionType, + String messageFragment) { + Snapshot originalSourceBefore = sourceSnapshot(prepared, stored.sourceIdentity()); + Snapshot freshSourceBefore = sourceSnapshot(prepared, freshIdentity); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + assertThatThrownBy( + () -> + readCorrelation( + reader, + prepared, + originalIdentity, + originalRequestDigest, + freshIdentity, + signedFreshGatewayContext)) + .isInstanceOf(exceptionType) + .hasMessageContaining(messageFragment); + assertThat(sourceSnapshot(prepared, stored.sourceIdentity())).isEqualTo(originalSourceBefore); + assertThat(sourceSnapshot(prepared, freshIdentity)).isEqualTo(freshSourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + private static void assertCorrelationIdentityRejected( + PreparedAccount prepared, + AccountStoredBareLoginRecoveryReader reader, + StoredBareLoginFixture stored, + AccountConnectTokenIssuanceIdentity freshIdentity) { + Snapshot originalSourceBefore = sourceSnapshot(prepared, stored.sourceIdentity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + assertThatThrownBy( + () -> + readCorrelation( + reader, prepared, stored, freshIdentity, "unused-unverified-context")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("same Account and tenant"); + assertThat(sourceSnapshot(prepared, stored.sourceIdentity())).isEqualTo(originalSourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + private static String resignCurrentGatewayContext(PreparedAccount prepared, SourceFixture source) + throws Exception { + Map currentClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + source.sourceClaims(), + prepared.clock().instant().getEpochSecond(), + "gateway-request-" + UUID.randomUUID()); + byte[] payload = JSON.writeValueAsBytes(currentClaims); + return GatewayConnectContextSignature.sign( + payload, GATEWAY_KEY_ID, prepared.gatewayKeyPair().getPrivate()); + } + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { Context scoped = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); Context previous = scoped.attach(); @@ -932,6 +2329,12 @@ private static byte[] digest(String value) { return sha256(value.getBytes(StandardCharsets.UTF_8)); } + private static byte[] randomDigest() { + byte[] value = new byte[32]; + FIXTURE_RANDOM.nextBytes(value); + return value; + } + private static byte[] sha256(byte[] value) { try { return MessageDigest.getInstance("SHA-256").digest(value); @@ -963,10 +2366,26 @@ private record SourceOptions( new SourceOptions(false, false, false, false, false, false, false); } + private record SourceTarget( + String worldSlug, + String realmSlug, + UUID playtestLifecycleId, + BigInteger playtestStateGeneration) { + private static final SourceTarget NORMAL = new SourceTarget("world", "realm", null, null); + + private SourceTarget { + if ((playtestLifecycleId == null) != (playtestStateGeneration == null)) { + throw new IllegalArgumentException( + "Playtest lifecycle and generation must appear together"); + } + } + } + private record TestContext( DSLContext dsl, TransactionTemplate transaction, AccountConnectTokenIssuanceRepository issuanceRepository, + AccountBareLoginExchangeRepository bareLoginExchangeRepository, AccountEnvelopeCrypto envelopeCrypto) {} private record PreparedAccount( @@ -975,6 +2394,7 @@ private record PreparedAccount( long tenantId, UUID accountUuid, UUID tenantUuid, + UUID freshTenantUuid, KeyPair accountKeyPair, KeyPair unknownAccountKeyPair, KeyPair gatewayKeyPair, @@ -983,6 +2403,7 @@ private record PreparedAccount( Map gatewayKeys, AccountRepository accountRepository, AccountTenantIdentityResolver tenantResolver, + FreshTenantIdentityAssociationRepository freshTenantIdentityRepository, AccountJoinOperationRepository joinRepository, AccountCommittedConnectSourceReader reader, TestClock clock) {} @@ -994,8 +2415,26 @@ private record SourceFixture( Map gatewayClaims, String tokenIdentity) {} + private record StoredBareLoginFixture( + AccountBareLoginExchangeIdentity identity, + byte[] requestDigest, + AccountConnectTokenIssuanceIdentity sourceIdentity, + UUID operationId) { + private StoredBareLoginFixture { + requestDigest = requestDigest.clone(); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + } + private record Snapshot(UUID operationId, String status, String updatedAt, long envelopeCount) {} + private record BareLoginSnapshot( + UUID operationId, String status, String updatedAt, long envelopeCount) {} + private static final class TestClock extends Clock { private volatile Instant now; private final ZoneId zone; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountConnectStorageUuidMigrationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountConnectStorageUuidMigrationIntegrationTest.java new file mode 100644 index 0000000000..0571e37599 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountConnectStorageUuidMigrationIntegrationTest.java @@ -0,0 +1,794 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +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.AccountEnvelopePurpose; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +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 AccountConnectStorageUuidMigrationIntegrationTest { + private static final String HISTORY_TABLE = "flyway_schema_history_account_connect_storage"; + private static final String CONNECT_SCOPE_ID = "connect-scope-migration-proof"; + private static final String SCOPE_HASH = AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID); + private static final String DIGEST_SQL = "decode(repeat('11', 32), 'hex')"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshMigrationsAndEmptyV39UpgradeUseCanonicalUuidColumns() throws Exception { + Database fresh = newDatabase(); + flyway(fresh, null).migrate(); + assertTenantTypes(fresh, "uuid"); + + Database upgraded = newDatabase(); + flyway(upgraded, "39").migrate(); + assertTenantTypes(upgraded, "bigint"); + flyway(upgraded, null).migrate(); + assertTenantTypes(upgraded, "uuid"); + } + + @Test + void retainedConnectOperationBlocksMigrationWithoutChangingItsRow() throws Exception { + Database database = newDatabase(); + flyway(database, "39").migrate(); + try (Connection connection = database.dataSource().getConnection()) { + AccountRow account = insertAccount(connection, database); + insertPendingConnectOperation(connection, database, account, 81L, UUID.randomUUID()); + } + assertMigrationRefusesWithoutChangingEvidence(database); + } + + @Test + void retainedConnectEnvelopeBlocksMigrationWithoutChangingCiphertext(@TempDir Path directory) + throws Exception { + Database database = newDatabase(); + AccountEnvelopeCrypto crypto = keyRing(directory); + flyway(database, "39").migrate(); + try (Connection connection = database.dataSource().getConnection()) { + connection.setAutoCommit(false); + AccountRow account = insertAccount(connection, database); + insertCommittedConnectChain(connection, database, account, 82L, UUID.randomUUID(), crypto); + connection.commit(); + } + assertMigrationRefusesWithoutChangingEvidence(database, crypto); + } + + @Test + void retainedBareLoginOperationAndEnvelopeBlockMigrationWithoutChangingEvidence( + @TempDir Path directory) throws Exception { + Database database = newDatabase(); + AccountEnvelopeCrypto crypto = keyRing(directory); + flyway(database, "39").migrate(); + try (Connection connection = database.dataSource().getConnection()) { + connection.setAutoCommit(false); + AccountRow account = insertAccount(connection, database); + UUID sourceOperationId = UUID.randomUUID(); + insertCommittedConnectChain(connection, database, account, 83L, sourceOperationId, crypto); + insertCommittedBareLoginChain( + connection, database, account, 83L, sourceOperationId, UUID.randomUUID(), crypto); + connection.commit(); + } + assertMigrationRefusesWithoutChangingEvidence(database, crypto); + } + + @Test + void migrationWaitsForConcurrentWriterThenRejectsItsCommittedEvidence() throws Exception { + Database database = newDatabase(); + flyway(database, "39").migrate(); + UUID operationId = UUID.randomUUID(); + Connection writer = database.dataSource().getConnection(); + writer.setAutoCommit(false); + AccountRow account = insertAccount(writer, database); + insertPendingConnectOperation(writer, database, account, 84L, operationId); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future migration = executor.submit(() -> flyway(database, null).migrate()); + assertThat(awaitMigrationLockWait(database.dataSource(), Duration.ofSeconds(10))).isTrue(); + assertThat(migration.isDone()).isFalse(); + + writer.commit(); + assertThatThrownBy(() -> migration.get(20, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .satisfies(AccountConnectStorageUuidMigrationIntegrationTest::assertSqlMigrationRefusal); + } finally { + try { + writer.rollback(); + } finally { + writer.close(); + executor.shutdownNow(); + } + } + + assertThat(columnType(database, "account_connect_token_issuance_operations")) + .isEqualTo("bigint"); + assertThat(rowCount(database, "account_connect_token_issuance_operations")).isEqualTo(1); + } + + @Test + void uuidUpgradePreservesOperationEnvelopeAndDeferredSourceGuards(@TempDir Path directory) + throws Exception { + Database database = newDatabase(); + AccountEnvelopeCrypto crypto = keyRing(directory); + flyway(database, "39").migrate(); + flyway(database, null).migrate(); + + UUID tenantId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + try (Connection connection = database.dataSource().getConnection()) { + connection.setAutoCommit(false); + AccountRow account = insertAccount(connection, database); + insertCommittedConnectChain( + connection, database, account, tenantId, sourceOperationId, crypto); + insertCommittedBareLoginChain( + connection, database, account, tenantId, sourceOperationId, UUID.randomUUID(), crypto); + connection.commit(); + } + + assertThat(rowCount(database, "account_connect_token_issuance_operations")).isEqualTo(1); + assertThat(rowCount(database, "account_connect_token_response_envelopes")).isEqualTo(1); + assertThat(rowCount(database, "account_bare_login_exchange_operations")).isEqualTo(1); + assertThat(rowCount(database, "account_bare_login_response_envelopes")).isEqualTo(1); + assertTenantTypes(database, "uuid"); + assertStoredEnvelopesDecrypt(database, crypto, 1, 1); + + try (Connection connection = database.dataSource().getConnection()) { + assertThatThrownBy( + () -> + execute( + connection, + "UPDATE " + + table(database, "account_connect_token_issuance_operations") + + " SET tenant_id = ? WHERE operation_id = ?", + UUID.randomUUID(), + sourceOperationId)) + .isInstanceOf(SQLException.class) + .hasMessageContaining("Connect-token issuance identity and request digest are immutable"); + } + } + + private static void assertMigrationRefusesWithoutChangingEvidence(Database database) + throws Exception { + assertMigrationRefusesWithoutChangingEvidence(database, null); + } + + private static void assertMigrationRefusesWithoutChangingEvidence( + Database database, AccountEnvelopeCrypto crypto) throws Exception { + EvidenceSnapshot before = snapshot(database); + + assertThatThrownBy(() -> flyway(database, null).migrate()) + .satisfies(AccountConnectStorageUuidMigrationIntegrationTest::assertSqlMigrationRefusal); + + assertThat(snapshot(database)).isEqualTo(before); + assertTenantTypes(database, "bigint"); + if (crypto != null) { + assertStoredEnvelopesDecrypt( + database, + crypto, + before.connectCiphertexts().size(), + before.bareLoginCiphertexts().size()); + } + } + + private static void assertSqlMigrationRefusal(Throwable exception) { + SQLException sqlException = findSqlException(exception); + assertThat(sqlException.getSQLState()).isEqualTo("23514"); + assertThat(sqlException.getMessage()) + .contains( + "Account connect storage UUID migration requires all four operation and envelope tables to be empty"); + } + + private static SQLException findSqlException(Throwable exception) { + Throwable current = exception; + while (current != null) { + if (current instanceof SQLException sqlException) { + return sqlException; + } + current = current.getCause(); + } + throw new AssertionError("Migration refusal did not contain a JDBC SQL exception", exception); + } + + private static EvidenceSnapshot snapshot(Database database) throws SQLException { + return new EvidenceSnapshot( + rows(database, "account_connect_token_issuance_operations"), + rows(database, "account_connect_token_response_envelopes"), + ciphertexts(database, "account_connect_token_response_envelopes"), + rows(database, "account_bare_login_exchange_operations"), + rows(database, "account_bare_login_response_envelopes"), + ciphertexts(database, "account_bare_login_response_envelopes")); + } + + private static List rows(Database database, String table) throws SQLException { + try (Connection connection = database.dataSource().getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT to_jsonb(t)::text FROM " + + table(database, table) + + " t ORDER BY t.operation_id")) { + List rows = new ArrayList<>(); + while (result.next()) { + rows.add(result.getString(1)); + } + return rows; + } + } + + private static List ciphertexts(Database database, String table) throws SQLException { + try (Connection connection = database.dataSource().getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT encode(ciphertext, 'hex') FROM " + + table(database, table) + + " ORDER BY operation_id")) { + List values = new ArrayList<>(); + while (result.next()) { + values.add(result.getString(1)); + } + return values; + } + } + + private static boolean awaitMigrationLockWait(DataSource dataSource, Duration timeout) + throws Exception { + long deadline = System.nanoTime() + timeout.toNanos(); + String query = + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid <> pg_backend_pid() " + + "AND wait_event_type = 'Lock' " + + "AND query ILIKE '%LOCK TABLE account_connect_token_issuance_operations%')"; + do { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery(query)) { + if (result.next() && result.getBoolean(1)) { + return true; + } + } + TimeUnit.MILLISECONDS.sleep(25); + } while (System.nanoTime() < deadline); + return false; + } + + private static void assertTenantTypes(Database database, String expected) throws SQLException { + for (String table : + List.of( + "account_connect_token_issuance_operations", + "account_connect_token_response_envelopes", + "account_bare_login_exchange_operations", + "account_bare_login_response_envelopes")) { + assertThat(columnType(database, table)).as(table + ".tenant_id type").isEqualTo(expected); + } + } + + private static String columnType(Database database, String table) throws SQLException { + try (Connection connection = database.dataSource().getConnection(); + PreparedStatement statement = + connection.prepareStatement( + "SELECT data_type FROM information_schema.columns " + + "WHERE table_schema = ? AND table_name = ? AND column_name = 'tenant_id'")) { + statement.setString(1, database.schema()); + statement.setString(2, table); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + return result.getString(1); + } + } + } + + private static long rowCount(Database database, String table) throws SQLException { + try (Connection connection = database.dataSource().getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery("SELECT COUNT(*) FROM " + table(database, table))) { + assertThat(result.next()).isTrue(); + return result.getLong(1); + } + } + + private static AccountRow insertAccount(Connection connection, Database database) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO " + + table(database, "accounts") + + " (username, email, password_hash) VALUES (?, ?, ?) RETURNING id")) { + statement.setString(1, "migration-user-" + UUID.randomUUID()); + statement.setString(2, UUID.randomUUID() + "@example.test"); + statement.setString(3, "test-hash"); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + return new AccountRow(result.getLong(1)); + } + } + } + + private static void insertPendingConnectOperation( + Connection connection, + Database database, + AccountRow account, + Object tenantId, + UUID operationId) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO " + + table(database, "account_connect_token_issuance_operations") + + " (operation_id, account_id, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, status) " + + "VALUES (?, ?, ?, ?, ?, 1, " + + DIGEST_SQL + + ", 'PENDING')")) { + statement.setObject(1, operationId); + statement.setLong(2, account.id()); + setTenant(statement, 3, tenantId); + statement.setString(4, SCOPE_HASH); + statement.setString(5, "connect-request-" + operationId); + statement.executeUpdate(); + } + } + + private static void insertCommittedConnectChain( + Connection connection, + Database database, + AccountRow account, + Object tenantId, + UUID operationId, + AccountEnvelopeCrypto crypto) + throws SQLException { + String requestId = "connect-request-" + operationId; + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO " + + table(database, "account_connect_token_issuance_operations") + + " (operation_id, account_id, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, status, outcome_code, token_identity, " + + "token_hash, context_evidence_digest, authority_tuple_digest, " + + "issuance_fence_digest, postcondition_digest) " + + "VALUES (?, ?, ?, ?, ?, 1, " + + DIGEST_SQL + + ", 'COMMITTED', 'SUCCESS', ?, " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ")")) { + statement.setObject(1, operationId); + statement.setLong(2, account.id()); + setTenant(statement, 3, tenantId); + statement.setString(4, SCOPE_HASH); + statement.setString(5, requestId); + statement.setString(6, "connect-token-" + operationId); + statement.executeUpdate(); + } + insertConnectEnvelope(connection, database, account, tenantId, operationId, requestId, crypto); + } + + private static void insertConnectEnvelope( + Connection connection, + Database database, + AccountRow account, + Object tenantId, + UUID operationId, + String requestId, + AccountEnvelopeCrypto crypto) + throws SQLException { + AccountEnvelopeBinding binding = connectBinding(operationId, requestId, account.id(), tenantId); + AccountEncryptedEnvelope envelope = + crypto.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding, connectPlaintext(operationId)); + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO " + + table(database, "account_connect_token_response_envelopes") + + " (operation_id, operation_kind, account_id, tenant_id, connect_scope_hash, " + + "request_id, request_digest_version, request_digest, format_version, key_id, " + + "purpose, nonce, ciphertext, context_evidence_digest, authority_tuple_digest, " + + "issuance_fence_digest, postcondition_digest) " + + "VALUES (?, 'CONNECT_TOKEN_ISSUANCE', ?, ?, ?, ?, 1, " + + DIGEST_SQL + + ", ?, ?, 'CONNECT_TOKEN_RESPONSE', ?, ?, " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ")")) { + statement.setObject(1, operationId); + statement.setLong(2, account.id()); + setTenant(statement, 3, tenantId); + statement.setString(4, SCOPE_HASH); + statement.setString(5, requestId); + statement.setInt(6, envelope.formatVersion()); + statement.setString(7, envelope.keyId()); + statement.setBytes(8, envelope.nonce()); + statement.setBytes(9, envelope.ciphertext()); + statement.executeUpdate(); + } + } + + private static void insertCommittedBareLoginChain( + Connection connection, + Database database, + AccountRow account, + Object tenantId, + UUID sourceOperationId, + UUID exchangeOperationId, + AccountEnvelopeCrypto crypto) + throws SQLException { + String requestId = "bare-login-request-" + exchangeOperationId; + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO " + + table(database, "account_bare_login_exchange_operations") + + " (operation_id, source_connect_operation_id, account_id, tenant_id, " + + "connect_scope_hash, request_id, request_digest_version, request_digest, " + + "status, outcome_code, token_identity, token_hash, context_evidence_digest, " + + "authority_tuple_digest, issuance_fence_digest, postcondition_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, 1, " + + DIGEST_SQL + + ", 'COMMITTED', 'SUCCESS', ?, " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ")")) { + statement.setObject(1, exchangeOperationId); + statement.setObject(2, sourceOperationId); + statement.setLong(3, account.id()); + setTenant(statement, 4, tenantId); + statement.setString(5, SCOPE_HASH); + statement.setString(6, requestId); + statement.setString(7, "bare-login-token-" + exchangeOperationId); + statement.executeUpdate(); + } + insertBareLoginEnvelope( + connection, + database, + account, + tenantId, + sourceOperationId, + exchangeOperationId, + requestId, + crypto); + } + + private static void insertBareLoginEnvelope( + Connection connection, + Database database, + AccountRow account, + Object tenantId, + UUID sourceOperationId, + UUID exchangeOperationId, + String requestId, + AccountEnvelopeCrypto crypto) + throws SQLException { + AccountEnvelopeBinding binding = + bareLoginBinding(exchangeOperationId, requestId, account.id(), tenantId, sourceOperationId); + AccountEncryptedEnvelope envelope = + crypto.encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + binding, + bareLoginPlaintext(exchangeOperationId)); + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO " + + table(database, "account_bare_login_response_envelopes") + + " (operation_id, operation_kind, source_connect_operation_id, account_id, " + + "tenant_id, connect_scope_hash, request_id, request_digest_version, " + + "request_digest, format_version, key_id, purpose, nonce, ciphertext, " + + "context_evidence_digest, authority_tuple_digest, issuance_fence_digest, " + + "postcondition_digest) VALUES (?, 'BARE_LOGIN_EXCHANGE', ?, ?, ?, ?, ?, 1, " + + DIGEST_SQL + + ", ?, ?, 'BARE_LOGIN_RESPONSE', ?, ?, " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ", " + + DIGEST_SQL + + ")")) { + statement.setObject(1, exchangeOperationId); + statement.setObject(2, sourceOperationId); + statement.setLong(3, account.id()); + setTenant(statement, 4, tenantId); + statement.setString(5, SCOPE_HASH); + statement.setString(6, requestId); + statement.setInt(7, envelope.formatVersion()); + statement.setString(8, envelope.keyId()); + statement.setBytes(9, envelope.nonce()); + statement.setBytes(10, envelope.ciphertext()); + statement.executeUpdate(); + } + } + + private static AccountEnvelopeCrypto keyRing(Path directory) throws IOException { + byte[] connectKey = new byte[32]; + byte[] bareLoginKey = new byte[32]; + Arrays.fill(connectKey, (byte) 1); + Arrays.fill(bareLoginKey, (byte) 2); + Path manifest = directory.resolve("account-envelope-test-ring.v1"); + Files.writeString( + manifest, + "version=1\nactiveKeyId=k1\n" + + "key:k1:bare-login=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(bareLoginKey) + + "\nkey:k1:connect-token=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(connectKey) + + "\n", + StandardCharsets.US_ASCII); + Arrays.fill(connectKey, (byte) 0); + Arrays.fill(bareLoginKey, (byte) 0); + return new AccountEnvelopeCrypto(manifest); + } + + private static void assertStoredEnvelopesDecrypt( + Database database, + AccountEnvelopeCrypto crypto, + int expectedConnectEnvelopes, + int expectedBareLoginEnvelopes) + throws SQLException { + assertThat(assertConnectEnvelopesDecrypt(database, crypto)).isEqualTo(expectedConnectEnvelopes); + assertThat(assertBareLoginEnvelopesDecrypt(database, crypto)) + .isEqualTo(expectedBareLoginEnvelopes); + } + + private static int assertConnectEnvelopesDecrypt(Database database, AccountEnvelopeCrypto crypto) + throws SQLException { + String sql = + "SELECT op.operation_id, op.request_id, op.account_id, op.tenant_id::text, " + + "op.request_digest, op.context_evidence_digest, op.authority_tuple_digest, " + + "op.issuance_fence_digest, op.postcondition_digest, env.format_version, " + + "env.key_id, env.purpose, env.nonce, env.ciphertext " + + "FROM " + + table(database, "account_connect_token_issuance_operations") + + " op JOIN " + + table(database, "account_connect_token_response_envelopes") + + " env USING (operation_id) ORDER BY op.operation_id"; + try (Connection connection = database.dataSource().getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery(sql)) { + int rows = 0; + while (result.next()) { + UUID operationId = result.getObject(1, UUID.class); + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + operationId.toString(), + result.getString(2), + Long.toString(result.getLong(3)), + result.getString(4), + CONNECT_SCOPE_ID, + null, + result.getBytes(5), + result.getBytes(6), + result.getBytes(7), + result.getBytes(8), + result.getBytes(9)); + AccountEncryptedEnvelope envelope = + new AccountEncryptedEnvelope( + result.getInt(10), + result.getString(11), + AccountEnvelopePurpose.valueOf(result.getString(12)), + result.getBytes(13), + result.getBytes(14)); + assertThat(crypto.decrypt(envelope, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding)) + .containsExactly(connectPlaintext(operationId)); + rows++; + } + return rows; + } + } + + private static int assertBareLoginEnvelopesDecrypt( + Database database, AccountEnvelopeCrypto crypto) throws SQLException { + String sql = + "SELECT op.operation_id, op.source_connect_operation_id, op.request_id, op.account_id, " + + "op.tenant_id::text, op.request_digest, op.context_evidence_digest, " + + "op.authority_tuple_digest, op.issuance_fence_digest, op.postcondition_digest, " + + "env.format_version, env.key_id, env.purpose, env.nonce, env.ciphertext " + + "FROM " + + table(database, "account_bare_login_exchange_operations") + + " op JOIN " + + table(database, "account_bare_login_response_envelopes") + + " env USING (operation_id) ORDER BY op.operation_id"; + try (Connection connection = database.dataSource().getConnection(); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery(sql)) { + int rows = 0; + while (result.next()) { + UUID operationId = result.getObject(1, UUID.class); + UUID sourceOperationId = result.getObject(2, UUID.class); + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operationId.toString(), + result.getString(3), + Long.toString(result.getLong(4)), + result.getString(5), + CONNECT_SCOPE_ID, + sourceOperationId.toString(), + result.getBytes(6), + result.getBytes(7), + result.getBytes(8), + result.getBytes(9), + result.getBytes(10)); + AccountEncryptedEnvelope envelope = + new AccountEncryptedEnvelope( + result.getInt(11), + result.getString(12), + AccountEnvelopePurpose.valueOf(result.getString(13)), + result.getBytes(14), + result.getBytes(15)); + assertThat(crypto.decrypt(envelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, binding)) + .containsExactly(bareLoginPlaintext(operationId)); + rows++; + } + return rows; + } + } + + private static AccountEnvelopeBinding connectBinding( + UUID operationId, String requestId, long accountId, Object tenantId) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + operationId.toString(), + requestId, + Long.toString(accountId), + tenantText(tenantId), + CONNECT_SCOPE_ID, + null, + digest(), + digest(), + digest(), + digest(), + digest()); + } + + private static AccountEnvelopeBinding bareLoginBinding( + UUID operationId, String requestId, long accountId, Object tenantId, UUID sourceOperationId) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operationId.toString(), + requestId, + Long.toString(accountId), + tenantText(tenantId), + CONNECT_SCOPE_ID, + sourceOperationId.toString(), + digest(), + digest(), + digest(), + digest(), + digest()); + } + + private static String tenantText(Object tenantId) { + return tenantId instanceof Long numericTenantId + ? Long.toString(numericTenantId) + : tenantId.toString(); + } + + private static byte[] digest() { + byte[] value = new byte[32]; + Arrays.fill(value, (byte) 0x11); + return value; + } + + private static byte[] connectPlaintext(UUID operationId) { + return ("original-connect-token-response:" + operationId).getBytes(StandardCharsets.UTF_8); + } + + private static byte[] bareLoginPlaintext(UUID operationId) { + return ("original-bare-login-response:" + operationId).getBytes(StandardCharsets.UTF_8); + } + + private static void setTenant(PreparedStatement statement, int index, Object tenantId) + throws SQLException { + if (tenantId instanceof Long numericTenantId) { + statement.setLong(index, numericTenantId); + } else { + statement.setObject(index, tenantId); + } + } + + private static void execute(Connection connection, String sql, Object... values) + throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(sql)) { + for (int index = 0; index < values.length; index++) { + statement.setObject(index + 1, values[index]); + } + statement.executeUpdate(); + } + } + + private static Flyway flyway(Database database, String target) { + var configuration = + Flyway.configure() + .dataSource(database.dataSource()) + .schemas(database.schema()) + .defaultSchema(database.schema()) + .table(HISTORY_TABLE) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(MigrationVersion.fromVersion(target)); + } + return configuration.load(); + } + + private static Database newDatabase() throws SQLException { + String schema = "account_connect_uuid_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), 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 String table(Database database, String table) { + return database.schema() + "." + table; + } + + private record Database(String schema, DataSource dataSource) {} + + private record AccountRow(long id) {} + + private record EvidenceSnapshot( + List connectOperations, + List connectEnvelopes, + List connectCiphertexts, + List bareLoginOperations, + List bareLoginEnvelopes, + List bareLoginCiphertexts) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java new file mode 100644 index 0000000000..fedb879aea --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java @@ -0,0 +1,816 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +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.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.AopTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=firemud-unit1b" + }) +class AccountFreshUuidMembershipSnapshotIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AccountMembershipAuthorityEventProducer producer; + @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; + @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; + @Autowired private FreshTenantIdentityAssociationRepository freshAssociationRepository; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoSpyBean private AccountJoinOperationRepository joinOperationRepository; + @MockitoSpyBean private AccountMembershipPairAuthorityRepository pairAuthorityRepository; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @Test + void freshUuidSnapshotEnrollsExactNonAdmittingBaselineAndRetriesWithoutSideEffects() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = importFreshTenantAssociation(tenantUuid); + long originalIssuanceFence = issuanceFence(account.accountUuid()); + + var first = readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + Map pairRow = membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + + assertThat(first.accountId()).isEqualTo(account.accountUuid().toString()); + assertThat(first.tenantId()).isEqualTo(tenantUuid.toString()); + assertThat(first.membershipExists()).isFalse(); + assertThat(first.membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(first.gameplayAdmissionAllowed()).isFalse(); + assertThat(first.roles()).isEmpty(); + assertThat(first.membershipVersion()).isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.authorityTuple().privateRealmGrantVersions()).isEmpty(); + assertThat(first.authorityTuple().accountSecurityCutoff()).isEmpty(); + assertThat(first.authorityTuple().tenantBillingCutoff()).isEmpty(); + assertThat(first.issuanceFence()).isEqualTo(Long.toString(originalIssuanceFence)); + assertThat(first.evaluatedAt()).isNotNull(); + assertThat(first.outboxStreamKey()) + .isEqualTo(membershipStreamKey(account.accountUuid(), tenantUuid)); + assertThat(first.outboxCheckpoints()) + .containsExactlyElementsOf(expectedCheckpoints(account.accountUuid(), tenantUuid)); + assertThat(first.outboxSourceEvidence()).isEmpty(); + assertThat(pairRow) + .containsEntry("account_uuid", account.accountUuid()) + .containsEntry("tenant_uuid", tenantUuid) + .containsEntry("legacy_tenant_id", null) + .containsEntry("tenant_provenance_kind", "FRESH_GAME_DESIGN") + .containsEntry("tenant_source_operation_id", evidence.operationId()) + .containsEntry("tenant_provenance_digest", evidence.evidenceDigest()) + .containsEntry("membership_exists", false) + .containsEntry("membership_version", 1L) + .containsEntry("membership_authority_generation", 1L) + .containsEntry("last_event_sequence", 0L) + .containsEntry("last_event_id", null) + .containsEntry("last_event_digest", null); + assertThat(authorityGeneration("MEMBERSHIP", account.accountUuid(), tenantUuid)).isEqualTo(1L); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countFreshCanonicalClaim(tenantUuid)).isEqualTo(1L); + assertThat(countApprovedAssociationForCanonicalTenant(tenantUuid)).isZero(); + + var retry = readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + assertThat(retry.accountId()).isEqualTo(first.accountId()); + assertThat(retry.tenantId()).isEqualTo(first.tenantId()); + assertThat(retry.membershipVersion()).isEqualTo(first.membershipVersion()); + assertThat(retry.membershipAuthorityGeneration()) + .isEqualTo(first.membershipAuthorityGeneration()); + assertThat(retry.authorityTuple()).isEqualTo(first.authorityTuple()); + assertThat(retry.issuanceFence()).isEqualTo(first.issuanceFence()); + assertThat(retry.outboxCheckpoints()).isEqualTo(first.outboxCheckpoints()); + assertThat(retry.outboxSourceEvidence()).isEmpty(); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)).isEqualTo(pairRow); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)) + .isEqualTo(1L); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + } + + @Test + void strictExistingMembershipReadDeniesFreshAssociationWithoutEnrollmentOrMutation() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = importFreshTenantAssociation(tenantUuid); + long originalIssuanceFence = issuanceFence(account.accountUuid()); + + assertThatThrownBy( + () -> + readExistingPairBoundPositiveMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Fresh tenant membership has no positive current Account"); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + + // A separately established V38.1 sequence-zero pair remains non-admitting, and the strict + // existing-positive reader must neither promote it nor alter its counters. + readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + Map pairBeforeRead = + membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + long tenantGeneration = authorityGeneration("TENANT", null, tenantUuid); + assertThatThrownBy( + () -> + readExistingPairBoundPositiveMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Fresh tenant membership has no positive current Account"); + + Optional associationReadback = + new TransactionTemplate(transactionManager) + .execute(status -> freshAssociationRepository.read(tenantUuid)); + assertThat(associationReadback).contains(evidence); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)) + .isEqualTo(pairBeforeRead); + assertThat(authorityGeneration("TENANT", null, tenantUuid)).isEqualTo(tenantGeneration); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isEqualTo(1L); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)) + .isEqualTo(1L); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } + + @Test + void canonicalRuntimeReadUsesFreshUuidAssociationWithoutInventingRetainedAlias() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = importFreshTenantAssociation(tenantUuid); + long originalIssuanceFence = issuanceFence(account.accountUuid()); + + RuntimeMembershipSnapshotDto first = + readRuntimeMembershipSnapshot(account.accountUuid(), tenantUuid); + + assertThat(first.requestAccountUuid()).isEqualTo(account.accountUuid().toString()); + assertThat(first.requestTenantUuid()).isEqualTo(tenantUuid.toString()); + assertThat(first.accountUuid()).isEqualTo(account.accountUuid().toString()); + assertThat(first.tenantUuid()).isEqualTo(tenantUuid.toString()); + assertThat(first.membershipExists()).isFalse(); + assertThat(first.gameplayAdmissionAllowed()).isFalse(); + assertThat(first.membershipBaseline().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(first.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.authorityTuple().privateRealmGrantVersions()).isEmpty(); + assertThat(first.issuanceFence()).isEqualTo(Long.toString(originalIssuanceFence)); + assertThat(first.evaluatedAt()).isNotNull(); + assertThat(first.outboxCheckpoints()) + .containsExactlyElementsOf(expectedCheckpoints(account.accountUuid(), tenantUuid)); + assertThat(first.outboxSourceEvidence()).isEmpty(); + assertThat(first.sourceEvent()).isNull(); + assertThat(first.roles()).isEmpty(); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)) + .containsEntry("legacy_tenant_id", null) + .containsEntry("tenant_provenance_kind", "FRESH_GAME_DESIGN") + .containsEntry("tenant_source_operation_id", evidence.operationId()) + .containsEntry("tenant_provenance_digest", evidence.evidenceDigest()) + .containsEntry("membership_exists", false) + .containsEntry("membership_version", 1L) + .containsEntry("membership_authority_generation", 1L) + .containsEntry("last_event_sequence", 0L); + assertThat(countApprovedAssociationForCanonicalTenant(tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + + RuntimeMembershipSnapshotDto retry = + readRuntimeMembershipSnapshot(account.accountUuid(), tenantUuid); + assertThat(retry.requestAccountUuid()).isEqualTo(first.requestAccountUuid()); + assertThat(retry.requestTenantUuid()).isEqualTo(first.requestTenantUuid()); + assertThat(retry.membershipBaseline()).isEqualTo(first.membershipBaseline()); + assertThat(retry.authorityTuple()).isEqualTo(first.authorityTuple()); + assertThat(retry.issuanceFence()).isEqualTo(first.issuanceFence()); + assertThat(retry.outboxCheckpoints()).isEqualTo(first.outboxCheckpoints()); + assertThat(retry.outboxSourceEvidence()).isEmpty(); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isEqualTo(1L); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)) + .isEqualTo(1L); + } + + @Test + void canonicalRuntimeReadRejectsUnmappedTenantUuidWithoutEnrollment() { + AccountFixture account = accountFixture(); + UUID unmappedTenantUuid = UUID.randomUUID(); + + assertThatThrownBy( + () -> readRuntimeMembershipSnapshot(account.accountUuid(), unmappedTenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("approved Account tenant association is absent"); + assertThat(countMembershipPairAuthorities(account.accountUuid(), unmappedTenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), unmappedTenantUuid)) + .isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + } + + @Test + void freshUuidSnapshotRejectsUnmappedTenantWithoutEnrollment() { + AccountFixture account = accountFixture(); + UUID unmappedTenantUuid = UUID.randomUUID(); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), unmappedTenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is absent"); + assertThat(countMembershipPairAuthorities(account.accountUuid(), unmappedTenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), unmappedTenantUuid)) + .isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + } + + @Test + void freshUuidSnapshotRejectsPairProvenanceThatConflictsWithSourceReadback() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = importFreshTenantAssociation(tenantUuid); + dsl.execute( + "INSERT INTO account_membership_pair_authority " + + "(account_uuid, tenant_uuid, legacy_tenant_id, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, membership_exists, " + + "membership_version, membership_authority_generation, last_event_sequence, " + + "last_event_id, last_event_digest, last_transition_invalidated) " + + "VALUES (?, ?, NULL, 'FRESH_GAME_DESIGN', ?, ?, FALSE, 1, 1, 0, NULL, NULL, FALSE)", + account.accountUuid(), + tenantUuid, + UUID.randomUUID(), + evidence.evidenceDigest()); + Map conflictingPair = + membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with verified association provenance"); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)) + .isEqualTo(conflictingPair); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } + + @Test + void freshUuidSnapshotRollsBackGenerationAndPairWhenEnrollmentCompositionFails() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + AccountMembershipPairAuthorityRepository pairAuthorityTarget = + AopTestUtils.getUltimateTargetObject(pairAuthorityRepository); + doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException("simulated failure after pair enrollment"); + }) + .when(pairAuthorityTarget) + .enrollAbsence(eq(account.accountUuid()), eq(tenantUuid), any()); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulated failure after pair enrollment"); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } + + @Test + void freshUuidSnapshotRejectsCommittedMembershipHistoryBeforeBaselineEnrollment() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + String streamKey = membershipStreamKey(account.accountUuid(), tenantUuid); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + authorityOutboxRepository.append( + streamKey, + "fresh-history-" + UUID.randomUUID(), + UUID.randomUUID().toString(), + "sha256:" + "a".repeat(64), + "{}".getBytes(StandardCharsets.UTF_8))); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained authority-event history"); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(streamKey)).isEqualTo(1L); + assertThat(countAuthorityStreams(streamKey)).isEqualTo(1L); + } + + @Test + void freshUuidSnapshotRejectsAdvancedPairAndGenerationWithoutResettingEither() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + var original = readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + Map pairRow = membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + dsl.execute( + "UPDATE account_authority_generations SET generation = 2, source_version = 2 " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?", + account.accountUuid(), + tenantUuid); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "membership authority generation cannot prove its sequence-zero baseline"); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)).isEqualTo(pairRow); + assertThat(authorityGeneration("MEMBERSHIP", account.accountUuid(), tenantUuid)).isEqualTo(2L); + assertThat(countAuthorityEvents(original.outboxStreamKey())).isZero(); + + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_exists = TRUE, " + + "membership_version = 2, membership_authority_generation = 2, " + + "last_event_sequence = 1, last_event_id = ?, last_event_digest = ?, " + + "last_transition_invalidated = TRUE WHERE account_uuid = ? AND tenant_uuid = ?", + UUID.randomUUID().toString(), + "sha256:" + "b".repeat(64), + account.accountUuid(), + tenantUuid); + Map progressedPair = + membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)) + .isEqualTo(progressedPair); + assertThat(countAuthorityEvents(original.outboxStreamKey())).isZero(); + } + + @Test + void freshUuidSnapshotRejectsAdvancedTenantGenerationAndRollsBackBaselineWrites() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + dsl.execute( + "UPDATE account_authority_generations SET generation = 2, source_version = 2 " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantUuid); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "tenant authority generation cannot prove its sequence-zero baseline"); + assertThat(authorityGeneration("TENANT", null, tenantUuid)).isEqualTo(2L); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } + + @Test + void concurrentFreshUuidSnapshotCallsInitializeOneExactPairBaseline() throws Exception { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch firstSnapshotReady = new CountDownLatch(1); + CountDownLatch releaseFirstSnapshot = new CountDownLatch(1); + CountDownLatch secondLockAttempted = new CountDownLatch(1); + AtomicReference firstBackendPid = new AtomicReference<>(); + AtomicReference secondBackendPid = new AtomicReference<>(); + AtomicInteger lockInvocations = new AtomicInteger(); + doAnswer( + invocation -> { + if (lockInvocations.incrementAndGet() == 2) { + secondBackendPid.set(currentBackendPid()); + secondLockAttempted.countDown(); + } + return invocation.callRealMethod(); + }) + .when(joinOperationRepository) + .lockAccount(anyLong()); + try { + Future first = + executor.submit( + () -> + new TransactionTemplate(transactionManager) + .execute( + status -> { + var snapshot = + producer.readFreshNeverJoinedMembershipSnapshot( + account.accountUuid(), tenantUuid); + firstBackendPid.set(currentBackendPid()); + firstSnapshotReady.countDown(); + await(releaseFirstSnapshot); + return snapshot; + })); + assertThat(firstSnapshotReady.await(10, TimeUnit.SECONDS)).isTrue(); + + Future second = + executor.submit( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)); + assertThat(secondLockAttempted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitAccountFenceLockWait(firstBackendPid.get(), secondBackendPid.get()); + assertThat(second.isDone()).isFalse(); + + releaseFirstSnapshot.countDown(); + var firstSnapshot = first.get(20, TimeUnit.SECONDS); + var secondSnapshot = second.get(20, TimeUnit.SECONDS); + assertThat(firstSnapshot.membershipVersion()).isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(secondSnapshot.membershipVersion()).isEqualTo(firstSnapshot.membershipVersion()); + assertThat(secondSnapshot.authorityTuple()).isEqualTo(firstSnapshot.authorityTuple()); + assertThat(secondSnapshot.outboxCheckpoints()).isEqualTo(firstSnapshot.outboxCheckpoints()); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isEqualTo(1L); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)) + .isEqualTo(1L); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } catch (ExecutionException exception) { + throw new AssertionError("Concurrent fresh snapshot read failed", exception.getCause()); + } finally { + releaseFirstSnapshot.countDown(); + executor.shutdownNow(); + } + } + + private AccountFixture accountFixture() { + String suffix = UUID.randomUUID().toString().replace("-", ""); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING id", + "fresh-snapshot-" + suffix, + "fresh-snapshot-" + suffix + "@example.com", + "test-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 1, 1)", + accountUuid); + dsl.execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + accountUuid); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + authorityGenerationRepository.initializeIssuerIfAbsent( + AccountServiceImpl.ACCOUNT_JWT_ISSUER)); + return new AccountFixture(accountId, accountUuid); + } + + private FreshTenantCreationEvidence importFreshTenantAssociation(UUID canonicalTenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String targetNamespace = "firemud-unit1b"; + String sourceGameTenantKey = + "fresh-" + UUID.randomUUID().toString().replace("-", "").substring(0, 20); + String requestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, creationRequestId, sourceGameTenantKey, "Fresh tenant", null); + long sourceGameRowId = positiveRandomLong(); + String provenanceKind = "NEW_GAME_ROW"; + FreshTenantCreationEvidence evidence = + new FreshTenantCreationEvidence( + 1, + targetNamespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> { + freshAssociationRepository.importVerified(evidence); + authorityGenerationRepository.initializeTenantIfAbsent(canonicalTenantUuid); + }); + return evidence; + } + + private AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot + readFreshNeverJoinedMembershipSnapshot(UUID accountUuid, UUID tenantUuid) { + return new TransactionTemplate(transactionManager) + .execute( + status -> producer.readFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid)); + } + + private RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( + UUID accountUuid, UUID tenantUuid) { + return new TransactionTemplate(transactionManager) + .execute(status -> producer.readRuntimeMembershipSnapshot(accountUuid, tenantUuid)); + } + + private AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot + readExistingPairBoundPositiveMembershipSnapshot(UUID accountUuid, UUID tenantUuid) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + producer.readExistingPairBoundPositiveMembershipSnapshot(accountUuid, tenantUuid)); + } + + private Map membershipPairAuthorityRow(UUID accountUuid, UUID tenantUuid) { + var row = + dsl.resultQuery( + "SELECT xmin::text AS row_xmin, * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private long countMembershipPairAuthorities(UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long countMembershipAuthorityGenerations(UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? " + + "AND tenant_uuid = ?", + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long authorityGeneration(String scopeKind, UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = ? AND account_uuid IS NOT DISTINCT FROM ? " + + "AND tenant_uuid IS NOT DISTINCT FROM ?", + scopeKind, + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long issuanceFence(UUID accountUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class)); + } + + private long countMembershipsForAccount(long accountId) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", accountId) + .fetchOne(0, Long.class)); + } + + private long countMembershipTransitionReceiptsForAccount(long accountId) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts WHERE account_id = ?", + accountId) + .fetchOne(0, Long.class)); + } + + private long countAuthorityEvents(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)); + } + + private long countAuthorityStreams(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)); + } + + private long countFreshCanonicalClaim(UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_canonical_tenant_identity_claims " + + "WHERE canonical_tenant_id = ? AND identity_kind = 'FRESH_GAME_DESIGN'", + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long countApprovedAssociationForCanonicalTenant(UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_approved_legacy_tenant_associations " + + "WHERE canonical_tenant_id = ?", + tenantUuid) + .fetchOne(0, Long.class)); + } + + private String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private List expectedCheckpoints(UUID accountUuid, UUID tenantUuid) { + return List.of( + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountUuid, "0"), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "issuer/" + + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + "0"), + new OutboxCheckpointEntry(membershipStreamKey(accountUuid, tenantUuid), "0"), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid, "0")); + } + + private long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; + } + + private Integer currentBackendPid() { + return dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class); + } + + private void awaitAccountFenceLockWait(Integer snapshotBackendPid, Integer waitingBackendPid) + throws InterruptedException { + assertThat(snapshotBackendPid).isNotNull(); + assertThat(waitingBackendPid).isNotNull(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + Boolean blockedBySnapshot = + dsl.resultQuery( + "SELECT CAST(? AS integer) = ANY(pg_blocking_pids(CAST(? AS integer)))", + snapshotBackendPid, + waitingBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blockedBySnapshot)) { + return; + } + Thread.sleep(10); + } + throw new AssertionError( + "second fresh snapshot transaction did not block on the Account-row fence"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(60, TimeUnit.SECONDS)) { + throw new IllegalStateException("fresh snapshot concurrency test timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("fresh snapshot concurrency test was interrupted", exception); + } + } + + private record AccountFixture(long accountId, UUID accountUuid) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index a33640ab5a..1a68601c19 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -80,9 +80,10 @@ GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, - "firemud.grpc.workload-namespace=account_service" + "firemud.grpc.workload-namespace=" + AccountJoinPostgresIntegrationTest.WORKLOAD_NAMESPACE }) class AccountJoinPostgresIntegrationTest { + static final String WORKLOAD_NAMESPACE = "account-service-test"; private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); private static final String WORLD_SLUG = "join-proof-world"; private static final String REALM_SLUG = "production"; @@ -948,6 +949,37 @@ void positiveMembershipSnapshotReturnsExactCommittedAuthorityEvidence() { snapshot.authorityEvent().canonicalJson())); } + @Test + void canonicalExistingPairBoundPositiveMembershipSnapshotRepeatsWithoutMutation() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + Map before = membershipAuthorityReadEvidenceSnapshot(fixture); + + var first = readExistingPairBoundPositiveMembershipSnapshot(fixture); + var second = readExistingPairBoundPositiveMembershipSnapshot(fixture); + + assertThat(joined.success()).isTrue(); + assertThat(first.membershipExists()).isTrue(); + assertThat(first.gameplayAdmissionAllowed()).isTrue(); + assertThat(first.accountId()).isEqualTo(fixture.accountUuid().toString()); + assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(first.membershipVersion()).isEqualTo(second.membershipVersion()); + assertThat(first.membershipAuthorityGeneration()) + .isEqualTo(second.membershipAuthorityGeneration()); + assertThat(first.roles()).containsExactly("player"); + assertThat(second.authorityTuple()).isEqualTo(first.authorityTuple()); + assertThat(second.issuanceFence()).isEqualTo(first.issuanceFence()); + assertThat(second.outboxCheckpoints()).isEqualTo(first.outboxCheckpoints()); + assertThat(second.outboxSourceEvidence()).isEqualTo(first.outboxSourceEvidence()); + assertThat(second.transitionReceipt()).isEqualTo(first.transitionReceipt()); + assertThat(second.authorityEvent().eventId()).isEqualTo(first.authorityEvent().eventId()); + assertThat(second.authorityEvent().eventDigest()) + .isEqualTo(first.authorityEvent().eventDigest()); + assertThat(second.authorityEvent().canonicalJsonUtf8()) + .containsExactly(first.authorityEvent().canonicalJsonUtf8()); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture)).isEqualTo(before); + } + @Test void positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps() { JoinFixture scalarVersion = fixture("active"); @@ -970,9 +1002,14 @@ void positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps() { @Test void positiveMembershipSnapshotFailsClosedForAbsentMembershipOrReceipt() { JoinFixture absent = fixture("active"); + Map absentBeforeRead = membershipAuthorityReadEvidenceSnapshot(absent); assertThatThrownBy(() -> readPositiveMembershipSnapshot(absent)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Current Account membership row is absent"); + assertThatThrownBy(() -> readExistingPairBoundPositiveMembershipSnapshot(absent)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account membership row is absent"); + assertThat(membershipAuthorityReadEvidenceSnapshot(absent)).isEqualTo(absentBeforeRead); JoinFixture missingReceipt = fixture("active"); dsl.execute( @@ -1035,6 +1072,13 @@ void positiveMembershipSnapshotFailsClosedForMismatchedAuthorityTuple() { assertThatThrownBy(() -> readPositiveMembershipSnapshot(mismatchedTuple)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("differs from its V31 authority generation"); + Map mismatchedBeforeStrictRead = + membershipAuthorityReadEvidenceSnapshot(mismatchedTuple); + assertThatThrownBy(() -> readExistingPairBoundPositiveMembershipSnapshot(mismatchedTuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from its V31 authority generation"); + assertThat(membershipAuthorityReadEvidenceSnapshot(mismatchedTuple)) + .isEqualTo(mismatchedBeforeStrictRead); } @Test @@ -1166,8 +1210,8 @@ void runtimeMembershipSnapshotKeepsAbsenceAndFirstJoinEvidenceInOneFencedResult( var absent = readRuntimeMembershipSnapshot(fixture); Map baselineRow = membershipPairAuthorityRow(fixture); - assertThat(absent.requestAccountId()).isEqualTo(fixture.accountId()); - assertThat(absent.requestTenantId()).isEqualTo(fixture.tenantId()); + assertThat(absent.requestAccountUuid()).isEqualTo(fixture.accountUuid().toString()); + assertThat(absent.requestTenantUuid()).isEqualTo(fixture.tenantUuid().toString()); assertThat(absent.accountUuid()).isEqualTo(fixture.accountUuid().toString()); assertThat(absent.tenantUuid()).isEqualTo(fixture.tenantUuid().toString()); assertThat(absent.membershipExists()).isFalse(); @@ -1258,6 +1302,13 @@ void runtimeMembershipSnapshotRejectsContradictoryGeneration() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining( "Absent Account membership differs from its durable pair authority baseline"); + Map beforeStrictRead = + membershipAuthorityReadEvidenceSnapshot(contradictoryPair); + assertThatThrownBy(() -> readExistingPairBoundPositiveMembershipSnapshot(contradictoryPair)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account membership row is absent"); + assertThat(membershipAuthorityReadEvidenceSnapshot(contradictoryPair)) + .isEqualTo(beforeStrictRead); } @Test @@ -1347,7 +1398,7 @@ void concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot() t status -> { capturedSnapshot.set( membershipAuthorityEventProducer.readRuntimeMembershipSnapshot( - fixture.accountId(), fixture.tenantId())); + fixture.accountUuid(), fixture.tenantUuid())); snapshotBackendPid.set( dsl.resultQuery("SELECT pg_backend_pid()") .fetchOne(0, Integer.class)); @@ -1405,8 +1456,8 @@ void concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot() t RuntimeMembershipSnapshotDto absent = capturedSnapshot.get(); assertThat(absent).isNotNull(); - assertThat(absent.requestAccountId()).isEqualTo(fixture.accountId()); - assertThat(absent.requestTenantId()).isEqualTo(fixture.tenantId()); + assertThat(absent.requestAccountUuid()).isEqualTo(fixture.accountUuid().toString()); + assertThat(absent.requestTenantUuid()).isEqualTo(fixture.tenantUuid().toString()); assertThat(absent.accountUuid()).isEqualTo(fixture.accountUuid().toString()); assertThat(absent.tenantUuid()).isEqualTo(fixture.tenantUuid().toString()); assertThat(absent.membershipExists()).isFalse(); @@ -1537,10 +1588,16 @@ void runtimeMembershipSnapshotRejectsInactiveMembershipWithoutChangingAuthority( "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + "gameplay_admission_allowed = FALSE WHERE id = ?", joined.membershipId()); + Map inactiveBeforeStrictRead = membershipAuthorityReadEvidenceSnapshot(fixture); assertThatThrownBy(() -> readRuntimeMembershipSnapshot(fixture)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not a positive active explicit membership"); + assertThatThrownBy(() -> readExistingPairBoundPositiveMembershipSnapshot(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a positive active explicit membership"); + assertThat(membershipAuthorityReadEvidenceSnapshot(fixture)) + .isEqualTo(inactiveBeforeStrictRead); assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairRow); assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) .isEqualTo(membershipGeneration); @@ -1635,7 +1692,7 @@ private void prepareRuntimeSnapshotAuthority(JoinFixture fixture) { .execute( status -> membershipAuthorityEventProducer.readRuntimeMembershipSnapshot( - fixture.accountId(), fixture.tenantId())); + fixture.accountUuid(), fixture.tenantUuid())); } private AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot @@ -1647,6 +1704,124 @@ private void prepareRuntimeSnapshotAuthority(JoinFixture fixture) { fixture.accountId(), fixture.tenantId())); } + private AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot + readExistingPairBoundPositiveMembershipSnapshot(JoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readExistingPairBoundPositiveMembershipSnapshot( + fixture.accountUuid(), fixture.tenantUuid())); + } + + private Map membershipAuthorityReadEvidenceSnapshot(JoinFixture fixture) { + String streamKey = authorityStreamKey(fixture); + Map snapshot = new LinkedHashMap<>(); + snapshot.put( + "account", + dsl.fetch( + "SELECT xmin::text AS row_xmin, a.* FROM accounts a WHERE a.id = ?", + fixture.accountId()) + .intoMaps()); + snapshot.put( + "membership", + dsl.fetch( + "SELECT xmin::text AS row_xmin, m.* FROM account_tenant_membership m " + + "WHERE m.account_id = ? AND m.tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .intoMaps()); + snapshot.put( + "pairAuthority", + dsl.fetch( + "SELECT xmin::text AS row_xmin, p.* FROM account_membership_pair_authority p " + + "WHERE p.account_uuid = ? AND p.tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .intoMaps()); + snapshot.put( + "roleSnapshots", + dsl.fetch( + "SELECT xmin::text AS row_xmin, s.* " + + "FROM account_tenant_membership_role_snapshots s " + + "WHERE s.membership_id = (SELECT id FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?)", + fixture.accountId(), + fixture.tenantId()) + .intoMaps()); + snapshot.put( + "roleSnapshotRoles", + dsl.fetch( + "SELECT xmin::text AS row_xmin, r.* " + + "FROM account_tenant_membership_role_snapshot_roles r " + + "WHERE r.membership_id = (SELECT id FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?)", + fixture.accountId(), + fixture.tenantId()) + .intoMaps()); + snapshot.put( + "transitionReceipts", + dsl.fetch( + "SELECT xmin::text AS row_xmin, r.* " + + "FROM account_membership_transition_receipts r " + + "WHERE r.account_id = ? AND r.tenant_id = ? ORDER BY r.receipt_sequence", + fixture.accountId(), + fixture.tenantId()) + .intoMaps()); + snapshot.put( + "transitionReceiptStreamHead", + dsl.fetch( + "SELECT xmin::text AS row_xmin, h.* " + + "FROM account_membership_transition_receipt_stream_heads h " + + "WHERE h.account_id = ? AND h.tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .intoMaps()); + snapshot.put( + "authorityGenerations", + dsl.fetch( + "SELECT xmin::text AS row_xmin, g.* FROM account_authority_generations g " + + "WHERE (g.scope_kind = 'ACCOUNT' AND g.account_uuid = ?) " + + "OR (g.scope_kind = 'TENANT' AND g.tenant_uuid = ?) " + + "OR (g.scope_kind = 'MEMBERSHIP' AND g.account_uuid = ? " + + "AND g.tenant_uuid = ?) ORDER BY g.scope_kind", + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.accountUuid(), + fixture.tenantUuid()) + .intoMaps()); + snapshot.put( + "issuanceFence", + dsl.fetch( + "SELECT xmin::text AS row_xmin, f.* " + + "FROM account_authority_issuance_fences f WHERE f.account_uuid = ?", + fixture.accountUuid()) + .intoMaps()); + snapshot.put( + "authorityOutboxStream", + dsl.fetch( + "SELECT xmin::text AS row_xmin, s.* FROM account_authority_outbox_streams s " + + "WHERE s.outbox_stream_key = ?", + streamKey) + .intoMaps()); + snapshot.put( + "authorityOutboxEvents", + dsl.fetch( + "SELECT xmin::text AS row_xmin, e.outbox_stream_key, e.outbox_sequence, " + + "e.request_id, e.event_id, e.event_digest, encode(e.payload, 'hex') " + + "AS payload_hex, e.created_at FROM account_authority_outbox_events e " + + "WHERE e.outbox_stream_key = ? ORDER BY e.outbox_sequence", + streamKey) + .intoMaps()); + snapshot.put( + "joinOperation", + dsl.fetch( + "SELECT xmin::text AS row_xmin, o.* FROM account_join_operations o " + + "WHERE o.request_id = ?", + fixture.requestId()) + .intoMaps()); + return Map.copyOf(snapshot); + } + private Map membershipPairAuthorityRow(JoinFixture fixture) { var row = dsl.resultQuery( @@ -1901,7 +2076,7 @@ private ResolveLegacyAccountTenantAssociationResponse approvedTenantAssociation( .setOperationId(UUID.randomUUID().toString()) .setManifestDigest("sha256:" + "b".repeat(64)) .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) - .setTargetNamespace("account_service") + .setTargetNamespace(WORKLOAD_NAMESPACE) .setSignerKeyId("game-design-owner-test") .setApprovedBy("owner@example.test") .setApprovalReference("unit-1b-postgres-fixture") diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepositoryIntegrationTest.java index e00fb4591f..1cd9db0072 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepositoryIntegrationTest.java @@ -760,7 +760,7 @@ private long insertAccount(DSLContext dsl) { private AccountConnectTokenIssuanceIdentity newIdentity(long accountId) { return new AccountConnectTokenIssuanceIdentity( accountId, - 77L, + UUID.randomUUID(), "opaque-connect-scope-" + UUID.randomUUID(), "request-" + UUID.randomUUID()); } @@ -772,7 +772,7 @@ private AccountEnvelopeBinding binding( operationId.toString(), identity.requestId(), Long.toString(identity.accountId()), - Long.toString(identity.tenantId()), + identity.tenantId().toString(), identity.connectScopeId(), null, requestDigest, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java index 5e1f247fed..eb2d0a61f1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java @@ -4,7 +4,9 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Map; +import java.util.Objects; import java.util.UUID; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; @@ -12,6 +14,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -27,14 +30,14 @@ @Testcontainers(disabledWithoutDocker = true) class AccountMembershipPairAuthorityRepositoryIntegrationTest { - private static final String SCHEMA = "account_membership_pair_authority_proof"; + private static final String SCHEMA_PREFIX = "pair_authority_proof_"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @Test void immutableValueTypesRejectContradictoryAuthorityEvidence() { - VerifiedTenantProvenance provenance = provenance(701L, TenantProvenanceKind.FRESH_GAME_DESIGN); + VerifiedTenantProvenance provenance = provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN); UUID accountUuid = UUID.randomUUID(); UUID tenantUuid = UUID.randomUUID(); @@ -61,23 +64,283 @@ void immutableValueTypesRejectContradictoryAuthorityEvidence() { assertThatThrownBy( () -> new VerifiedTenantProvenance( - 701L, + null, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), "SHA256:" + "a".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical lowercase SHA-256"); + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + 701L, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), digest(1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not carry a legacy"); + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + null, TenantProvenanceKind.APPROVED_RETAINED, UUID.randomUUID(), digest(1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive legacy tenant ID"); assertThatThrownBy(() -> new ProvenPositiveCheckpoint(1L, 1L, 0L, "event", digest(1), false)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("incomplete"); } @Test - void enrollmentAndTransitionsPreserveExactPositiveAuthorityAndProvenance() { + void freshPairsUseUuidIdentityWithoutLegacyAliasesAndRequireTheOwnerTransaction() { + TestContext context = newTestContext(); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID firstTenantUuid = UUID.randomUUID(); + UUID secondTenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance firstFresh = provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN); + VerifiedTenantProvenance secondFresh = provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN); + + assertThatThrownBy(() -> context.repository().readForUpdate(accountUuid, firstTenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + + PairAuthority first = + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, firstTenantUuid, firstFresh)); + PairAuthority second = + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, secondTenantUuid, secondFresh)); + assertThat(first.provenance().legacyTenantId()).isNull(); + assertThat(second.provenance().legacyTenantId()).isNull(); + assertThat( + Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT count(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? " + + "AND tenant_provenance_kind = 'FRESH_GAME_DESIGN' " + + "AND legacy_tenant_id IS NULL", + accountUuid), + "Fresh pair count query must return a row") + .get(0, Long.class)) + .isEqualTo(2L); + + VerifiedTenantProvenance retained = provenance(705L, TenantProvenanceKind.APPROVED_RETAINED); + UUID retainedTenantUuid = UUID.randomUUID(); + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, retainedTenantUuid, retained)); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(705L, TenantProvenanceKind.APPROVED_RETAINED)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with an existing pair authority"); + + UUID rolledBackTenantUuid = UUID.randomUUID(); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> { + context + .repository() + .enrollAbsence(accountUuid, rolledBackTenantUuid, firstFresh); + throw new IllegalStateException("rollback pair enrollment"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("rollback pair enrollment"); + assertThat( + Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT count(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + rolledBackTenantUuid), + "Rolled-back pair count query must return a row") + .get(0, Long.class)) + .isZero(); + } + + @Test + void databaseRejectsRetainedNullAndFreshNumericLegacyKeys() { TestContext context = newTestContext(); UUID accountUuid = insertAccount(context.setupDsl()); + + assertThatThrownBy( + () -> + insertPair( + context.setupDsl(), + accountUuid, + UUID.randomUUID(), + null, + TenantProvenanceKind.APPROVED_RETAINED)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertPair( + context.setupDsl(), + accountUuid, + UUID.randomUUID(), + 706L, + TenantProvenanceKind.FRESH_GAME_DESIGN)) + .isInstanceOf(DataAccessException.class); + } + + @Test + void v39PreservesRetainedPairHistoryAndEnforcesUuidOnlyFreshRows() { + TestContext context = newTestContext(newSchema(), "38"); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID retainedTenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance retained = provenance(707L, TenantProvenanceKind.APPROVED_RETAINED); + insertPair( + context.setupDsl(), + accountUuid, + retainedTenantUuid, + retained.legacyTenantId(), + retained.kind(), + retained.sourceOperationId(), + retained.digest()); + org.jooq.Record retainedBefore = + context + .setupDsl() + .fetchOne( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + retainedTenantUuid); + + UUID advancedTenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance advancedRetained = + provenance(709L, TenantProvenanceKind.APPROVED_RETAINED); + ProvenPositiveCheckpoint advancedCheckpoint = + new ProvenPositiveCheckpoint(8L, 3L, 11L, "retained-event-11", digest(9), true); + PairAuthority advancedAuthority = + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollProvenPositive( + accountUuid, advancedTenantUuid, advancedRetained, advancedCheckpoint)); + org.jooq.Record advancedBefore = + context + .setupDsl() + .fetchOne( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + advancedTenantUuid); + + flyway(context.dataSource(), context.schema(), null).migrate(); + org.jooq.Record retainedAfter = + context + .setupDsl() + .fetchOne( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + retainedTenantUuid); + org.jooq.Record advancedAfter = + context + .setupDsl() + .fetchOne( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + advancedTenantUuid); + assertThat(retainedAfter).isEqualTo(retainedBefore); + assertThat(advancedAfter).isEqualTo(advancedBefore); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, retainedTenantUuid))) + .contains( + new PairAuthority( + accountUuid, retainedTenantUuid, retained, false, 1L, 1L, 0L, null, null, false)); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, advancedTenantUuid))) + .contains(advancedAuthority); + + PairAuthority firstFresh = + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN))); + PairAuthority secondFresh = + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN))); + assertThat(firstFresh.tenantUuid()).isNotEqualTo(secondFresh.tenantUuid()); + assertThat(firstFresh.provenance().legacyTenantId()).isNull(); + assertThat(secondFresh.provenance().legacyTenantId()).isNull(); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(707L, TenantProvenanceKind.APPROVED_RETAINED)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with an existing pair authority"); + } + + @Test + void v39RefusesToRewriteAnExistingFreshNumericPair() { + TestContext context = newTestContext(newSchema(), "38"); + UUID accountUuid = insertAccount(context.setupDsl()); UUID tenantUuid = UUID.randomUUID(); - VerifiedTenantProvenance fresh = provenance(702L, TenantProvenanceKind.FRESH_GAME_DESIGN); + insertPair( + context.setupDsl(), accountUuid, tenantUuid, 708L, TenantProvenanceKind.FRESH_GAME_DESIGN); + + assertThatThrownBy(() -> flyway(context.dataSource(), context.schema(), null).migrate()) + .isInstanceOf(FlywayException.class); + assertThat( + Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT legacy_tenant_id FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid), + "Rejected migration must leave the existing pair row") + .get(0, Long.class)) + .isEqualTo(708L); + } + + @Test + void enrollmentAndTransitionsPreserveExactAuthorityAndProvenance() { + TestContext context = newTestContext(); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID tenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance fresh = provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN); PairAuthority baseline = inTransaction( @@ -192,7 +455,7 @@ void enrollmentAndTransitionsPreserveExactPositiveAuthorityAndProvenance() { VerifiedTenantProvenance wrongProvenance = new VerifiedTenantProvenance( - 702L, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), digest(4)); + null, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), digest(4)); assertThatThrownBy( () -> inTransaction( @@ -203,20 +466,6 @@ void enrollmentAndTransitionsPreserveExactPositiveAuthorityAndProvenance() { .enrollAbsence(accountUuid, tenantUuid, wrongProvenance))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts with verified association provenance"); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> - context - .repository() - .enrollAbsence( - accountUuid, - UUID.randomUUID(), - provenance(702L, TenantProvenanceKind.FRESH_GAME_DESIGN)))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("conflicts with an existing pair authority"); - assertThatThrownBy( () -> inTransaction( @@ -335,7 +584,7 @@ void positiveRetainedEnrollmentUsesSuppliedCountersAndRejectsSeqZeroOrChangedEvi .enrollProvenPositive( accountUuid, tenantUuid, - provenance(703L, TenantProvenanceKind.FRESH_GAME_DESIGN), + provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN), checkpoint))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("approved retained tenant provenance"); @@ -375,29 +624,47 @@ void databaseRejectsPositiveSequenceWithoutEventDigest() { } private TestContext newTestContext() { + return newTestContext(newSchema(), null); + } + + private TestContext newTestContext(String schema, String targetVersion) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); - String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; - dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + SCHEMA); + dataSource.setUrl(postgres.getJdbcUrl()); 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") - .load() - .migrate(); + dataSource.setSchema(schema); + flyway(dataSource, schema, targetVersion).migrate(); DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + assertThat(setupDsl.fetchOne("SELECT current_schema()").get(0, String.class)).isEqualTo(schema); DSLContext transactionDsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); return new TestContext( + schema, + dataSource, setupDsl, new AccountMembershipPairAuthorityRepository(transactionDsl), new TransactionTemplate(new DataSourceTransactionManager(dataSource))); } + private String newSchema() { + return SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + } + + private Flyway flyway(DataSource dataSource, String schema, String targetVersion) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + configuration.target(targetVersion); + } + return configuration.load(); + } + private UUID insertAccount(DSLContext dsl) { String unique = UUID.randomUUID().toString().replace("-", ""); return dsl.resultQuery( @@ -409,10 +676,42 @@ private UUID insertAccount(DSLContext dsl) { .fetchOne(0, UUID.class); } - private VerifiedTenantProvenance provenance(long legacyTenantId, TenantProvenanceKind kind) { + private VerifiedTenantProvenance provenance(Long legacyTenantId, TenantProvenanceKind kind) { return new VerifiedTenantProvenance(legacyTenantId, kind, UUID.randomUUID(), digest(1)); } + private void insertPair( + DSLContext dsl, + UUID accountUuid, + UUID tenantUuid, + Long legacyTenantId, + TenantProvenanceKind kind) { + insertPair(dsl, accountUuid, tenantUuid, legacyTenantId, kind, UUID.randomUUID(), digest(1)); + } + + private void insertPair( + DSLContext dsl, + UUID accountUuid, + UUID tenantUuid, + Long legacyTenantId, + TenantProvenanceKind kind, + UUID sourceOperationId, + String evidenceDigest) { + dsl.execute( + "INSERT INTO account_membership_pair_authority " + + "(account_uuid, tenant_uuid, legacy_tenant_id, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, membership_exists, " + + "membership_version, membership_authority_generation, last_event_sequence, " + + "last_event_id, last_event_digest, last_transition_invalidated) " + + "VALUES (?, ?, ?, ?, ?, ?, FALSE, 1, 1, 0, NULL, NULL, FALSE)", + accountUuid, + tenantUuid, + legacyTenantId, + kind.name(), + sourceOperationId, + evidenceDigest); + } + private String digest(int digit) { return "sha256:" + Integer.toString(digit).repeat(64); } @@ -423,6 +722,8 @@ private T inTransaction( } private record TestContext( + String schema, + DataSource dataSource, DSLContext setupDsl, AccountMembershipPairAuthorityRepository repository, TransactionTemplate transaction) {} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationIntegrationTest.java new file mode 100644 index 0000000000..5c694556bd --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationIntegrationTest.java @@ -0,0 +1,628 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.time.Duration; +import java.util.Base64; +import java.util.Map; +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.accountservice.client.GameDesignFreshTenantIdentityClient; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.FreshTenantIdentityEnrollmentService; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.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; + +/** + * PostgreSQL-only Account persistence proof. The Game Design client is mocked here: these cases + * prove local association, claim, and transaction behavior, not authenticated mTLS owner evidence. + */ +@Testcontainers(disabledWithoutDocker = true) +class FreshTenantIdentityAssociationIntegrationTest { + private static final String TEST_NAMESPACE = "account-service"; + private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64); + private static final UUID RETAINED_OPERATION_ID = + UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID RETAINED_UUID = UUID.fromString("88888888-8888-4888-8888-888888888888"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void exactRetryReadbackGenerationInitializationAndImmutabilityStayAccountLocal() { + Fixture fixture = fixture(false); + FreshTenantCreationEvidence evidence = + evidence( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + REQUEST_DIGEST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 117L, + "new-game-tenant-117"); + FreshTenantIdentityEnrollmentService service = service(fixture, evidence); + + assertThatThrownBy(() -> fixture.repository().importVerified(evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy(() -> fixture.repository().read(evidence.canonicalTenantId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThat( + inTransaction( + fixture.transaction(), () -> fixture.repository().read(UUID.randomUUID()))) + .isEmpty(); + + assertThat(service.enroll(evidence.creationRequestId(), evidence.requestDigest())) + .isEqualTo(evidence); + assertThat(service.enroll(evidence.creationRequestId(), evidence.requestDigest())) + .isEqualTo(evidence); + assertThat(count(fixture.setupDsl(), "account_fresh_tenant_identity_associations")) + .isEqualTo(1L); + assertThat(count(fixture.setupDsl(), "account_canonical_tenant_identity_claims")).isEqualTo(1L); + + ScopeState tenantState = + inTransaction( + fixture.transaction(), + () -> fixture.generations().read(AuthorityScope.tenant(evidence.canonicalTenantId()))); + assertThat(tenantState.generation()).isEqualTo(1L); + assertThat(tenantState.sourceVersion()).isEqualTo(1L); + ScopeState advanced = + inTransaction( + fixture.transaction(), () -> fixture.generations().advance(tenantState, null)); + assertThat(advanced.generation()).isEqualTo(2L); + assertThat(service.enroll(evidence.creationRequestId(), evidence.requestDigest())) + .isEqualTo(evidence); + assertThat( + inTransaction( + fixture.transaction(), + () -> + fixture + .generations() + .read(AuthorityScope.tenant(evidence.canonicalTenantId())))) + .isEqualTo(advanced); + + assertNoMembershipOrAdmissionSideEffects(fixture.setupDsl()); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_fresh_tenant_identity_associations " + + "SET request_digest = ? WHERE canonical_tenant_id = ?", + "sha256:" + "f".repeat(64), + evidence.canonicalTenantId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_canonical_tenant_identity_claims " + + "WHERE canonical_tenant_id = ?", + evidence.canonicalTenantId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("immutable"); + assertThatThrownBy( + () -> fixture.setupDsl().execute("TRUNCATE account_fresh_tenant_identity_associations")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("immutable"); + } + + @Test + void changedRequestOperationOrUuidCannotMutateAnExistingAssociation() { + Fixture fixture = fixture(false); + FreshTenantCreationEvidence original = + evidence( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + REQUEST_DIGEST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 117L, + "new-game-tenant-117"); + inTransaction(fixture.transaction(), () -> fixture.repository().importVerified(original)); + + FreshTenantCreationEvidence changedRequest = + evidence( + original.creationRequestId(), + "sha256:" + "b".repeat(64), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + UUID.fromString("55555555-5555-4555-8555-555555555555"), + 118L, + "different-game-tenant"); + FreshTenantCreationEvidence changedOperation = + evidence( + UUID.fromString("66666666-6666-4666-8666-666666666666"), + REQUEST_DIGEST, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + original.canonicalTenantId(), + 119L, + "another-game-tenant"); + FreshTenantCreationEvidence changedUuid = + evidence( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + REQUEST_DIGEST, + original.operationId(), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + 120L, + "third-game-tenant"); + FreshTenantCreationEvidence changedSource = + evidence( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + REQUEST_DIGEST, + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + original.sourceGameRowId(), + original.sourceGameTenantKey()); + + assertThatThrownBy( + () -> + inTransaction( + fixture.transaction(), + () -> fixture.repository().importVerified(changedRequest))) + .isInstanceOf( + FreshTenantIdentityAssociationRepository.IdentityAssociationConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + fixture.transaction(), + () -> fixture.repository().importVerified(changedOperation))) + .isInstanceOf( + FreshTenantIdentityAssociationRepository.IdentityAssociationConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + fixture.transaction(), () -> fixture.repository().importVerified(changedUuid))) + .isInstanceOf( + FreshTenantIdentityAssociationRepository.IdentityAssociationConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + fixture.transaction(), + () -> fixture.repository().importVerified(changedSource))) + .isInstanceOf( + FreshTenantIdentityAssociationRepository.IdentityAssociationConflictException.class); + + assertThat( + inTransaction( + fixture.transaction(), + () -> fixture.repository().read(original.canonicalTenantId()))) + .contains(original); + assertThat(count(fixture.setupDsl(), "account_fresh_tenant_identity_associations")) + .isEqualTo(1L); + assertThat(count(fixture.setupDsl(), "account_canonical_tenant_identity_claims")).isEqualTo(1L); + } + + @Test + void generationFailureRollsBackFreshAssociationAndCanonicalClaim() { + Fixture fixture = fixture(false); + FreshTenantCreationEvidence evidence = + evidence( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + REQUEST_DIGEST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 117L, + "new-game-tenant-117"); + GameDesignFreshTenantIdentityClient client = mock(GameDesignFreshTenantIdentityClient.class); + when(client.resolveCreation(evidence.creationRequestId(), evidence.requestDigest())) + .thenReturn(evidence); + AccountAuthorityGenerationRepository failingGenerationRepository = + mock(AccountAuthorityGenerationRepository.class); + doThrow(new IllegalStateException("generation enrollment failure")) + .when(failingGenerationRepository) + .initializeTenantIfAbsent(evidence.canonicalTenantId()); + FreshTenantIdentityEnrollmentService service = + new FreshTenantIdentityEnrollmentService( + client, fixture.repository(), failingGenerationRepository, fixture.transaction()); + + assertThatThrownBy(() -> service.enroll(evidence.creationRequestId(), evidence.requestDigest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("generation enrollment failure"); + + assertThat( + inTransaction( + fixture.transaction(), + () -> fixture.repository().read(evidence.canonicalTenantId()))) + .isEmpty(); + assertThat(count(fixture.setupDsl(), "account_fresh_tenant_identity_associations")).isZero(); + assertThat(count(fixture.setupDsl(), "account_canonical_tenant_identity_claims")).isZero(); + assertThat( + countWhere( + fixture.setupDsl(), + "account_authority_generations", + "scope_kind = 'TENANT' AND tenant_uuid = ?", + evidence.canonicalTenantId())) + .isZero(); + } + + @Test + void retainedAndFreshUuidClaimsConflictInEitherInsertionOrder() { + Fixture retainedFirst = fixture(false); + FreshTenantCreationEvidence fresh = + evidence( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + REQUEST_DIGEST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + RETAINED_UUID, + 117L, + "fresh-collision-source"); + inTransaction( + retainedFirst.transaction(), + () -> { + insertRetained( + retainedFirst.transactionDsl(), 81L, RETAINED_UUID, 721L, "retained-source"); + return null; + }); + assertThatThrownBy( + () -> + inTransaction( + retainedFirst.transaction(), + () -> retainedFirst.repository().importVerified(fresh))) + .isInstanceOf(DataAccessException.class); + assertThat(count(retainedFirst.setupDsl(), "account_fresh_tenant_identity_associations")) + .isZero(); + assertThat(count(retainedFirst.setupDsl(), "account_approved_legacy_tenant_associations")) + .isEqualTo(1L); + + Fixture freshFirst = fixture(false); + FreshTenantCreationEvidence freshWinner = + evidence( + UUID.fromString("33333333-3333-4333-8333-333333333333"), + REQUEST_DIGEST, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + RETAINED_UUID, + 118L, + "fresh-winner-source"); + inTransaction( + freshFirst.transaction(), () -> freshFirst.repository().importVerified(freshWinner)); + assertThatThrownBy( + () -> + inTransaction( + freshFirst.transaction(), + () -> { + insertRetained( + freshFirst.transactionDsl(), 82L, RETAINED_UUID, 722L, "retained-loser"); + return null; + })) + .isInstanceOf(DataAccessException.class); + assertThat(count(freshFirst.setupDsl(), "account_fresh_tenant_identity_associations")) + .isEqualTo(1L); + assertThat(count(freshFirst.setupDsl(), "account_approved_legacy_tenant_associations")) + .isZero(); + } + + @Test + void concurrentRetainedAndFreshUuidClaimsSerializeOnTheSharedPrimaryKey() throws Exception { + Fixture fixture = fixture(false); + FreshTenantCreationEvidence fresh = + evidence( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + REQUEST_DIGEST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + RETAINED_UUID, + 117L, + "fresh-concurrent-source"); + CountDownLatch contenderHasPid = new CountDownLatch(1); + AtomicInteger contenderPid = new AtomicInteger(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + + try (Connection holder = fixture.dataSource().getConnection()) { + holder.setAutoCommit(false); + DSLContext holderDsl = DSL.using(holder, SQLDialect.POSTGRES); + Integer observedHolderPid = + fetchOneValue(holderDsl, "SELECT pg_backend_pid()", Integer.class); + if (observedHolderPid == null || observedHolderPid <= 0) { + throw new IllegalStateException("Holder PostgreSQL backend PID is absent or invalid"); + } + int holderPid = observedHolderPid; + insertRetained(holderDsl, 83L, RETAINED_UUID, 723L, "retained-concurrent-source"); + + Future contender = + executor.submit( + () -> { + try { + inTransaction( + fixture.transaction(), + () -> { + Integer observedContenderPid = + fetchOneValue( + fixture.transactionDsl(), "SELECT pg_backend_pid()", Integer.class); + if (observedContenderPid == null || observedContenderPid <= 0) { + throw new IllegalStateException( + "Contender PostgreSQL backend PID is absent or invalid"); + } + contenderPid.set(observedContenderPid); + contenderHasPid.countDown(); + fixture.repository().importVerified(fresh); + return null; + }); + return null; + } catch (RuntimeException failure) { + return failure; + } + }); + + assertThat(contenderHasPid.await(10, TimeUnit.SECONDS)).isTrue(); + awaitBlockedBy(fixture.setupDsl(), holderPid, contenderPid.get()); + holder.commit(); + + RuntimeException failure = contender.get(10, TimeUnit.SECONDS); + assertThat(failure).isInstanceOf(DataAccessException.class); + } finally { + executor.shutdownNow(); + } + + assertThat(count(fixture.setupDsl(), "account_approved_legacy_tenant_associations")) + .isEqualTo(1L); + assertThat(count(fixture.setupDsl(), "account_fresh_tenant_identity_associations")).isZero(); + assertThat(count(fixture.setupDsl(), "account_canonical_tenant_identity_claims")).isEqualTo(1L); + } + + @Test + void v381BackfillsOnlyExistingExactRetainedAssociationsAndRejectsOrphanClaims() { + Fixture fixture = fixture(true); + var retainedClaim = + fixture + .setupDsl() + .fetchOne( + "SELECT canonical_tenant_id, identity_kind, source_operation_id, " + + "source_account_legacy_tenant_id, source_target_namespace, " + + "source_game_row_id, source_game_tenant_key, source_evidence_digest, " + + "source_manifest_digest FROM account_canonical_tenant_identity_claims " + + "WHERE canonical_tenant_id = ?", + RETAINED_UUID); + assertThat(retainedClaim).isNotNull(); + assertThat(retainedClaim.get("canonical_tenant_id", UUID.class)).isEqualTo(RETAINED_UUID); + assertThat(retainedClaim.get("identity_kind", String.class)).isEqualTo("APPROVED_RETAINED"); + assertThat(retainedClaim.get("source_operation_id", UUID.class)) + .isEqualTo(RETAINED_OPERATION_ID); + assertThat(retainedClaim.get("source_account_legacy_tenant_id", Long.class)).isEqualTo(80L); + assertThat(retainedClaim.get("source_target_namespace", String.class)) + .isEqualTo(TEST_NAMESPACE); + assertThat(retainedClaim.get("source_game_row_id", Long.class)).isEqualTo(720L); + assertThat(retainedClaim.get("source_game_tenant_key", String.class)) + .isEqualTo("retained-backfill-source"); + assertThat(retainedClaim.get("source_evidence_digest", String.class)) + .isEqualTo("sha256:" + "c".repeat(64)); + assertThat(retainedClaim.get("source_manifest_digest", String.class)) + .isEqualTo("sha256:" + "d".repeat(64)); + assertThat( + fetchOneValue( + fixture.setupDsl(), + "SELECT source_legacy_game_tenant_id FROM " + + "account_approved_legacy_tenant_associations WHERE canonical_tenant_id = ?", + String.class, + RETAINED_UUID)) + .isEqualTo("retained-backfill-source"); + assertThat(count(fixture.setupDsl(), "account_canonical_tenant_identity_claims")).isEqualTo(1L); + + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "INSERT INTO account_canonical_tenant_identity_claims " + + "(canonical_tenant_id, identity_kind, source_operation_id, " + + "source_target_namespace, source_creation_request_id, " + + "source_request_digest, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest) " + + "VALUES (?, 'FRESH_GAME_DESIGN', ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?) ", + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + TEST_NAMESPACE, + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + REQUEST_DIGEST, + 990L, + "orphan-tenant-key", + "sha256:" + "d".repeat(64))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("no exact source association"); + } + + private static Fixture fixture(boolean preexistingRetainedAssociation) { + String schema = "fresh_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + + if (preexistingRetainedAssociation) { + flyway(dataSource, schema, "38").migrate(); + DSLContext beforeV381 = DSL.using(dataSource, SQLDialect.POSTGRES); + insertRetained(beforeV381, 80L, RETAINED_UUID, 720L, "retained-backfill-source"); + } + flyway(dataSource, schema, null).migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + assertThat(fetchOneValue(setupDsl, "SELECT current_schema()", String.class)).isEqualTo(schema); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + FreshTenantIdentityAssociationRepository repository = + new FreshTenantIdentityAssociationRepository(transactionDsl, TEST_NAMESPACE); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(transactionDsl); + return new Fixture(dataSource, setupDsl, transactionDsl, transaction, repository, generations); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + configuration.target(targetVersion); + } + return configuration.load(); + } + + private static FreshTenantIdentityEnrollmentService service( + Fixture fixture, FreshTenantCreationEvidence evidence) { + GameDesignFreshTenantIdentityClient client = mock(GameDesignFreshTenantIdentityClient.class); + when(client.resolveCreation(evidence.creationRequestId(), evidence.requestDigest())) + .thenReturn(evidence); + return new FreshTenantIdentityEnrollmentService( + client, fixture.repository(), fixture.generations(), fixture.transaction()); + } + + private static FreshTenantCreationEvidence evidence( + UUID requestId, + String requestDigest, + UUID operationId, + UUID canonicalTenantId, + long sourceRowId, + String sourceKey) { + String receiptDigest = + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + receiptDigest); + } + + private static void insertRetained( + DSLContext dsl, + long legacyTenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey) { + dsl.execute( + "INSERT INTO account_approved_legacy_tenant_associations " + + "(legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, manifest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)", + legacyTenantId, + canonicalTenantId, + sourceGameTenantKey, + sourceGameRowId, + "sha256:" + "c".repeat(64), + RETAINED_OPERATION_ID, + "sha256:" + "d".repeat(64), + Base64.getEncoder().encodeToString(new byte[64]), + TEST_NAMESPACE, + "retained-signing-key", + "owner@example.test", + "reviewed-retained-import", + "2026-09-30T00:00:00Z"); + } + + private static void assertNoMembershipOrAdmissionSideEffects(DSLContext dsl) { + assertThat(count(dsl, "account_tenant_membership")).isZero(); + assertThat(count(dsl, "profiles")).isZero(); + assertThat(count(dsl, "account_membership_pair_authority")).isZero(); + assertThat(count(dsl, "account_membership_transition_receipts")).isZero(); + assertThat(count(dsl, "account_authority_outbox_events")).isZero(); + assertThat(count(dsl, "account_join_operations")).isZero(); + assertThat(count(dsl, "account_connect_token_issuance_operations")).isZero(); + assertThat(count(dsl, "account_connect_token_response_envelopes")).isZero(); + assertThat(count(dsl, "account_bare_login_exchange_operations")).isZero(); + assertThat(count(dsl, "account_approved_legacy_tenant_associations")).isZero(); + } + + private static void awaitBlockedBy(DSLContext dsl, int blockerPid, int blockedPid) + throws InterruptedException { + long deadline = System.nanoTime() + Duration.ofSeconds(15).toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + fetchOneValue( + dsl, + "SELECT ? = ANY(pg_blocking_pids(pid)) FROM pg_stat_activity WHERE pid = ?", + Boolean.class, + blockerPid, + blockedPid); + if (Boolean.TRUE.equals(blocked)) { + return; + } + Thread.yield(); + } + throw new AssertionError("Contender PostgreSQL backend was not observed blocked by the holder"); + } + + private static long count(DSLContext dsl, String table) { + Long count = fetchOneValue(dsl, "SELECT count(*) FROM " + table, Long.class); + if (count == null || count < 0L) { + throw new IllegalStateException("PostgreSQL aggregate count is absent or negative"); + } + return count; + } + + private static long countWhere(DSLContext dsl, String table, String predicate, Object... values) { + Long count = + fetchOneValue( + dsl, "SELECT count(*) FROM " + table + " WHERE " + predicate, Long.class, values); + if (count == null || count < 0L) { + throw new IllegalStateException("PostgreSQL aggregate count is absent or negative"); + } + return count; + } + + private static T fetchOneValue( + DSLContext dsl, String query, Class valueType, Object... bindings) { + Record row = dsl.fetchOne(query, bindings); + return row == null ? null : row.get(0, valueType); + } + + private static T inTransaction( + TransactionTemplate transaction, java.util.function.Supplier work) { + return transaction.execute(status -> work.get()); + } + + private record Fixture( + DriverManagerDataSource dataSource, + DSLContext setupDsl, + DSLContext transactionDsl, + TransactionTemplate transaction, + FreshTenantIdentityAssociationRepository repository, + AccountAuthorityGenerationRepository generations) {} +} 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 new file mode 100644 index 0000000000..cd6f947603 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java @@ -0,0 +1,471 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.CallOptions; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +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.TenantIdentityServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; + +class GameDesignFreshTenantIdentityClientTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OTHER_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + 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 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); + + @Test + void exactResponseIsValidatedAndStableOnReplayWithoutCallingRetainedRpcs() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveFreshTenantCreation(any())).thenReturn(validResponse()); + GameDesignFreshTenantIdentityClient client = newClient(stub); + + FreshTenantCreationEvidence first = client.resolveCreation(REQUEST_ID, REQUEST_DIGEST); + FreshTenantCreationEvidence retry = client.resolveCreation(REQUEST_ID, REQUEST_DIGEST); + + assertThat(first).isEqualTo(retry); + assertThat(first.schemaVersion()).isEqualTo(1); + assertThat(first.targetNamespace()).isEqualTo("test"); + assertThat(first.creationRequestId()).isEqualTo(REQUEST_ID); + assertThat(first.operationId()).isEqualTo(OPERATION_ID); + assertThat(first.requestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(first.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); + assertThat(first.sourceGameRowId()).isEqualTo(SOURCE_GAME_ROW_ID); + assertThat(first.sourceGameTenantKey()).isEqualTo(SOURCE_GAME_TENANT_KEY); + assertThat(first.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(first.evidenceDigest()).isEqualTo(validResponse().getEvidenceDigest()); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ResolveFreshTenantCreationRequest.class); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub, times(2)).resolveFreshTenantCreation(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .allSatisfy( + request -> { + assertThat(request.getCreationRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(request.getExpectedRequestDigest()).isEqualTo(REQUEST_DIGEST); + }); + verify(stub, never()).resolveLegacyAccountTenantAssociation(any()); + verify(stub, never()).resolveLegacyGameTenantIdentity(any()); + } + + @Test + void rejectsResponseThatDoesNotBindTheConfiguredNamespaceRequestAndExpectedDigest() + throws Exception { + assertRejected(validResponse("other", REQUEST_ID, REQUEST_DIGEST, SOURCE_GAME_ROW_ID)); + assertRejected(validResponse("test", OTHER_REQUEST_ID, REQUEST_DIGEST, SOURCE_GAME_ROW_ID)); + assertRejected( + validResponse("test", REQUEST_ID, "sha256:" + "b".repeat(64), SOURCE_GAME_ROW_ID)); + } + + @Test + void rejectsChangedSourceRowCorruptDigestUnsupportedSchemaAndWrongProvenance() throws Exception { + ResolveFreshTenantCreationResponse valid = validResponse(); + assertRejected(valid.toBuilder().setSourceGameRowId(SOURCE_GAME_ROW_ID + 1).build()); + assertRejected(valid.toBuilder().setEvidenceDigest("sha256:" + "d".repeat(64)).build()); + assertRejected(valid.toBuilder().setSchemaVersion(2).build()); + assertRejected(valid.toBuilder().setProvenanceKind("RETAINED_GAME_V30").build()); + assertRejected(valid.toBuilder().setOperationId("22222222-2222-4222-8222-22222222222").build()); + assertRejected(valid.toBuilder().setCanonicalTenantId(NIL_UUID.toString()).build()); + } + + @Test + void rejectsUnknownFieldsInClosedFreshTenantEvidenceResponse() throws Exception { + UnknownFieldSet unknownFields = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertRejected(validResponse().toBuilder().setUnknownFields(unknownFields).build()); + } + + @Test + void rejectsMalformedSelectorsBeforeAnyRpc() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + GameDesignFreshTenantIdentityClient client = newClient(stub); + + assertThatThrownBy(() -> client.resolveCreation(null, REQUEST_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.resolveCreation(NIL_UUID, REQUEST_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.resolveCreation(REQUEST_ID, "SHA256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.resolveCreation(REQUEST_ID, "bad-digest")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + } + + @Test + void rejectsPlaintextAndIncompleteAccountMtlsConfigurationBeforeChannelCreation() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + + assertThatThrownBy( + () -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy( + () -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), null, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + List incompleteConfigurations = + List.of( + incompleteMtlsProperties(null, "certs/account-client.key", "certs/game-design-ca.crt"), + incompleteMtlsProperties("certs/account-client.crt", null, "certs/game-design-ca.crt"), + incompleteMtlsProperties("certs/account-client.crt", "certs/account-client.key", null)); + for (CommonGrpcClientProperties incomplete : incompleteConfigurations) { + assertThatThrownBy( + () -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("certificate, key, and CA"); + } + + CommonGrpcClientProperties classpathMaterial = mtlsProperties(); + classpathMaterial.setCertChain("classpath:certs/account-client.crt"); + assertThatThrownBy( + () -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), classpathMaterial, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + List classpathConfigurations = + List.of( + mtlsPropertiesWith( + "certs/account-client.crt", "classpath:account-client.key", "ca.crt"), + mtlsPropertiesWith( + "certs/account-client.crt", "account-client.key", "classpath:ca.crt")); + for (CommonGrpcClientProperties classpathConfiguration : classpathConfigurations) { + assertThatThrownBy( + () -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), + classpathConfiguration, + channelFactory, + "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + for (String invalidNamespace : new String[] {null, "", "Upper", "not/a-label"}) { + assertThatThrownBy( + () -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + channelFactory, + invalidNamespace)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + } + verifyNoInteractions(channelFactory); + } + + @Test + void transportFailureIsPropagatedAndUsesTheBoundedDeadline() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Game Design unavailable")); + when(stub.resolveFreshTenantCreation(any())).thenThrow(unavailable); + GameDesignFreshTenantIdentityClient client = newClient(stub); + + assertThatThrownBy(() -> client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)) + .isSameAs(unavailable); + + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void initUsesFileBackedTlsAndExactGameDesignPeerIdentityForConfiguredEndpoint( + @TempDir Path directory) throws Exception { + CommonGrpcClientProperties tls = mtlsProperties(directory); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design-service.internal:6565"); + GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); + GameDesignFreshTenantIdentityClient client = + new GameDesignFreshTenantIdentityClient(endpoints, tls, channelFactory, "test"); + try { + // This creates the common TLS channel but does not perform a live peer-certificate handshake. + client.init(); + + verify(channelFactory) + .buildChannel( + eq("game-design-service.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + assertThat(installedServerPeerUri(client)) + .isEqualTo("spiffe://firemud/ns/test/sa/game-design-service"); + } finally { + client.close(); + } + } + + @Test + void initializedStubRejectsResponseWithoutAuthenticatedServerSession(@TempDir Path directory) + throws Exception { + UnauthenticatedResponseChannel channel = new UnauthenticatedResponseChannel(validResponse()); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + when(channelFactory.buildChannel( + anyString(), anyInt(), any(CommonGrpcClientProperties.class), anyBoolean())) + .thenReturn(channel); + GameDesignFreshTenantIdentityClient client = + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), mtlsProperties(directory), channelFactory, "test"); + + try { + client.init(); + + assertThatThrownBy(() -> client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(channel.lastCallCancelled).isTrue(); + } finally { + client.close(); + } + } + + private static void assertRejected(ResolveFreshTenantCreationResponse response) throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveFreshTenantCreation(any())).thenReturn(response); + GameDesignFreshTenantIdentityClient client = newClient(stub); + + assertThatThrownBy(() -> client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class); + } + + private static GameDesignFreshTenantIdentityClient newClient( + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) throws Exception { + GameDesignFreshTenantIdentityClient client = + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + mock(GrpcChannelFactory.class), + "test"); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static String installedServerPeerUri(GameDesignFreshTenantIdentityClient client) + throws Exception { + Field interceptorField = + GameDesignFreshTenantIdentityClient.class.getDeclaredField("serverPeerIdentityInterceptor"); + interceptorField.setAccessible(true); + GrpcServerPeerIdentityClientInterceptor interceptor = + (GrpcServerPeerIdentityClientInterceptor) interceptorField.get(client); + Field expectedPeerUriField = + GrpcServerPeerIdentityClientInterceptor.class.getDeclaredField("expectedPeerUri"); + expectedPeerUriField.setAccessible(true); + return (String) expectedPeerUriField.get(interceptor); + } + + private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub mockStub() { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = + mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static ResolveFreshTenantCreationResponse validResponse() { + return validResponse("test", REQUEST_ID, REQUEST_DIGEST, SOURCE_GAME_ROW_ID); + } + + private static ResolveFreshTenantCreationResponse validResponse( + String namespace, UUID requestId, String requestDigest, long sourceGameRowId) { + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + namespace, + requestId, + OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + sourceGameRowId, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW"); + return ResolveFreshTenantCreationResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(namespace) + .setCreationRequestId(requestId.toString()) + .setOperationId(OPERATION_ID.toString()) + .setRequestDigest(requestDigest) + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setSourceGameRowId(sourceGameRowId) + .setSourceGameTenantKey(SOURCE_GAME_TENANT_KEY) + .setProvenanceKind("NEW_GAME_ROW") + .setEvidenceDigest(evidenceDigest) + .build(); + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/account-client.crt"); + tls.setPrivateKey("certs/account-client.key"); + tls.setCaCert("certs/gamedesign-server-ca.crt"); + return tls; + } + + private static CommonGrpcClientProperties incompleteMtlsProperties( + String certificate, String privateKey, String caCertificate) { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate); + tls.setPrivateKey(privateKey); + tls.setCaCert(caCertificate); + return tls; + } + + private static CommonGrpcClientProperties mtlsPropertiesWith( + String certificate, String privateKey, String caCertificate) { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate); + tls.setPrivateKey(privateKey); + tls.setCaCert(caCertificate); + return tls; + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(copyCertificateResource("dev-cert.pem", directory).toString()); + tls.setPrivateKey(copyCertificateResource("dev-key.pem", directory).toString()); + tls.setCaCert(copyCertificateResource("dev-ca.pem", directory).toString()); + return tls; + } + + private static Path copyCertificateResource(String fileName, Path directory) throws Exception { + Path destination = directory.resolve(fileName); + try (InputStream source = + GameDesignFreshTenantIdentityClientTest.class.getResourceAsStream("/certs/" + fileName)) { + if (source == null) { + throw new IllegalStateException("Missing shared TLS test resource: " + fileName); + } + Files.copy(source, destination); + } + return destination; + } + + private static final class UnauthenticatedResponseChannel extends ManagedChannel { + private final byte[] responseBytes; + private boolean lastCallCancelled; + + private UnauthenticatedResponseChannel(ResolveFreshTenantCreationResponse response) { + this.responseBytes = response.toByteArray(); + } + + @Override + public String authority() { + return "test-authority"; + } + + @Override + public ClientCall newCall( + MethodDescriptor method, CallOptions callOptions) { + return new ClientCall<>() { + @Override + public void start(Listener responseListener, Metadata headers) { + responseListener.onHeaders(new Metadata()); + responseListener.onMessage(method.parseResponse(new ByteArrayInputStream(responseBytes))); + responseListener.onClose(Status.OK, new Metadata()); + } + + @Override + public void request(int numMessages) {} + + @Override + public void cancel(String message, Throwable cause) { + lastCallCancelled = true; + } + + @Override + public void halfClose() {} + + @Override + public void sendMessage(ReqT message) {} + + @Override + public Attributes getAttributes() { + // No SSL session means the server workload identity cannot be authenticated. + return Attributes.EMPTY; + } + }; + } + + @Override + public ManagedChannel shutdown() { + return this; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public ManagedChannel shutdownNow() { + return this; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClientTest.java new file mode 100644 index 0000000000..002a43e705 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClientTest.java @@ -0,0 +1,259 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.CallOptions; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class GameDesignTenantIdentityClientTest { + @Test + void rejectsInvalidNamespaceAndNonFileBackedMtlsBeforeChannelCreation() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + + assertThatThrownBy(() -> newClient(plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy(() -> newClient(null, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + List incompleteConfigurations = + List.of( + mtlsPropertiesWith(null, "account.key", "gamedesign-ca.crt"), + mtlsPropertiesWith("account.crt", null, "gamedesign-ca.crt"), + mtlsPropertiesWith("account.crt", "account.key", null)); + for (CommonGrpcClientProperties incomplete : incompleteConfigurations) { + assertThatThrownBy(() -> newClient(incomplete, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("certificate, key, and CA"); + } + + List classpathConfigurations = + List.of( + mtlsPropertiesWith("classpath:account.crt", "account.key", "gamedesign-ca.crt"), + mtlsPropertiesWith("account.crt", "classpath:account.key", "gamedesign-ca.crt"), + mtlsPropertiesWith("account.crt", "account.key", "classpath:gamedesign-ca.crt")); + for (CommonGrpcClientProperties classpathConfiguration : classpathConfigurations) { + assertThatThrownBy(() -> newClient(classpathConfiguration, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + for (String invalidNamespace : new String[] {null, "", "Upper", "not/a-label"}) { + assertThatThrownBy(() -> newClient(mtlsProperties(), channelFactory, invalidNamespace)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + } + verifyNoInteractions(channelFactory); + } + + @Test + void initInstallsExactGameDesignServerIdentityOnTheConfiguredTlsChannel(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design-service.internal:6565"); + GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); + GameDesignTenantIdentityClient client = + new GameDesignTenantIdentityClient( + endpoints, mtlsProperties(directory), channelFactory, "account-test"); + try { + // This constructs the configured TLS channel and stub, but performs no live TLS handshake. + client.init(); + + verify(channelFactory) + .buildChannel( + eq("game-design-service.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + assertThat(installedServerPeerUri(client)) + .isEqualTo("spiffe://firemud/ns/account-test/sa/game-design-service"); + } finally { + client.close(); + } + } + + @Test + void initializedStubRejectsResponseWithoutAuthenticatedServerSession(@TempDir Path directory) + throws Exception { + UnauthenticatedResponseChannel channel = + new UnauthenticatedResponseChannel( + ResolveLegacyAccountTenantAssociationResponse.getDefaultInstance()); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + when(channelFactory.buildChannel( + anyString(), anyInt(), any(CommonGrpcClientProperties.class), anyBoolean())) + .thenReturn(channel); + GameDesignTenantIdentityClient client = + newClient(mtlsProperties(directory), channelFactory, "account-test"); + + try { + client.init(); + + assertThatThrownBy(() -> client.resolveApprovedAssociation(1L)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(channel.lastCallCancelled).isTrue(); + } finally { + client.close(); + } + } + + private static GameDesignTenantIdentityClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory, String namespace) { + return new GameDesignTenantIdentityClient( + new ServiceEndpointsProperties(), tls, channelFactory, namespace); + } + + private static String installedServerPeerUri(GameDesignTenantIdentityClient client) + throws Exception { + Field interceptorField = + GameDesignTenantIdentityClient.class.getDeclaredField("serverPeerIdentityInterceptor"); + interceptorField.setAccessible(true); + GrpcServerPeerIdentityClientInterceptor interceptor = + (GrpcServerPeerIdentityClientInterceptor) interceptorField.get(client); + Field expectedPeerUriField = + GrpcServerPeerIdentityClientInterceptor.class.getDeclaredField("expectedPeerUri"); + expectedPeerUriField.setAccessible(true); + return (String) expectedPeerUriField.get(interceptor); + } + + private static CommonGrpcClientProperties mtlsProperties() { + return mtlsPropertiesWith( + "certs/account-client.crt", "certs/account-client.key", "certs/gamedesign-server-ca.crt"); + } + + private static CommonGrpcClientProperties mtlsPropertiesWith( + String certificate, String privateKey, String caCertificate) { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate); + tls.setPrivateKey(privateKey); + tls.setCaCert(caCertificate); + return tls; + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(copyCertificateResource("dev-cert.pem", directory).toString()); + tls.setPrivateKey(copyCertificateResource("dev-key.pem", directory).toString()); + tls.setCaCert(copyCertificateResource("dev-ca.pem", directory).toString()); + return tls; + } + + private static Path copyCertificateResource(String fileName, Path directory) throws Exception { + Path destination = directory.resolve(fileName); + try (InputStream source = + GameDesignTenantIdentityClientTest.class.getResourceAsStream("/certs/" + fileName)) { + if (source == null) { + throw new IllegalStateException("Missing shared TLS test resource: " + fileName); + } + Files.copy(source, destination); + } + return destination; + } + + private static final class UnauthenticatedResponseChannel extends ManagedChannel { + private final byte[] responseBytes; + private boolean lastCallCancelled; + + private UnauthenticatedResponseChannel(ResolveLegacyAccountTenantAssociationResponse response) { + this.responseBytes = response.toByteArray(); + } + + @Override + public String authority() { + return "test-authority"; + } + + @Override + public ClientCall newCall( + MethodDescriptor method, CallOptions callOptions) { + return new ClientCall<>() { + @Override + public void start(Listener responseListener, Metadata headers) { + responseListener.onHeaders(new Metadata()); + responseListener.onMessage(method.parseResponse(new ByteArrayInputStream(responseBytes))); + responseListener.onClose(Status.OK, new Metadata()); + } + + @Override + public void request(int numMessages) {} + + @Override + public void cancel(String message, Throwable cause) { + lastCallCancelled = true; + } + + @Override + public void halfClose() {} + + @Override + public void sendMessage(ReqT message) {} + + @Override + public Attributes getAttributes() { + // No SSL session means the server workload identity cannot be authenticated. + return Attributes.EMPTY; + } + }; + } + + @Override + public ManagedChannel shutdown() { + return this; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public ManagedChannel shutdownNow() { + return this; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java new file mode 100644 index 0000000000..5540800e32 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.ProvenPositiveCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class AccountMembershipPairAuthorityRepositoryTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String EVENT_DIGEST = "sha256:" + "a".repeat(64); + private static final String SOURCE_DIGEST = "sha256:" + "b".repeat(64); + + @Test + void verifiedProvenanceRequiresKindQualifiedLegacyIdentity() { + VerifiedTenantProvenance fresh = freshProvenance(); + VerifiedTenantProvenance retained = retainedProvenance(72L); + + assertThat(fresh.legacyTenantId()).isNull(); + assertThat(fresh.kind()).isEqualTo(TenantProvenanceKind.FRESH_GAME_DESIGN); + assertThat(retained.legacyTenantId()).isEqualTo(72L); + assertThat(retained.kind()).isEqualTo(TenantProvenanceKind.APPROVED_RETAINED); + + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + 72L, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, SOURCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not carry a legacy tenant ID"); + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + null, TenantProvenanceKind.APPROVED_RETAINED, OPERATION_ID, SOURCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive legacy tenant ID"); + assertThatThrownBy(() -> retainedProvenance(0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive legacy tenant ID"); + assertThatThrownBy(() -> retainedProvenance(-1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive legacy tenant ID"); + } + + @Test + void pairRecordsPreservePositiveBaselineAndEventShapes() { + PairAuthority baseline = + new PairAuthority( + ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); + assertThat(baseline.membershipVersion()).isEqualTo(1L); + assertThat(baseline.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(baseline.lastEventSequence()).isZero(); + assertThat(baseline.membershipExists()).isFalse(); + + PairAuthority joined = + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + true, + 2L, + 1L, + 1L, + "join-event-1", + EVENT_DIGEST, + false); + assertThat(joined.membershipVersion()).isEqualTo(2L); + assertThat(joined.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(joined.lastEventSequence()).isEqualTo(1L); + + PairTransition leave = new PairTransition(false, 2L, "leave-event-2", EVENT_DIGEST, true); + assertThat(leave.eventSequence()).isEqualTo(2L); + assertThat(leave.callerBoundAuthorityInvalidated()).isTrue(); + ProvenPositiveCheckpoint retainedCheckpoint = + new ProvenPositiveCheckpoint(8L, 3L, 11L, "retained-event-11", EVENT_DIGEST, true); + assertThat(retainedCheckpoint.membershipVersion()).isEqualTo(8L); + assertThat(retainedCheckpoint.membershipAuthorityGeneration()).isEqualTo(3L); + assertThat(retainedCheckpoint.eventSequence()).isEqualTo(11L); + + assertThatThrownBy( + () -> + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + false, + 0L, + 1L, + 0L, + null, + null, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + assertThatThrownBy( + () -> + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + false, + 1L, + 0L, + 0L, + null, + null, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + assertThatThrownBy( + () -> + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + true, + 1L, + 1L, + 0L, + null, + null, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Sequence-zero"); + assertThatThrownBy( + () -> + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + true, + 2L, + 1L, + 1L, + " ", + EVENT_DIGEST, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("event evidence"); + assertThatThrownBy( + () -> new ProvenPositiveCheckpoint(8L, 3L, 0L, "event-0", EVENT_DIGEST, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + assertThatThrownBy(() -> new PairTransition(true, 0L, "event-0", EVENT_DIGEST, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + } + + @Test + void directRepositoryOperationsRequireOwnerTransactionBeforeDslAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountMembershipPairAuthorityRepository repository = + new AccountMembershipPairAuthorityRepository(dsl); + PairAuthority baseline = + new PairAuthority( + ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); + PairTransition transition = new PairTransition(true, 1L, "join-event-1", EVENT_DIGEST, false); + ProvenPositiveCheckpoint checkpoint = + new ProvenPositiveCheckpoint(8L, 3L, 11L, "retained-event-11", EVENT_DIGEST, true); + + assertThatThrownBy(() -> repository.enrollAbsence(ACCOUNT_UUID, TENANT_UUID, freshProvenance())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy( + () -> + repository.enrollProvenPositive( + ACCOUNT_UUID, TENANT_UUID, retainedProvenance(72L), checkpoint)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy(() -> repository.readForUpdate(ACCOUNT_UUID, TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy(() -> repository.commitTransition(baseline, transition)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + + verifyNoInteractions(dsl); + } + + private VerifiedTenantProvenance freshProvenance() { + return new VerifiedTenantProvenance( + null, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, SOURCE_DIGEST); + } + + private VerifiedTenantProvenance retainedProvenance(long legacyTenantId) { + return new VerifiedTenantProvenance( + legacyTenantId, TenantProvenanceKind.APPROVED_RETAINED, OPERATION_ID, SOURCE_DIGEST); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java index 03e568dacd..a4699e09da 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java @@ -30,13 +30,17 @@ void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws "V37__verified_audit_projection_evidence.sql", "V37.1__account_bare_login_exchange_storage.sql", "V38__account_join_reconciliation.sql", + "V38.1__fresh_tenant_identity_associations.sql", + "V39__fresh_uuid_membership_pair_authority.sql", + "V39.1__migrate_empty_account_connect_storage_to_uuid.sql", "V40__account_membership_transition_receipts.sql", "V41__protect_account_membership_transition_receipts.sql") .doesNotContain( "V28__account_join_reconciliation.sql", "V28__account_membership_transition_receipts.sql", "V28.1__account_membership_transition_receipts.sql", - "V37__account_bare_login_exchange_storage.sql"); + "V37__account_bare_login_exchange_storage.sql", + "V38__fresh_tenant_identity_associations.sql"); assertThat(migrations.stream().map(AccountMigrationVersionTest::version).toList()) .as("Flyway rejects two different migration descriptions with the same version") .doesNotHaveDuplicates(); @@ -48,6 +52,12 @@ void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws .isLessThan(version("V37.1__account_bare_login_exchange_storage.sql")); assertThat(version("V37.1__account_bare_login_exchange_storage.sql")) .isLessThan(version("V38__account_join_reconciliation.sql")); + assertThat(version("V38__account_join_reconciliation.sql")) + .isLessThan(version("V38.1__fresh_tenant_identity_associations.sql")); + assertThat(version("V38.1__fresh_tenant_identity_associations.sql")) + .isLessThan(version("V39__fresh_uuid_membership_pair_authority.sql")); + assertThat(version("V39__fresh_uuid_membership_pair_authority.sql")) + .isLessThan(version("V39.1__migrate_empty_account_connect_storage_to_uuid.sql")); assertThat(version("V38__account_join_reconciliation.sql")) .isLessThan(MigrationVersion.fromVersion("39.1")); assertThat(version("V40__account_membership_transition_receipts.sql")) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolverTest.java index 3741b1f5c1..db0548da4a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolverTest.java @@ -18,6 +18,10 @@ class AccountTenantIdentityResolverTest { private static final long LEGACY_TENANT_ID = 41L; private static final String NAMESPACE = "proof"; private static final String EVIDENCE_DIGEST = "sha256:" + "a".repeat(64); + private static final UUID CANONICAL_TENANT_UUID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OTHER_TENANT_UUID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); private final ApprovedLegacyTenantAssociationRepository associations = mock(ApprovedLegacyTenantAssociationRepository.class); @@ -32,6 +36,11 @@ void resolverRequiresCallerOwnedSnapshotTransaction() throws NoSuchMethodExcepti .getMethod("resolve", long.class) .getAnnotation(Transactional.class); assertThat(boundary.propagation()).isEqualTo(Propagation.MANDATORY); + Transactional uuidBoundary = + AccountTenantIdentityResolver.class + .getMethod("resolve", UUID.class) + .getAnnotation(Transactional.class); + assertThat(uuidBoundary.propagation()).isEqualTo(Propagation.MANDATORY); } @Test @@ -55,6 +64,60 @@ void resolvesCanonicalIdentityWithRetainedProvenanceAfterExactEvidenceReadback() verify(sourceEvidence).digest(LEGACY_TENANT_ID); } + @Test + void resolvesCanonicalUuidThroughExactRetainedReverseLookupAndSourceDigest() { + ApprovedAssociation association = association(); + when(associations.findByCanonicalTenantId(CANONICAL_TENANT_UUID)) + .thenReturn(Optional.of(association)); + when(sourceEvidence.digest(LEGACY_TENANT_ID)).thenReturn(EVIDENCE_DIGEST); + + ApprovedAssociation resolved = resolver.resolve(CANONICAL_TENANT_UUID); + + assertThat(resolved).isSameAs(association); + assertThat(resolved.legacyTenantId()).isEqualTo(LEGACY_TENANT_ID); + assertThat(resolved.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_UUID); + assertThat(resolved.sourceGameRowId()).isEqualTo(7L); + verify(associations).findByCanonicalTenantId(CANONICAL_TENANT_UUID); + verify(sourceEvidence).digest(LEGACY_TENANT_ID); + } + + @Test + void canonicalUuidReverseLookupRejectsUnmappedAssociation() { + when(associations.findByCanonicalTenantId(CANONICAL_TENANT_UUID)).thenReturn(Optional.empty()); + assertThatThrownBy(() -> resolver.resolve(CANONICAL_TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is absent"); + verify(sourceEvidence, never()).digest(LEGACY_TENANT_ID); + } + + @Test + void canonicalUuidReverseLookupRejectsConflictingAssociationBeforeSourceRead() { + when(associations.findByCanonicalTenantId(CANONICAL_TENANT_UUID)) + .thenReturn(Optional.of(association(OTHER_TENANT_UUID, NAMESPACE))); + assertThatThrownBy(() -> resolver.resolve(CANONICAL_TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is mismatched"); + verify(sourceEvidence, never()).digest(LEGACY_TENANT_ID); + } + + @Test + void canonicalUuidReverseLookupRejectsChangedRetainedSourceDigest() { + when(associations.findByCanonicalTenantId(CANONICAL_TENANT_UUID)) + .thenReturn(Optional.of(association())); + when(sourceEvidence.digest(LEGACY_TENANT_ID)).thenReturn("sha256:" + "c".repeat(64)); + + assertThatThrownBy(() -> resolver.resolve(CANONICAL_TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("evidence differs"); + } + + @Test + void nilCanonicalUuidIsRejectedBeforeReverseLookup() { + assertThatThrownBy(() -> resolver.resolve(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil canonical tenant UUID"); + } + @Test void missingAssociationFailsClosedBeforeReadingRetainedEvidence() { when(associations.findByLegacyTenantId(LEGACY_TENANT_ID)).thenReturn(Optional.empty()); @@ -114,9 +177,13 @@ private static ApprovedAssociation association() { } private static ApprovedAssociation association(String targetNamespace) { + return association(CANONICAL_TENANT_UUID, targetNamespace); + } + + private static ApprovedAssociation association(UUID canonicalTenantUuid, String targetNamespace) { return new ApprovedAssociation( LEGACY_TENANT_ID, - UUID.fromString("22222222-2222-4222-8222-222222222222"), + canonicalTenantUuid, "legacy-game-7", 7L, EVIDENCE_DIGEST, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java index 78c39533a4..e322260b65 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException; import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.BareLoginRecoveryPayload; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -41,11 +42,16 @@ void exactEnvelopeBytesDecryptAfterCryptoObjectRecreationForBothPurposes() throw byte[] exactResult = "the exact previously issued result".getBytes(StandardCharsets.UTF_8); AccountEnvelopeBinding loginBinding = loginBinding("login-op-1", "login-request-1"); byte[] exactLoginResult = "the exact bare LOGIN result".getBytes(StandardCharsets.UTF_8); + byte[] exactLoginRecoveryPayload = + BareLoginRecoveryPayload.of( + "original-protected.original-payload.original-signature", exactLoginResult) + .encode(); AccountEncryptedEnvelope envelope = writer.encrypt(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding, exactResult); AccountEncryptedEnvelope loginEnvelope = - writer.encrypt(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding, exactLoginResult); + writer.encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding, exactLoginRecoveryPayload); AccountEnvelopeCrypto recoveryReader = new AccountEnvelopeCrypto(manifestPath); assertEquals("k1", envelope.keyId()); @@ -56,9 +62,17 @@ void exactEnvelopeBytesDecryptAfterCryptoObjectRecreationForBothPurposes() throw assertEquals("k1", loginEnvelope.keyId()); assertEquals(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginEnvelope.purpose()); assertArrayEquals( - exactLoginResult, + exactLoginRecoveryPayload, recoveryReader.decrypt( loginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding)); + BareLoginRecoveryPayload recoveredLoginPayload = + BareLoginRecoveryPayload.decode( + recoveryReader.decrypt( + loginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding)); + assertEquals( + "original-protected.original-payload.original-signature", + recoveredLoginPayload.originalGatewayContext()); + assertArrayEquals(exactLoginResult, recoveredLoginPayload.originalResultBytes()); assertFailure( Failure.AUTHENTICATION_FAILED, () -> diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java index eadd9ed0f5..fdabc81d30 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java @@ -1,5 +1,6 @@ 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.assertInstanceOf; @@ -20,6 +21,10 @@ import java.util.List; import java.util.Map; import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.security.HistoricalAccountGameplayConnectEvidence; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; @@ -28,6 +33,7 @@ class AccountGameplayConnectSourceVerifierTest { private static final String ISSUER = "https://account.example.test"; private static final String RSA_KID = "account-rsa-current"; private static final String ED_KID = "account-ed-current"; + private static final String GATEWAY_KID = "gateway-history-test"; private static final int MAX_COMPACT_JWT_BYTES = 16 * 1024; private static final Instant NOW = Instant.parse("2026-04-06T12:00:00Z"); private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); @@ -44,6 +50,7 @@ class AccountGameplayConnectSourceVerifierTest { private KeyPair rsaKeyPair; private KeyPair edKeyPair; + private KeyPair gatewayKeyPair; @BeforeEach void setUp() throws Exception { @@ -51,6 +58,7 @@ void setUp() throws Exception { rsa.initialize(2048); rsaKeyPair = rsa.generateKeyPair(); edKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + gatewayKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); } @Test @@ -176,6 +184,81 @@ void rejectsExpiredFutureAndOverlongSourceTimesBeforeProjection() throws Excepti assertSanitizedFailure(sign(overlong, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); } + @Test + void verifiesExpiredSourceOnlyAgainstSignedHistoricalGatewayTime() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 30, NOW_SECONDS - 1); + String compactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + HistoricalGatewayConnectEvidence gatewayEvidence = + historicalGatewayEvidence(claims, NOW_SECONDS - 2); + + assertSanitizedFailure(compactJwt); + HistoricalAccountGameplayConnectEvidence evidence = + verifier().verifyHistorical(compactJwt, gatewayEvidence); + + assertEquals(RSA_KID, evidence.accountKeyId()); + assertEquals(claims, evidence.sourceClaims()); + assertEquals(gatewayEvidence.signedEnvelope(), evidence.gatewayEvidence().signedEnvelope()); + assertArrayEquals(gatewayEvidence.signedPayload(), evidence.gatewayEvidence().signedPayload()); + assertEquals(gatewayEvidence.claims(), evidence.gatewayEvidence().claims()); + assertEquals( + LARGE_ACCOUNT_GENERATION, + objectMap(objectMap(evidence.sourceClaims().get("authorityTuple"))) + .get("accountAuthorityGeneration")); + assertFalse(evidence.sourceClaims().containsValue(compactJwt)); + assertFalse(evidence.toString().contains(compactJwt)); + assertThrows(UnsupportedOperationException.class, () -> evidence.sourceClaims().put("x", "y")); + Map tuple = objectMap(evidence.sourceClaims().get("authorityTuple")); + assertThrows( + UnsupportedOperationException.class, + () -> tuple.put("accountAuthorityGeneration", BigInteger.ZERO)); + assertFalse(evidence.gatewayEvidence().signedEnvelope().isEmpty()); + } + + @Test + void rejectsBadAccountSignatureProfileAndHistoricalSourceCorrespondence() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 30, NOW_SECONDS - 1); + String validCompactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + HistoricalGatewayConnectEvidence validGatewayEvidence = + historicalGatewayEvidence(claims, NOW_SECONDS - 2); + + KeyPair wrongAccountSigner = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + assertHistoricalSanitizedFailure( + sign(claims, "RS256", RSA_KID, "JWT", wrongAccountSigner.getPrivate()), + validGatewayEvidence); + + Map wrongIssuer = new LinkedHashMap<>(claims); + wrongIssuer.put("iss", "https://other-account.example.test"); + assertHistoricalSanitizedFailure( + sign(wrongIssuer, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()), validGatewayEvidence); + + Map wrongAudience = new LinkedHashMap<>(claims); + wrongAudience.put("aud", "player-bootstrap"); + assertHistoricalSanitizedFailure( + sign(wrongAudience, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()), + validGatewayEvidence); + + Map changedTarget = new LinkedHashMap<>(claims); + changedTarget.put("realmId", "00000000-0000-4000-8000-000000000099"); + assertHistoricalSanitizedFailure( + sign(changedTarget, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()), + validGatewayEvidence); + + HistoricalGatewayConnectEvidence changedGatewayEvidence = + historicalGatewayEvidence( + claims, NOW_SECONDS - 2, "realmId", "00000000-0000-4000-8000-000000000099"); + assertHistoricalSanitizedFailure(validCompactJwt, changedGatewayEvidence); + + Map sourceValidAtGatewayTime = sourceClaims(NOW_SECONDS - 29, NOW_SECONDS + 1); + HistoricalGatewayConnectEvidence gatewayAfterSourceExpiry = + historicalGatewayEvidence(sourceValidAtGatewayTime, NOW_SECONDS); + assertHistoricalSanitizedFailure(validCompactJwt, gatewayAfterSourceExpiry); + + Map openProfile = new LinkedHashMap<>(claims); + openProfile.put("unregisteredClaim", "not accepted"); + assertHistoricalSanitizedFailure( + sign(openProfile, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()), validGatewayEvidence); + } + @Test void rejectsNonCanonicalMalformedAndOversizedCompactJwts() throws Exception { Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); @@ -332,6 +415,28 @@ private AccountGameplayConnectSourceVerifier verifier() { ISSUER, Map.of(RSA_KID, rsaKeyPair.getPublic()), MAX_COMPACT_JWT_BYTES, CLOCK); } + private HistoricalGatewayConnectEvidence historicalGatewayEvidence( + Map sourceClaims, long verifiedAt) throws Exception { + return historicalGatewayEvidence(sourceClaims, verifiedAt, null, null); + } + + private HistoricalGatewayConnectEvidence historicalGatewayEvidence( + Map sourceClaims, long verifiedAt, String changedField, Object changedValue) + throws Exception { + Map contextClaims = + new LinkedHashMap<>( + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + sourceClaims, verifiedAt, "gateway-history-request")); + if (changedField != null) { + contextClaims.put(changedField, changedValue); + } + String envelope = + GatewayConnectContextSignature.sign( + JSON.writeValueAsBytes(contextClaims), GATEWAY_KID, gatewayKeyPair.getPrivate()); + return GatewayConnectContextCodec.verifyHistoricalEvidence( + envelope, Map.of(GATEWAY_KID, gatewayKeyPair.getPublic())); + } + private void assertSanitizedFailure(String compactJwt) { assertSanitizedFailure(verifier(), compactJwt); } @@ -347,6 +452,19 @@ private void assertSanitizedFailure( } } + private void assertHistoricalSanitizedFailure( + String compactJwt, HistoricalGatewayConnectEvidence gatewayEvidence) { + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> verifier().verifyHistorical(compactJwt, gatewayEvidence)); + assertEquals("invalid Account gameplay-connect source JWT", failure.getMessage()); + assertNull(failure.getCause()); + if (compactJwt != null) { + assertFalse(failure.getMessage().contains(compactJwt)); + } + } + private static Map sourceClaims(long issuedAt, long expiresAt) { Map claims = new LinkedHashMap<>(); claims.put("iss", ISSUER); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayloadTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayloadTest.java new file mode 100644 index 0000000000..9ed07850e7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayloadTest.java @@ -0,0 +1,207 @@ +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.assertThrows; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.BareLoginRecoveryPayload; +import org.junit.jupiter.api.Test; + +class BareLoginRecoveryPayloadTest { + private static final String GATEWAY_CONTEXT = "protected.payload.signature"; + private static final byte[] RESULT_BYTES = new byte[] {0, 1, (byte) 0xff, '\n', 42}; + + @Test + void roundTripsExactContextAndOpaqueResultBytes() { + BareLoginRecoveryPayload original = BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, RESULT_BYTES); + byte[] encoded = original.encode(); + + BareLoginRecoveryPayload recovered = BareLoginRecoveryPayload.decode(encoded); + + assertEquals(GATEWAY_CONTEXT, recovered.originalGatewayContext()); + assertArrayEquals( + GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8), recovered.originalGatewayContextUtf8()); + assertArrayEquals(RESULT_BYTES, recovered.originalResultBytes()); + assertEquals( + 16 + GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8).length + RESULT_BYTES.length, + encoded.length); + assertFalse(recovered.toString().contains(GATEWAY_CONTEXT)); + assertFalse(recovered.toString().contains("signature")); + } + + @Test + void rejectsUnknownVersionTruncationTrailingBytesAndUnknownHeader() { + byte[] valid = BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, RESULT_BYTES).encode(); + + byte[] unknownVersion = valid.clone(); + unknownVersion[7] = 2; + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(unknownVersion)); + + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.decode(Arrays.copyOf(valid, valid.length - 1))); + + byte[] trailingByte = Arrays.copyOf(valid, valid.length + 1); + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(trailingByte)); + + byte[] unknownHeader = valid.clone(); + unknownHeader[0] ^= 1; + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(unknownHeader)); + } + + @Test + void rejectsNegativeAndHugeDeclaredContextAndResultLengths() { + byte[] context = GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8); + byte[] valid = rawFrame(context, RESULT_BYTES); + int resultLengthOffset = 12 + context.length; + + byte[] negativeContextLength = valid.clone(); + putInt(negativeContextLength, 8, -1); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.decode(negativeContextLength)); + + byte[] hugeContextLength = valid.clone(); + putInt(hugeContextLength, 8, Integer.MAX_VALUE); + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(hugeContextLength)); + + byte[] negativeResultLength = valid.clone(); + putInt(negativeResultLength, resultLengthOffset, -1); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.decode(negativeResultLength)); + + byte[] hugeResultLength = valid.clone(); + putInt(hugeResultLength, resultLengthOffset, Integer.MAX_VALUE); + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(hugeResultLength)); + } + + @Test + void rejectsContextOnlyFrameTruncatedAtResultLengthBoundary() { + byte[] context = GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8); + byte[] contextOnly = contextOnlyFrame(context); + + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(contextOnly)); + } + + @Test + void rejectsEmptyInvalidUtf8AndNonCompactFields() { + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.of("", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, new byte[0])); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of(".payload.signature", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of("header..signature", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of("header.payload.", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of("header.payload.signature.extra", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of("header.päyload.signature", RESULT_BYTES)); + + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.decode(rawFrame(new byte[0], RESULT_BYTES))); + assertThrows( + IllegalArgumentException.class, + () -> + BareLoginRecoveryPayload.decode( + rawFrame(GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8), new byte[0]))); + assertThrows( + IllegalArgumentException.class, + () -> + BareLoginRecoveryPayload.decode( + rawFrame(new byte[] {(byte) 0xc3, '.', 'b', '.', 'c'}, RESULT_BYTES))); + } + + @Test + void rejectsFramesBeyondAccountEnvelopePlaintextBound() { + byte[] oversizedResult = new byte[AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES]; + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, oversizedResult)); + + byte[] oversizedFrame = new byte[AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES + 1]; + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(oversizedFrame)); + } + + @Test + void acceptsFrameAtExactAccountEnvelopePlaintextBound() { + int maxFrameLength = AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES; + int contextLength = maxFrameLength - 16 - 1; + String context = "a".repeat(contextLength - 4) + ".b.c"; + byte[] result = new byte[] {(byte) 0xff}; + + byte[] encoded = BareLoginRecoveryPayload.of(context, result).encode(); + + assertEquals(maxFrameLength, encoded.length); + BareLoginRecoveryPayload recovered = BareLoginRecoveryPayload.decode(encoded); + assertEquals(context, recovered.originalGatewayContext()); + assertArrayEquals(result, recovered.originalResultBytes()); + } + + @Test + void defensivelyCopiesInputsAndOutputs() { + byte[] result = RESULT_BYTES.clone(); + BareLoginRecoveryPayload payload = BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, result); + Arrays.fill(result, (byte) 0); + + byte[] exposedContext = payload.originalGatewayContextUtf8(); + byte[] exposedResult = payload.originalResultBytes(); + byte[] exposedFrame = payload.encode(); + Arrays.fill(exposedContext, (byte) 0); + Arrays.fill(exposedResult, (byte) 0); + Arrays.fill(exposedFrame, (byte) 0); + + assertArrayEquals(RESULT_BYTES, payload.originalResultBytes()); + assertEquals(GATEWAY_CONTEXT, payload.originalGatewayContext()); + assertArrayEquals( + RESULT_BYTES, BareLoginRecoveryPayload.decode(payload.encode()).originalResultBytes()); + } + + private static byte[] rawFrame(byte[] context, byte[] result) { + ByteBuffer frame = + ByteBuffer.allocate(16 + context.length + result.length).order(ByteOrder.BIG_ENDIAN); + frame.put(new byte[] {'F', 'M', 'B', 'R'}); + frame.putInt(1); + frame.putInt(context.length); + frame.put(context); + frame.putInt(result.length); + frame.put(result); + return frame.array(); + } + + private static byte[] contextOnlyFrame(byte[] context) { + ByteBuffer frame = ByteBuffer.allocate(12 + context.length).order(ByteOrder.BIG_ENDIAN); + frame.put(new byte[] {'F', 'M', 'B', 'R'}); + frame.putInt(1); + frame.putInt(context.length); + frame.put(context); + return frame.array(); + } + + private static void putInt(byte[] frame, int offset, int value) { + ByteBuffer.wrap(frame).order(ByteOrder.BIG_ENDIAN).putInt(offset, value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java index 4952b4afcf..13e277104d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java @@ -12,12 +12,14 @@ import java.time.Instant; import java.time.ZoneOffset; import java.util.Map; +import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; @@ -30,13 +32,18 @@ class AccountCommittedConnectSourceReaderGuardTest { private static final String WORKLOAD_NAMESPACE = "account-unit"; private static final AccountConnectTokenIssuanceIdentity IDENTITY = - new AccountConnectTokenIssuanceIdentity(101L, 202L, "connect-scope-1", "request-1"); + new AccountConnectTokenIssuanceIdentity( + 101L, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + "connect-scope-1", + "request-1"); private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-04-06T12:00:00Z"), ZoneOffset.UTC); private AccountConnectTokenIssuanceRepository issuanceRepository; private AccountRepository accountRepository; private AccountTenantIdentityResolver tenantIdentityResolver; + private FreshTenantIdentityAssociationRepository freshTenantIdentityRepository; private AccountJoinOperationRepository joinOperationRepository; private AccountEnvelopeCrypto envelopeCrypto; private AccountGameplayConnectSourceVerifier sourceVerifier; @@ -48,6 +55,7 @@ void setUp() throws Exception { issuanceRepository = mock(AccountConnectTokenIssuanceRepository.class); accountRepository = mock(AccountRepository.class); tenantIdentityResolver = mock(AccountTenantIdentityResolver.class); + freshTenantIdentityRepository = mock(FreshTenantIdentityAssociationRepository.class); joinOperationRepository = mock(AccountJoinOperationRepository.class); envelopeCrypto = mock(AccountEnvelopeCrypto.class); sourceVerifier = mock(AccountGameplayConnectSourceVerifier.class); @@ -59,6 +67,7 @@ void setUp() throws Exception { issuanceRepository, accountRepository, tenantIdentityResolver, + freshTenantIdentityRepository, joinOperationRepository, envelopeCrypto, sourceVerifier, @@ -80,6 +89,15 @@ void missingPeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { verifyNoCollaboratorInteractions(); } + @Test + void connectSourceIdentityRequiresNonNilCanonicalTenantUuid() { + assertThrows( + IllegalArgumentException.class, + () -> + new AccountConnectTokenIssuanceIdentity( + IDENTITY.accountId(), new UUID(0L, 0L), "scope", "request")); + } + @Test void wrongServicePeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { assertPeerDeniedBeforeInteractions(peer(WORKLOAD_NAMESPACE, "world-management-service")); @@ -108,6 +126,42 @@ void exactPeerWithoutOwnerTransactionIsDeniedBeforeAnyRepositoryOrCredentialInte verifyNoCollaboratorInteractions(); } + @Test + void historicalReadRequiresExactPeerAndOwnerTransactionBeforeAnyInteraction() { + AdminAuthorizationException missingPeer = + assertThrows( + AdminAuthorizationException.class, + () -> withoutPeer(() -> reader.readHistorical(IDENTITY, "unparsed-gateway-context"))); + assertEquals( + "Committed Account source readback requires the exact Game Session workload identity", + missingPeer.getMessage()); + verifyNoCollaboratorInteractions(); + + AdminAuthorizationException wrongPeer = + assertThrows( + AdminAuthorizationException.class, + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "world-management-service"), + () -> reader.readHistorical(IDENTITY, "unparsed-gateway-context"))); + assertEquals( + "Committed Account source readback requires the exact Game Session workload identity", + wrongPeer.getMessage()); + verifyNoCollaboratorInteractions(); + + IllegalStateException missingTransaction = + assertThrows( + IllegalStateException.class, + () -> + withPeer( + expectedGameSessionPeer, + () -> reader.readHistorical(IDENTITY, "unparsed-gateway-context"))); + assertEquals( + "Committed Account source readback requires an active owner transaction", + missingTransaction.getMessage()); + verifyNoCollaboratorInteractions(); + } + private void assertPeerDeniedBeforeInteractions(GrpcPeerIdentity peer) { AdminAuthorizationException failure = assertThrows( @@ -125,6 +179,7 @@ private void verifyNoCollaboratorInteractions() { issuanceRepository, accountRepository, tenantIdentityResolver, + freshTenantIdentityRepository, joinOperationRepository, envelopeCrypto, sourceVerifier); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java new file mode 100644 index 0000000000..2076cdc2b7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java @@ -0,0 +1,135 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +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.FreshTenantIdentityAssociationRepository; +import org.junit.jupiter.api.Test; + +class AccountMembershipAuthorityEventProducerTest { + @Test + void freshSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { + AccountJoinOperationRepository joinOperationRepository = + mock(AccountJoinOperationRepository.class); + AccountRepository accountRepository = mock(AccountRepository.class); + FreshTenantIdentityAssociationRepository freshAssociationRepository = + mock(FreshTenantIdentityAssociationRepository.class); + AccountMembershipAuthorityEventProducer producer = + new AccountMembershipAuthorityEventProducer( + joinOperationRepository, + mock(AccountMembershipPairAuthorityRepository.class), + accountRepository, + mock(AccountTenantIdentityResolver.class), + freshAssociationRepository, + mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthorityOutboxRepository.class), + mock(AccountMembershipTransitionReceiptRepository.class), + mock(AccountTenantMembershipRepository.class), + mock(AccountTenantMembershipRoleSnapshotRepository.class)); + + assertThatThrownBy( + () -> + producer.readFreshNeverJoinedMembershipSnapshot( + UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + verifyNoInteractions(joinOperationRepository, accountRepository, freshAssociationRepository); + } + + @Test + void canonicalRuntimeSnapshotRequiresOwnerTransactionBeforeIdentityReads() { + AccountJoinOperationRepository joinOperationRepository = + mock(AccountJoinOperationRepository.class); + AccountRepository accountRepository = mock(AccountRepository.class); + AccountTenantIdentityResolver tenantIdentityResolver = + mock(AccountTenantIdentityResolver.class); + FreshTenantIdentityAssociationRepository freshAssociationRepository = + mock(FreshTenantIdentityAssociationRepository.class); + AccountMembershipAuthorityEventProducer producer = + new AccountMembershipAuthorityEventProducer( + joinOperationRepository, + mock(AccountMembershipPairAuthorityRepository.class), + accountRepository, + tenantIdentityResolver, + freshAssociationRepository, + mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthorityOutboxRepository.class), + mock(AccountMembershipTransitionReceiptRepository.class), + mock(AccountTenantMembershipRepository.class), + mock(AccountTenantMembershipRoleSnapshotRepository.class)); + + assertThatThrownBy( + () -> producer.readRuntimeMembershipSnapshot(UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + verifyNoInteractions( + joinOperationRepository, + accountRepository, + tenantIdentityResolver, + freshAssociationRepository); + } + + @Test + void existingPositiveSnapshotRequiresOwnerTransactionBeforeIdentityReads() { + AccountJoinOperationRepository joinOperationRepository = + mock(AccountJoinOperationRepository.class); + AccountMembershipPairAuthorityRepository pairAuthorityRepository = + mock(AccountMembershipPairAuthorityRepository.class); + AccountRepository accountRepository = mock(AccountRepository.class); + AccountTenantIdentityResolver tenantIdentityResolver = + mock(AccountTenantIdentityResolver.class); + FreshTenantIdentityAssociationRepository freshAssociationRepository = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository authorityGenerationRepository = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository authorityOutboxRepository = + mock(AccountAuthorityOutboxRepository.class); + AccountMembershipTransitionReceiptRepository transitionReceiptRepository = + mock(AccountMembershipTransitionReceiptRepository.class); + AccountTenantMembershipRepository membershipRepository = + mock(AccountTenantMembershipRepository.class); + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + AccountMembershipAuthorityEventProducer producer = + new AccountMembershipAuthorityEventProducer( + joinOperationRepository, + pairAuthorityRepository, + accountRepository, + tenantIdentityResolver, + freshAssociationRepository, + authorityGenerationRepository, + authorityOutboxRepository, + transitionReceiptRepository, + membershipRepository, + roleSnapshotRepository); + + assertThatThrownBy( + () -> + producer.readExistingPairBoundPositiveMembershipSnapshot( + UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + verifyNoInteractions( + joinOperationRepository, + pairAuthorityRepository, + accountRepository, + tenantIdentityResolver, + freshAssociationRepository, + authorityGenerationRepository, + authorityOutboxRepository, + transitionReceiptRepository, + membershipRepository, + roleSnapshotRepository); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReaderGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReaderGuardTest.java new file mode 100644 index 0000000000..c4b11033d4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReaderGuardTest.java @@ -0,0 +1,188 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.security.KeyPairGenerator; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountStoredBareLoginRecoveryReaderGuardTest { + private static final String WORKLOAD_NAMESPACE = "account-unit"; + private static final AccountBareLoginExchangeIdentity IDENTITY = + new AccountBareLoginExchangeIdentity( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + 101L, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + "connect-scope-1", + "exchange-request-1"); + private static final byte[] REQUEST_DIGEST = new byte[32]; + + private AccountBareLoginExchangeRepository exchangeRepository; + private AccountJoinOperationRepository joinOperationRepository; + private AccountEnvelopeCrypto envelopeCrypto; + private AccountCommittedConnectSourceReader committedSourceReader; + private AccountStoredBareLoginRecoveryReader reader; + private GrpcPeerIdentity expectedGameSessionPeer; + + @BeforeEach + void setUp() throws Exception { + exchangeRepository = mock(AccountBareLoginExchangeRepository.class); + joinOperationRepository = mock(AccountJoinOperationRepository.class); + envelopeCrypto = mock(AccountEnvelopeCrypto.class); + committedSourceReader = mock(AccountCommittedConnectSourceReader.class); + expectedGameSessionPeer = peer(WORKLOAD_NAMESPACE, "game-session-service"); + var gatewayKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair().getPublic(); + reader = + new AccountStoredBareLoginRecoveryReader( + exchangeRepository, + joinOperationRepository, + envelopeCrypto, + committedSourceReader, + Map.of("gateway-test", gatewayKey), + WORKLOAD_NAMESPACE); + } + + @Test + void missingPeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + AdminAuthorizationException failure = + assertThrows( + AdminAuthorizationException.class, + () -> withoutPeer(() -> reader.readHistorical(IDENTITY, REQUEST_DIGEST.clone()))); + + assertEquals( + "Stored bare LOGIN history readback requires the exact Game Session workload identity", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + @Test + void bareLoginIdentityRequiresNonNilCanonicalTenantUuid() { + assertThrows( + IllegalArgumentException.class, + () -> + new AccountBareLoginExchangeIdentity( + IDENTITY.sourceConnectOperationId(), + IDENTITY.accountId(), + new UUID(0L, 0L), + "scope", + "request")); + } + + @Test + void wrongServiceOrNamespacePeerIsDeniedBeforeAnyInteraction() { + assertPeerDenied(peer(WORKLOAD_NAMESPACE, "account-service")); + assertPeerDenied(peer("other-account-unit", "game-session-service")); + } + + @Test + void exactPeerWithoutOwnerTransactionIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + withPeer( + expectedGameSessionPeer, + () -> reader.readHistorical(IDENTITY, REQUEST_DIGEST.clone()))); + + assertEquals( + "Stored bare LOGIN history readback requires an active owner transaction", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + @Test + void correlationRequiresExactPeerAndOwnerTransactionBeforeAnyCollaboratorInteraction() { + AccountConnectTokenIssuanceIdentity freshIdentity = + new AccountConnectTokenIssuanceIdentity( + IDENTITY.accountId(), IDENTITY.tenantId(), "fresh-connect-scope", "fresh-request"); + + AdminAuthorizationException peerFailure = + assertThrows( + AdminAuthorizationException.class, + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "account-service"), + () -> + reader.readCorrelation( + IDENTITY, REQUEST_DIGEST.clone(), freshIdentity, "signed-context"))); + assertEquals( + "Stored bare LOGIN history readback requires the exact Game Session workload identity", + peerFailure.getMessage()); + verifyNoCollaboratorInteractions(); + + IllegalStateException transactionFailure = + assertThrows( + IllegalStateException.class, + () -> + withPeer( + expectedGameSessionPeer, + () -> + reader.readCorrelation( + IDENTITY, REQUEST_DIGEST.clone(), freshIdentity, "signed-context"))); + assertEquals( + "Stored bare LOGIN history readback requires an active owner transaction", + transactionFailure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + private void assertPeerDenied(GrpcPeerIdentity peer) { + AdminAuthorizationException failure = + assertThrows( + AdminAuthorizationException.class, + () -> withPeer(peer, () -> reader.readHistorical(IDENTITY, REQUEST_DIGEST.clone()))); + + assertEquals( + "Stored bare LOGIN history readback requires the exact Game Session workload identity", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + private void verifyNoCollaboratorInteractions() { + verifyNoInteractions( + exchangeRepository, joinOperationRepository, envelopeCrypto, committedSourceReader); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context scoped = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = scoped.attach(); + try { + return action.get(); + } finally { + scoped.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java new file mode 100644 index 0000000000..b135f682d3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java @@ -0,0 +1,91 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.GameDesignFreshTenantIdentityClient; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.FreshTenantIdentityEnrollmentService; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionTemplate; + +class FreshTenantIdentityEnrollmentServiceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void ownerTransportFailureTouchesNoAccountRepositoryOrGenerationState() { + GameDesignFreshTenantIdentityClient client = mock(GameDesignFreshTenantIdentityClient.class); + FreshTenantIdentityAssociationRepository associations = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + TransactionTemplate transaction = mock(TransactionTemplate.class); + RuntimeException unavailable = new IllegalStateException("Game Design unavailable"); + when(client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)).thenThrow(unavailable); + + FreshTenantIdentityEnrollmentService service = + new FreshTenantIdentityEnrollmentService(client, associations, generations, transaction); + + assertThatThrownBy(() -> service.enroll(REQUEST_ID, REQUEST_DIGEST)).isSameAs(unavailable); + + verify(client).resolveCreation(REQUEST_ID, REQUEST_DIGEST); + verifyNoInteractions(associations, generations, transaction); + } + + @Test + void ownerOperationMismatchIsRejectedBeforeOpeningAccountTransaction() { + GameDesignFreshTenantIdentityClient client = mock(GameDesignFreshTenantIdentityClient.class); + FreshTenantIdentityAssociationRepository associations = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + TransactionTemplate transaction = mock(TransactionTemplate.class); + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence evidence = + evidence(UUID.fromString("22222222-2222-4222-8222-222222222222"), REQUEST_DIGEST); + when(client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)).thenReturn(evidence); + + FreshTenantIdentityEnrollmentService service = + new FreshTenantIdentityEnrollmentService(client, associations, generations, transaction); + + assertThatThrownBy(() -> service.enroll(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from the requested operation"); + + verify(client).resolveCreation(REQUEST_ID, REQUEST_DIGEST); + verifyNoInteractions(associations, generations, transaction); + } + + private static net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence evidence( + UUID creationRequestId, String requestDigest) { + UUID operationId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + UUID canonicalTenantId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + String sourceGameTenantKey = "game-tenant-key"; + String evidenceDigest = + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.evidenceDigest( + "account-service", + creationRequestId, + operationId, + requestDigest, + canonicalTenantId, + 17L, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( + 1, + "account-service", + creationRequestId, + operationId, + requestDigest, + canonicalTenantId, + 17L, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 5d5823af2c..d29aad1f3b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -78,7 +78,11 @@ class AccountGrpcServiceTest { private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; private static final String ACCOUNT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72001"; + private static final String OTHER_ACCOUNT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72003"; private static final String TENANT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72002"; + private static final String OTHER_TENANT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72004"; + private static final String PLAYABLE_NAMESPACE_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72005"; + private static final String GAME_INSTANCE_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72006"; private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; private static final GrpcPeerIdentity GAME_SESSION_PEER = new GrpcPeerIdentity( @@ -105,25 +109,39 @@ private static PlayerExecutionContext validPlayerContext() { } private static PlayerExecutionContext validRuntimeMembershipContext() { + return validRuntimeMembershipContext(ACCOUNT_UUID, TENANT_UUID); + } + + private static PlayerExecutionContext validRuntimeMembershipContext( + String accountUuid, String tenantUuid) { + return validRuntimeMembershipContext( + accountUuid, tenantUuid, PLAYABLE_NAMESPACE_UUID, GAME_INSTANCE_UUID); + } + + private static PlayerExecutionContext validRuntimeMembershipContext( + String accountUuid, + String tenantUuid, + String playableNamespaceUuid, + String gameInstanceUuid) { return PlayerExecutionContext.newBuilder() - .setAccountId("10") - .setTenantId("20") + .setAccountId(accountUuid) + .setTenantId(tenantUuid) .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateNamespaceId(playableNamespaceUuid) .setPlayableStateScope("SHARED") - .setGameInstanceId("40") + .setGameInstanceId(gameInstanceUuid) .setSessionId("50") .setRequestId("membership-read-1") .build(); } private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( - long requestAccountId, + String requestAccountUuid, boolean membershipExists, List checkpoints, List sourceEvidence) { return runtimeMembershipSnapshot( - requestAccountId, + requestAccountUuid, membershipExists, checkpoints, sourceEvidence, @@ -131,14 +149,14 @@ private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( } private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( - long requestAccountId, + String requestAccountUuid, boolean membershipExists, List checkpoints, List sourceEvidence, MembershipEvent sourceEvent) { return new RuntimeMembershipSnapshotDto( - requestAccountId, - 20L, + requestAccountUuid, + TENANT_UUID, ACCOUNT_UUID, TENANT_UUID, membershipExists, @@ -1984,7 +2002,10 @@ public void onCompleted() {} void encodeRuntimeMembershipCandidateEncodesCompleteActivePositiveSnapshot() { RuntimeMembershipSnapshotDto snapshot = runtimeMembershipSnapshot( - 10L, true, runtimeMembershipCheckpoints("1"), runtimeMembershipSourceEvidence()); + ACCOUNT_UUID, + true, + runtimeMembershipCheckpoints("1"), + runtimeMembershipSourceEvidence()); GetTenantMembershipForRuntimeResponse response = AccountGrpcService.encodeRuntimeMembershipCandidate( @@ -1992,8 +2013,8 @@ void encodeRuntimeMembershipCandidateEncodesCompleteActivePositiveSnapshot() { assertEquals(ACCOUNT_UUID, response.getAccountId()); assertEquals(TENANT_UUID, response.getTenantId()); - assertEquals("10", response.getRequestAccountId()); - assertEquals("20", response.getRequestTenantId()); + assertEquals(ACCOUNT_UUID, response.getRequestAccountId()); + assertEquals(TENANT_UUID, response.getRequestTenantId()); assertEquals("membership-read-1", response.getRequestId()); assertTrue(response.getMembershipExists()); assertTrue(response.getGameplayAdmissionAllowed()); @@ -2017,7 +2038,8 @@ void encodeRuntimeMembershipCandidateEncodesCompleteActivePositiveSnapshot() { @Test void encodeRuntimeMembershipCandidateEncodesNeverJoinedSequenceZeroSnapshot() { RuntimeMembershipSnapshotDto snapshot = - runtimeMembershipSnapshot(10L, false, runtimeMembershipCheckpoints("0"), List.of()); + runtimeMembershipSnapshot( + ACCOUNT_UUID, false, runtimeMembershipCheckpoints("0"), List.of()); GetTenantMembershipForRuntimeResponse response = AccountGrpcService.encodeRuntimeMembershipCandidate( @@ -2042,13 +2064,87 @@ void encodeRuntimeMembershipCandidateEncodesNeverJoinedSequenceZeroSnapshot() { void encodeRuntimeMembershipCandidateRejectsWrongCallerTarget() { RuntimeMembershipSnapshotDto snapshot = runtimeMembershipSnapshot( - 11L, true, runtimeMembershipCheckpoints("1"), runtimeMembershipSourceEvidence()); + ACCOUNT_UUID, + true, + runtimeMembershipCheckpoints("1"), + runtimeMembershipSourceEvidence()); + + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(OTHER_ACCOUNT_UUID, TENANT_UUID), snapshot)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(ACCOUNT_UUID, OTHER_TENANT_UUID), snapshot)); + } + + @Test + void encodeRuntimeMembershipCandidateRejectsNumericAndNoncanonicalUuidInputs() { + RuntimeMembershipSnapshotDto snapshot = + runtimeMembershipSnapshot( + ACCOUNT_UUID, + true, + runtimeMembershipCheckpoints("1"), + runtimeMembershipSourceEvidence()); assertThrows( IllegalArgumentException.class, () -> AccountGrpcService.encodeRuntimeMembershipCandidate( - validRuntimeMembershipContext(), snapshot)); + validRuntimeMembershipContext("10", TENANT_UUID), snapshot)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext("00000000-0000-0000-0000-000000000000", TENANT_UUID), + snapshot)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(ACCOUNT_UUID.toUpperCase(), TENANT_UUID), snapshot)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(ACCOUNT_UUID, "20"), snapshot)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext( + ACCOUNT_UUID, TENANT_UUID, "realm-state-30", GAME_INSTANCE_UUID), + snapshot)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext( + ACCOUNT_UUID, TENANT_UUID, PLAYABLE_NAMESPACE_UUID, "40"), + snapshot)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext( + ACCOUNT_UUID, + TENANT_UUID, + PLAYABLE_NAMESPACE_UUID.toUpperCase(), + GAME_INSTANCE_UUID), + snapshot)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext( + ACCOUNT_UUID, + TENANT_UUID, + PLAYABLE_NAMESPACE_UUID, + GAME_INSTANCE_UUID.toUpperCase()), + snapshot)); } @Test @@ -2056,7 +2152,7 @@ void encodeRuntimeMembershipCandidateRejectsIncompleteCheckpointOrSourceEvidence List completeCheckpoints = runtimeMembershipCheckpoints("1"); RuntimeMembershipSnapshotDto missingCheckpoint = runtimeMembershipSnapshot( - 10L, + ACCOUNT_UUID, true, completeCheckpoints.subList(0, completeCheckpoints.size() - 1), runtimeMembershipSourceEvidence()); @@ -2067,7 +2163,7 @@ void encodeRuntimeMembershipCandidateRejectsIncompleteCheckpointOrSourceEvidence validRuntimeMembershipContext(), missingCheckpoint)); assertThrows( IllegalArgumentException.class, - () -> runtimeMembershipSnapshot(10L, true, completeCheckpoints, List.of())); + () -> runtimeMembershipSnapshot(ACCOUNT_UUID, true, completeCheckpoints, List.of())); } @Test @@ -2104,7 +2200,7 @@ void runtimeMembershipSnapshotRejectsSourceEventContentThatDiffersFromSnapshot() IllegalArgumentException.class, () -> runtimeMembershipSnapshot( - 10L, + ACCOUNT_UUID, true, runtimeMembershipCheckpoints("1"), runtimeMembershipSourceEvidence(inconsistent), diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java new file mode 100644 index 0000000000..cb8925834d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ForwardingClientCall.SimpleForwardingClientCall; +import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; + +/** Rejects response content unless its TLS session proves one exact server workload URI. */ +public final class GrpcServerPeerIdentityClientInterceptor implements ClientInterceptor { + private final String expectedPeerUri; + + public GrpcServerPeerIdentityClientInterceptor(String expectedPeerUri) { + this.expectedPeerUri = + GrpcPeerIdentity.parseUri(expectedPeerUri) + .map(GrpcPeerIdentity::uri) + .filter(uri -> uri.equals(expectedPeerUri)) + .orElseThrow( + () -> new IllegalArgumentException("Exact server workload URI is required")); + } + + @Override + public ClientCall interceptCall( + MethodDescriptor method, CallOptions options, Channel next) { + ClientCall call = next.newCall(method, options); + return new SimpleForwardingClientCall<>(call) { + @Override + public void start(Listener listener, Metadata headers) { + super.start( + new SimpleForwardingClientCallListener<>(listener) { + private boolean verified; + private boolean closed; + + private boolean requireVerifiedPeer() { + if (closed) { + return false; + } + if (verified) { + return true; + } + verified = + GrpcPeerIdentity.fromSslSession( + call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .filter(peer -> expectedPeerUri.equals(peer.uri())) + .isPresent(); + if (!verified) { + closed = true; + listener.onClose( + Status.UNAUTHENTICATED.withDescription( + "Response lacks the exact authenticated server workload identity"), + new Metadata()); + call.cancel("Server workload identity mismatch", null); + } + return verified; + } + + @Override + public void onHeaders(Metadata responseHeaders) { + if (requireVerifiedPeer()) { + super.onHeaders(responseHeaders); + } + } + + @Override + public void onMessage(RespT message) { + if (requireVerifiedPeer()) { + super.onMessage(message); + } + } + + @Override + public void onClose(Status status, Metadata trailers) { + if (closed || (status.isOk() && !requireVerifiedPeer())) { + return; + } + closed = true; + super.onClose(status, trailers); + } + }, + headers); + } + }; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java new file mode 100644 index 0000000000..205007381c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java @@ -0,0 +1,147 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Canonical request and receipt digests for Game Design authored-world source evidence. */ +public final class AuthoredWorldSourceDigest { + private static final String REQUEST_DOMAIN = "game-design-authored-world-source-request/v1"; + private static final String RECEIPT_DOMAIN = "game-design-authored-world-source-receipt/v1"; + private static final Pattern CANONICAL_SLUG = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredWorldSourceDigest() {} + + public static String requestDigest( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return GameTenantCreationDigest.digest( + REQUEST_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName); + } + + public static String evidenceDigest( + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + requireNonNil(operationId, "operationId"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + validateSourceGameTenantKey(sourceGameTenantKey); + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V30".equals(provenanceKind)) { + throw new IllegalArgumentException("Authored-world source provenance kind is not recognized"); + } + return GameTenantCreationDigest.digest( + RECEIPT_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + operationId.toString(), + requestDigest, + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName, + Long.toString(sourceGameRowId), + sourceGameTenantKey, + provenanceKind); + } + + public static void validateReadSelector( + String targetNamespace, UUID canonicalTenantId, String worldSlug) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(worldSlug, "worldSlug"); + } + + private static void validateRequestTuple( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(registrationRequestId, "registrationRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(tenantSlug, "tenantSlug"); + validateSlug(worldSlug, "worldSlug"); + validateDisplayName(worldDisplayName); + } + + private static void validateSlug(String value, String label) { + Objects.requireNonNull(value, label); + int byteLength = GameTenantCreationDigest.utf8ByteLength(value); + if (byteLength == 0 || byteLength > 120 || !CANONICAL_SLUG.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical routing selector"); + } + } + + private static void validateDisplayName(String value) { + Objects.requireNonNull(value, "worldDisplayName"); + if (value.isBlank() || value.length() > 200 || value.codePointCount(0, value.length()) > 100) { + throw new IllegalArgumentException( + "worldDisplayName must be nonblank and contain at most 100 Unicode code points"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void validateSourceGameTenantKey(String value) { + Objects.requireNonNull(value, "sourceGameTenantKey"); + if (value.isBlank() || value.length() > 72 || value.codePointCount(0, value.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + 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/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java new file mode 100644 index 0000000000..c09fb7a277 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; + +/** Closed immutable Game Design evidence for one registered authored-world selector source. */ +public record AuthoredWorldSourceEvidence( + int schemaVersion, + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + + public AuthoredWorldSourceEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world source schema version"); + } + Objects.requireNonNull(requestDigest, "requestDigest"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + String expectedRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + if (!expectedRequestDigest.equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the registration tuple"); + } + Objects.requireNonNull(evidenceDigest, "evidenceDigest"); + if (!GameTenantCreationDigest.isDigest(evidenceDigest)) { + throw new IllegalArgumentException("evidenceDigest must be a lowercase SHA-256 digest"); + } + String expectedEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + if (!expectedEvidenceDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException("Evidence digest does not match the immutable tuple"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidence.java new file mode 100644 index 0000000000..5325d52498 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidence.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable evidence that Game Design created and read back one exact fresh tenant operation. */ +public record FreshTenantCreationEvidence( + int schemaVersion, + String targetNamespace, + UUID creationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public FreshTenantCreationEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported fresh tenant evidence schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(creationRequestId, "creationRequestId"); + requireNonNil(operationId, "operationId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); + if (sourceGameTenantKey.isBlank() + || sourceGameTenantKey.length() > 72 + || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey exceeds the owner key bounds"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + GameTenantCreationDigest.utf8ByteLength(sourceGameTenantKey); + if (!"NEW_GAME_ROW".equals(provenanceKind)) { + throw new IllegalArgumentException("Fresh tenant provenance must be NEW_GAME_ROW"); + } + Objects.requireNonNull(evidenceDigest, "evidenceDigest"); + String expectedEvidenceDigest = + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + if (!expectedEvidenceDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException("Evidence digest does not match the immutable 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/main/java/net/firedevops/firemud/common/tenant/GameTenantCreationDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameTenantCreationDigest.java new file mode 100644 index 0000000000..cfd301e66a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameTenantCreationDigest.java @@ -0,0 +1,140 @@ +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 length-framed digests for fresh Game Design tenant creation evidence. */ +public final class GameTenantCreationDigest { + private static final String REQUEST_DOMAIN = "game-design-tenant-creation-request/v1"; + private static final String RECEIPT_DOMAIN = "game-design-tenant-creation-receipt/v1"; + private static final String DIGEST_PREFIX = "sha256:"; + + private GameTenantCreationDigest() {} + + public static String requestDigest( + String targetNamespace, + UUID creationRequestId, + String sourceGameTenantKey, + String name, + String description) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(creationRequestId, "creationRequestId"); + Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); + Objects.requireNonNull(name, "name"); + return digest( + REQUEST_DOMAIN, + targetNamespace, + creationRequestId.toString(), + sourceGameTenantKey, + name, + description == null ? "absent" : "present", + description == null ? "" : description); + } + + public static String evidenceDigest( + String targetNamespace, + UUID creationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(creationRequestId, "creationRequestId"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + if (!"NEW_GAME_ROW".equals(provenanceKind)) { + throw new IllegalArgumentException("Fresh creation provenance must be NEW_GAME_ROW"); + } + if (!isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + return digest( + RECEIPT_DOMAIN, + targetNamespace, + creationRequestId.toString(), + operationId.toString(), + requestDigest, + canonicalTenantId.toString(), + Long.toString(sourceGameRowId), + sourceGameTenantKey, + provenanceKind); + } + + public static int utf8ByteLength(String value) { + Objects.requireNonNull(value, "value"); + int byteLength = 0; + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException("Creation inputs must contain valid Unicode"); + } + byteLength += 4; + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException("Creation inputs must contain valid Unicode"); + } else if (current <= 0x7f) { + byteLength++; + } else if (current <= 0x7ff) { + byteLength += 2; + } else { + byteLength += 3; + } + } + return byteLength; + } + + public static boolean isDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + 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, "value"); + 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("Creation inputs must contain valid Unicode", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java new file mode 100644 index 0000000000..a30b297b4b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.common.tenant; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable Game Design owner evidence for one persisted runtime tenant identity. */ +public record RuntimeTenantIdentityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int MAX_SOURCE_KEY_CODE_POINTS = 36; + private static final int MAX_SOURCE_KEY_UTF16_LENGTH = 72; + + public RuntimeTenantIdentityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported runtime tenant identity schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); + if (sourceGameTenantKey.isBlank() + || sourceGameTenantKey.length() > MAX_SOURCE_KEY_UTF16_LENGTH + || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) + > MAX_SOURCE_KEY_CODE_POINTS + || !StandardCharsets.UTF_8.newEncoder().canEncode(sourceGameTenantKey)) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V30".equals(provenanceKind)) { + throw new IllegalArgumentException("Runtime tenant provenance kind is not recognized"); + } + } + + 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/grpc/GrpcServerPeerIdentityClientInterceptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java new file mode 100644 index 0000000000..d9b08d7541 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java @@ -0,0 +1,206 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import javax.net.ssl.SSLSession; +import org.junit.jupiter.api.Test; + +class GrpcServerPeerIdentityClientInterceptorTest { + private static final String EXPECTED = "spiffe://firemud/ns/firemud/sa/game-design-service"; + + @Test + void deliversOnlyTheExactAuthenticatedServerResponse() throws Exception { + Fixture fixture = fixture(session(EXPECTED)); + fixture.call.listener.onHeaders(new Metadata()); + fixture.call.listener.onMessage("owner evidence"); + fixture.call.listener.onClose(Status.OK, new Metadata()); + assertThat(fixture.headers).hasSize(1); + assertThat(fixture.messages).containsExactly("owner evidence"); + assertThat(fixture.statuses).containsExactly(Status.OK); + assertThat(fixture.call.cancelled).isFalse(); + } + + @Test + void missingAmbiguousDifferentWorkloadOrNamespaceCannotDeliverHeadersOrContent() + throws Exception { + var sessions = new ArrayList(); + sessions.add(null); + sessions.add(session()); + sessions.add(session(EXPECTED, "spiffe://firemud/ns/firemud/sa/account-service")); + sessions.add(session("spiffe://firemud/ns/firemud/sa/account-service")); + sessions.add(session("spiffe://firemud/ns/other/sa/game-design-service")); + sessions.add(session("not-a-workload-identity")); + for (SSLSession session : sessions) { + Fixture fixture = fixture(session); + fixture.call.listener.onHeaders(new Metadata()); + fixture.call.listener.onMessage("untrusted evidence"); + fixture.call.listener.onClose(Status.OK, new Metadata()); + assertThat(fixture.headers).isEmpty(); + assertThat(fixture.messages).isEmpty(); + assertThat(fixture.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(fixture.call.cancelled).isTrue(); + } + } + + @Test + void contentWithoutHeadersStillRequiresExactPeer() throws Exception { + Fixture unverified = fixture(null); + unverified.call.listener.onMessage("unexpected content"); + assertThat(unverified.messages).isEmpty(); + assertThat(unverified.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + Fixture verified = fixture(session(EXPECTED)); + verified.call.listener.onMessage("owner evidence"); + assertThat(verified.messages).containsExactly("owner evidence"); + } + + @Test + void emptySuccessfulReplyCannotBypassPeerValidation() throws Exception { + Fixture fixture = fixture(null); + fixture.call.listener.onClose(Status.OK, new Metadata()); + assertThat(fixture.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(fixture.call.cancelled).isTrue(); + } + + @Test + void transportFailureRemainsUnavailableWithoutInventingAuthenticatedEvidence() throws Exception { + Fixture fixture = fixture(null); + fixture.call.listener.onClose(Status.UNAVAILABLE, new Metadata()); + assertThat(fixture.statuses).containsExactly(Status.UNAVAILABLE); + assertThat(fixture.headers).isEmpty(); + assertThat(fixture.messages).isEmpty(); + assertThat(fixture.call.cancelled).isFalse(); + } + + @Test + void unverifiedCertificateDeniesResponseWithoutThrowingIntoConsumer() throws Exception { + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()) + .thenThrow(new javax.net.ssl.SSLPeerUnverifiedException("no peer")); + Fixture fixture = fixture(session); + fixture.call.listener.onHeaders(new Metadata()); + fixture.call.listener.onClose(Status.OK, new Metadata()); + assertThat(fixture.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(fixture.messages).isEmpty(); + } + + @Test + void configuredIdentityMustBeOneExactCanonicalWorkloadUri() { + assertThatThrownBy(() -> new GrpcServerPeerIdentityClientInterceptor(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new GrpcServerPeerIdentityClientInterceptor("not-a-workload")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://FIREMUD/ns/firemud/sa/game-design-service")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SSLSession session(String... peerUris) throws Exception { + SSLSession session = mock(SSLSession.class); + X509Certificate certificate = mock(X509Certificate.class); + List> alternatives = new ArrayList<>(); + for (String uri : peerUris) { + alternatives.add(List.of(6, uri)); + } + when(certificate.getSubjectAlternativeNames()).thenReturn(alternatives); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + return session; + } + + private static Fixture fixture(SSLSession session) { + var fixture = new Fixture(); + fixture.call.attributes = + session == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + Channel channel = mock(Channel.class); + when(channel.newCall(null, CallOptions.DEFAULT)).thenReturn(fixture.call); + ClientCall intercepted = + new GrpcServerPeerIdentityClientInterceptor(EXPECTED) + .interceptCall(null, CallOptions.DEFAULT, channel); + intercepted.start( + new ClientCall.Listener<>() { + @Override + public void onHeaders(Metadata headers) { + fixture.headers.add(headers); + } + + @Override + public void onMessage(Object message) { + fixture.messages.add(message); + } + + @Override + public void onClose(Status status, Metadata trailers) { + fixture.statuses.add(status); + } + }, + new Metadata()); + return fixture; + } + + private static final class Fixture { + private final TestCall call = new TestCall(); + private final List headers = new ArrayList<>(); + private final List messages = new ArrayList<>(); + private final List statuses = new ArrayList<>(); + } + + private static final class TestCall extends ClientCall { + private Listener listener; + private Attributes attributes; + private boolean cancelled; + + @Override + public void start(Listener listener, Metadata headers) { + this.listener = listener; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public void request(int count) {} + + @Override + public void cancel(String message, Throwable cause) { + cancelled = true; + } + + @Override + public void halfClose() {} + + @Override + public void sendMessage(Object message) {} + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigestTest.java new file mode 100644 index 0000000000..8006b853ba --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigestTest.java @@ -0,0 +1,276 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AuthoredWorldSourceDigestTest { + private static final String NAMESPACE = "firemud"; + private static final UUID REGISTRATION_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String TENANT_SLUG = "north-star"; + private static final String WORLD_SLUG = "violet-wilds"; + private static final String DISPLAY_NAME = "Café 🐉"; + private static final long SOURCE_GAME_ROW_ID = 42L; + private static final String SOURCE_GAME_TENANT_KEY = "legacy-game-tenant-42"; + private static final String PROVENANCE = "RETAINED_GAME_V30"; + + @Test + void emitsFixedLengthFramedRequestAndReceiptVectorsForMultibyteDisplayName() { + String requestDigest = requestDigest(); + + assertThat(requestDigest) + .isEqualTo("sha256:2f2e50fd98aede5418d7b52b8c837e12b092edd4044624b4047d21123cb35ba3"); + assertThat( + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isEqualTo("sha256:847d6cce8840ef21e3c3e5507d24ed71f3ad8a847f33572d6fc7f9b51a4a127c"); + } + + @Test + void everyRequestAndReceiptFieldChangesItsDigest() { + String requestDigest = requestDigest(); + String evidenceDigest = + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + + assertThat( + AuthoredWorldSourceDigest.requestDigest( + "other", REGISTRATION_ID, TENANT_ID, TENANT_SLUG, WORLD_SLUG, DISPLAY_NAME)) + .isNotEqualTo(requestDigest); + assertThat( + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, UUID.randomUUID(), TENANT_ID, TENANT_SLUG, WORLD_SLUG, DISPLAY_NAME)) + .isNotEqualTo(requestDigest); + assertThat( + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_ID, + UUID.randomUUID(), + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME)) + .isNotEqualTo(requestDigest); + assertThat( + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT_ID, "south-star", WORLD_SLUG, DISPLAY_NAME)) + .isNotEqualTo(requestDigest); + assertThat( + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT_ID, TENANT_SLUG, "green-wilds", DISPLAY_NAME)) + .isNotEqualTo(requestDigest); + assertThat( + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT_ID, TENANT_SLUG, WORLD_SLUG, "Café 🐲")) + .isNotEqualTo(requestDigest); + + assertThat( + evidenceDigest( + "other", + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + UUID.randomUUID(), + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + UUID.randomUUID(), + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + "sha256:" + "a".repeat(64), + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + UUID.randomUUID(), + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + "south-star", + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + "green-wilds", + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "Café 🐲", + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID + 1, + SOURCE_GAME_TENANT_KEY, + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "another-game-key", + PROVENANCE)) + .isNotEqualTo(evidenceDigest); + assertThat( + evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW")) + .isNotEqualTo(evidenceDigest); + } + + private static String requestDigest() { + return AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT_ID, TENANT_SLUG, WORLD_SLUG, DISPLAY_NAME); + } + + private static String evidenceDigest( + String namespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String displayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + return AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java new file mode 100644 index 0000000000..6d2d39c325 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java @@ -0,0 +1,386 @@ +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 AuthoredWorldSourceEvidenceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID REGISTRATION_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String TENANT_SLUG = "north-star"; + private static final String WORLD_SLUG = "violet-wilds"; + private static final String DISPLAY_NAME = "Café 🐉"; + private static final long SOURCE_GAME_ROW_ID = 42L; + private static final String SOURCE_GAME_TENANT_KEY = "legacy-game-tenant-42"; + private static final String PROVENANCE = "RETAINED_GAME_V30"; + + @Test + void acceptsClosedNewAndRetainedSourceEvidenceAndRecomputesBothDigests() { + assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence("RETAINED_GAME_V30").provenanceKind()).isEqualTo("RETAINED_GAME_V30"); + } + + @Test + void acceptsMaximumSelectorBytesAndDisplayCodePoints() { + String maximumTenantSlug = "a".repeat(120); + String maximumWorldSlug = "b".repeat(120); + String maximumDisplayName = "é".repeat(100); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_ID, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + + assertThat( + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE, + evidenceDigest) + .worldDisplayName()) + .hasSize(100); + } + + @Test + void rejectsUnsupportedVersionMalformedIdentitySelectorsAndDisplayName() { + AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); + assertInvalid( + 2, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + "bad.namespace", + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + new UUID(0L, 0L), + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + new UUID(0L, 0L), + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + new UUID(0L, 0L), + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + "North-Star", + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + "a".repeat(121), + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + "bad_slug", + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + " ", + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "😀".repeat(101), + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "bad" + (char) 0xd800, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertThat(valid.worldDisplayName()).isEqualTo(DISPLAY_NAME); + } + + @Test + void rejectsChangedRequestReceiptSourceBoundsAndUnknownProvenance() { + AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); + assertThatThrownBy( + () -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + "sha256:" + "0".repeat(64), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Request digest"); + assertThatThrownBy( + () -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + "sha256:" + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Evidence digest"); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + 0L, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "x".repeat(37), + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "bad" + (char) 0xd800, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "OTHER"); + } + + private static AuthoredWorldSourceEvidence evidence(String provenanceKind) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT_ID, TENANT_SLUG, WORLD_SLUG, DISPLAY_NAME); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + provenanceKind, + evidenceDigest); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + assertThatThrownBy( + () -> { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + new AuthoredWorldSourceEvidence( + schemaVersion, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + }) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java new file mode 100644 index 0000000000..5e62a0a3e2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java @@ -0,0 +1,238 @@ +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 FreshTenantCreationEvidenceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + 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 String REQUEST_DIGEST = + "sha256:467cbe9641a3ad61d14969aece34b770629ae569641d69fb1aea6e3f1538a28a"; + private static final String SOURCE_KEY = "legacy-α"; + + @Test + void acceptsExactGoldenFreshTenantEvidence() { + FreshTenantCreationEvidence evidence = validEvidence(); + + assertThat(evidence.schemaVersion()).isEqualTo(1); + assertThat(evidence.targetNamespace()).isEqualTo("prod"); + assertThat(evidence.creationRequestId()).isEqualTo(REQUEST_ID); + assertThat(evidence.operationId()).isEqualTo(OPERATION_ID); + assertThat(evidence.requestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(evidence.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); + assertThat(evidence.sourceGameRowId()).isEqualTo(42L); + assertThat(evidence.sourceGameTenantKey()).isEqualTo(SOURCE_KEY); + assertThat(evidence.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence.evidenceDigest()) + .isEqualTo("sha256:533f0c6590aff359baa6bbaa1a4b9ab7cd6ebf68a3663ed6681053f5a8cc1955"); + } + + @Test + void rejectsUnsupportedSchemaNamespaceAndNilUuids() { + FreshTenantCreationEvidence valid = validEvidence(); + assertInvalid( + valid.schemaVersion() + 1, + valid.targetNamespace(), + valid.creationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + "prod.other", + valid.creationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + new UUID(0L, 0L), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + valid.creationRequestId(), + new UUID(0L, 0L), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + valid.creationRequestId(), + valid.operationId(), + valid.requestDigest(), + new UUID(0L, 0L), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest()); + } + + @Test + void rejectsMalformedDigestSourceKeyProvenanceAndChangedTupleDigest() { + FreshTenantCreationEvidence valid = validEvidence(); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + valid.creationRequestId(), + valid.operationId(), + "SHA256:" + "a".repeat(64), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + valid.creationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + 0L, + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + valid.creationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "bad" + (char) 0xd800, + valid.provenanceKind(), + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + valid.creationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "a".repeat(37), + valid.provenanceKind(), + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + valid.creationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + "RETAINED_GAME_V30", + valid.evidenceDigest()); + assertInvalid( + valid.schemaVersion(), + valid.targetNamespace(), + valid.creationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.sourceGameRowId() + 1, + valid.sourceGameTenantKey(), + valid.provenanceKind(), + "sha256:" + "d".repeat(64)); + } + + private static FreshTenantCreationEvidence validEvidence() { + return evidence( + 1, + "prod", + REQUEST_ID, + OPERATION_ID, + REQUEST_DIGEST, + CANONICAL_TENANT_ID, + 42L, + SOURCE_KEY, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + REQUEST_ID, + OPERATION_ID, + REQUEST_DIGEST, + CANONICAL_TENANT_ID, + 42L, + SOURCE_KEY, + "NEW_GAME_ROW")); + } + + private static void assertInvalid( + int schemaVersion, + String namespace, + UUID creationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) { + assertThatThrownBy( + () -> + evidence( + schemaVersion, + namespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static FreshTenantCreationEvidence evidence( + int schemaVersion, + String namespace, + UUID creationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) { + return new FreshTenantCreationEvidence( + schemaVersion, + namespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java new file mode 100644 index 0000000000..2c962a363f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java @@ -0,0 +1,121 @@ +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 RuntimeTenantIdentityEvidenceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void acceptsNewAndRetainedOwnerEvidence() { + assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence("RETAINED_GAME_V30").provenanceKind()).isEqualTo("RETAINED_GAME_V30"); + } + + @Test + void rejectsOpenOrIncompleteMetadataShapes() { + RuntimeTenantIdentityEvidence valid = evidence("NEW_GAME_ROW"); + assertInvalid( + 2, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + "test.invalid", + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + new UUID(0L, 0L), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + new UUID(0L, 0L), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + 0L, + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + " ", + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "x".repeat(37), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "invalid-" + (char) 0xd800, + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + "OTHER"); + } + + private static RuntimeTenantIdentityEvidence evidence(String provenanceKind) { + return new RuntimeTenantIdentityEvidence( + 1, "test", REQUEST_ID, TENANT_ID, 42L, "source-game-key-42", provenanceKind); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + assertThatThrownBy( + () -> + new RuntimeTenantIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java index 30766ff602..16965e5c3e 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java @@ -177,34 +177,65 @@ public static void requireVerifiedAccountSourceMatchesGatewayContext( Map context = verifiedGatewayContext.claims(); BigInteger verifiedAt = requirePositiveInteger(context, "verifiedAt"); - long gatewayVerifiedAt; try { - gatewayVerifiedAt = verifiedAt.longValueExact(); + long gatewayVerifiedAt = verifiedAt.longValueExact(); Instant originalVerificationTime = Instant.ofEpochSecond(gatewayVerifiedAt); validate(context, originalVerificationTime); - Map expected = - new LinkedHashMap<>( - projectVerifiedAccountGameplayConnectClaims( - verifiedSourceClaims, - gatewayVerifiedAt, - requireText(context, "gatewayRequestId"))); - - BigInteger latestPermittedExpiry = requirePositiveInteger(expected, "expiresAt"); - if (requirePositiveInteger(context, "expiresAt").compareTo(latestPermittedExpiry) > 0) { - throw invalid("Gateway context expiry extends beyond the Account source token"); - } - // Compare the complete registered projection, not a second field allowlist that could miss - // a future source-carried field. Only the independently shortened Gateway deadline differs. - expected.put("expiresAt", context.get("expiresAt")); - if (!expected.equals(context)) { - throw invalid("Gateway context does not exactly preserve the Account source evidence"); - } + requireSourceMatchesGatewayProjection(verifiedSourceClaims, context, gatewayVerifiedAt); + } catch (ArithmeticException | java.time.DateTimeException ex) { + throw invalid( + "Gateway context verification time is outside the supported epoch-second range"); + } + } + + /** + * Requires exact correspondence between already-verified Account gameplay-connect claims and a + * signature-verified historical Gateway assertion. This proves only that the signed historical + * assertion carried the complete registered projection of those source claims. Callers must + * independently verify the Account source signature/profile and must not treat this evidence as a + * current Gateway authorization or proof of current Account authority, registry state, or + * recovery eligibility. + */ + public static void requireVerifiedAccountSourceMatchesHistoricalGatewayEvidence( + Map verifiedSourceClaims, + HistoricalGatewayConnectEvidence historicalGatewayEvidence) { + if (historicalGatewayEvidence == null) { + throw invalid("historical Gateway evidence is required"); + } + + Map context = historicalGatewayEvidence.claims(); + BigInteger verifiedAt = requirePositiveInteger(context, "verifiedAt"); + try { + long gatewayVerifiedAt = verifiedAt.longValueExact(); + Instant.ofEpochSecond(gatewayVerifiedAt); + validateShapeAndTimeGeometry(context); + validateSupportedTimestampRange(context); + requireSourceMatchesGatewayProjection(verifiedSourceClaims, context, gatewayVerifiedAt); } catch (ArithmeticException | java.time.DateTimeException ex) { throw invalid( "Gateway context verification time is outside the supported epoch-second range"); } } + private static void requireSourceMatchesGatewayProjection( + Map verifiedSourceClaims, Map context, long gatewayVerifiedAt) { + Map expected = + new LinkedHashMap<>( + projectVerifiedAccountGameplayConnectClaims( + verifiedSourceClaims, gatewayVerifiedAt, requireText(context, "gatewayRequestId"))); + + BigInteger latestPermittedExpiry = requirePositiveInteger(expected, "expiresAt"); + if (requirePositiveInteger(context, "expiresAt").compareTo(latestPermittedExpiry) > 0) { + throw invalid("Gateway context expiry extends beyond the Account source token"); + } + // Compare the complete registered projection, not a second field allowlist that could miss a + // future source-carried field. Only the independently shortened Gateway deadline differs. + expected.put("expiresAt", context.get("expiresAt")); + if (!expected.equals(context)) { + throw invalid("Gateway context does not exactly preserve the Account source evidence"); + } + } + /** * Verifies a compact Gateway Ed25519 JWS, then validates its complete semantic schema and time * window. Expiration has no skew grace: skew cannot extend the signed lifetime. @@ -223,6 +254,25 @@ public static GatewayConnectContext verifyAndDecode( return new GatewayConnectContext(signedEnvelope, verified.payload(), verified.kid(), claims); } + /** + * Verifies and validates an expired Gateway assertion solely as immutable historical evidence. + * The result is a distinct type and is not accepted by current-context consumers. This method + * does not establish that Gateway actually observed or accepted the assertion at its signed + * times, verify the Account source signature, or establish any current authority or recovery + * eligibility. + */ + public static HistoricalGatewayConnectEvidence verifyHistoricalEvidence( + String signedEnvelope, + Map gatewayVerificationKeys) { + GatewayConnectContextSignature.VerifiedContext verified = + GatewayConnectContextSignature.verify(signedEnvelope, gatewayVerificationKeys); + Map claims = parsePayload(verified.payload()); + validateShapeAndTimeGeometry(claims); + validateSupportedTimestampRange(claims); + return new HistoricalGatewayConnectEvidence( + signedEnvelope, verified.payload(), verified.kid(), claims); + } + /** * Computes the Gateway assertion deadline without changing the Account-issued time anchor. The * caller must reject an already-expired source token; no configured skew is added here. @@ -274,6 +324,25 @@ private static Map parsePayload(byte[] payload) { } private static void validate(Map claims, Instant now) { + validateShapeAndTimeGeometry(claims); + + BigInteger issuedAt = requirePositiveInteger(claims, "issuedAt"); + BigInteger verifiedAt = requirePositiveInteger(claims, "verifiedAt"); + BigInteger expiresAt = requirePositiveInteger(claims, "expiresAt"); + BigInteger nowSeconds = BigInteger.valueOf(now.getEpochSecond()); + BigInteger latestAllowedVerification = + nowSeconds.add(BigInteger.valueOf(MAX_CLOCK_SKEW_SECONDS)); + if (verifiedAt.compareTo(latestAllowedVerification) > 0 + || issuedAt.compareTo(latestAllowedVerification) > 0) { + throw invalid("Gateway context time is too far in the future"); + } + if (expiresAt.compareTo(nowSeconds) <= 0) { + throw invalid("Gateway context is expired"); + } + validateSupportedTimestampRange(claims); + } + + private static void validateShapeAndTimeGeometry(Map claims) { Set allowed = new java.util.HashSet<>(REQUIRED_FIELDS); allowed.addAll(CONDITIONAL_FIELDS); if (!allowed.containsAll(claims.keySet()) || !claims.keySet().containsAll(REQUIRED_FIELDS)) { @@ -332,20 +401,13 @@ private static void validate(Map claims, Instant now) { > 0) { throw invalid("Gateway context verification time is outside its signed lifetime"); } - BigInteger nowSeconds = BigInteger.valueOf(now.getEpochSecond()); - BigInteger latestAllowedVerification = - nowSeconds.add(BigInteger.valueOf(MAX_CLOCK_SKEW_SECONDS)); - if (verifiedAt.compareTo(latestAllowedVerification) > 0 - || issuedAt.compareTo(latestAllowedVerification) > 0) { - throw invalid("Gateway context time is too far in the future"); - } - if (expiresAt.compareTo(nowSeconds) <= 0) { - throw invalid("Gateway context is expired"); - } + } + + private static void validateSupportedTimestampRange(Map claims) { try { - Instant.ofEpochSecond(issuedAt.longValueExact()); - Instant.ofEpochSecond(verifiedAt.longValueExact()); - Instant.ofEpochSecond(expiresAt.longValueExact()); + Instant.ofEpochSecond(requirePositiveInteger(claims, "issuedAt").longValueExact()); + Instant.ofEpochSecond(requirePositiveInteger(claims, "verifiedAt").longValueExact()); + Instant.ofEpochSecond(requirePositiveInteger(claims, "expiresAt").longValueExact()); } catch (ArithmeticException | java.time.DateTimeException ex) { throw invalid("Gateway context time is outside the supported epoch-second range"); } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/HistoricalGatewayConnectEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/HistoricalGatewayConnectEvidence.java new file mode 100644 index 0000000000..712c20a0d8 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/HistoricalGatewayConnectEvidence.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.common.security; + +import java.math.BigInteger; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** + * Immutable proof material for a previously signed Gateway assertion. + * + *

This is deliberately not a {@link GatewayConnectContext}: expired evidence cannot be passed to + * APIs that require a currently valid Gateway context. The original envelope and payload are + * retained exactly for a later exact encrypted-original readback. This type establishes neither + * source issuance nor current authorization, and must not be logged with its retained payload. + */ +public final class HistoricalGatewayConnectEvidence { + private final String signedEnvelope; + private final byte[] signedPayload; + private final String kid; + private final Map claims; + + HistoricalGatewayConnectEvidence( + String signedEnvelope, byte[] signedPayload, String kid, Map claims) { + this.signedEnvelope = Objects.requireNonNull(signedEnvelope, "signed envelope is required"); + this.signedPayload = + Objects.requireNonNull(signedPayload, "signed payload is required").clone(); + this.kid = Objects.requireNonNull(kid, "Gateway key identifier is required"); + this.claims = immutableObject(claims); + } + + /** Returns the exact compact JWS that was verified. */ + public String signedEnvelope() { + return signedEnvelope; + } + + /** Returns a defensive copy of the exact signed UTF-8 payload bytes. */ + public byte[] signedPayload() { + return signedPayload.clone(); + } + + public String kid() { + return kid; + } + + /** Returns an immutable, recursively copied view of every accepted payload field. */ + public Map claims() { + return immutableObject(claims); + } + + public String text(String name) { + Object value = claims.get(name); + return value instanceof String text ? text : null; + } + + public BigInteger integer(String name) { + Object value = claims.get(name); + return value instanceof BigInteger integer ? integer : null; + } + + @Override + public String toString() { + return "HistoricalGatewayConnectEvidence[kid=" + kid + ", historical=true]"; + } + + private static Map immutableObject(Map source) { + Objects.requireNonNull(source, "context claims are required"); + 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 typed = new LinkedHashMap<>(); + map.forEach( + (key, nested) -> { + if (!(key instanceof String text)) { + throw new IllegalArgumentException("context object keys must be strings"); + } + typed.put(text, immutableValue(nested)); + }); + return Collections.unmodifiableMap(typed); + } + if (value instanceof java.util.List list) { + return list.stream().map(HistoricalGatewayConnectEvidence::immutableValue).toList(); + } + if (value instanceof String + || value instanceof Boolean + || value instanceof BigInteger + || value == null) { + return value; + } + throw new IllegalArgumentException("unsupported decoded context value type"); + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java index 43826a1f2b..c75d16bca2 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java @@ -2,6 +2,7 @@ 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -21,6 +22,7 @@ import net.firedevops.firemud.common.security.GatewayConnectContext; import net.firedevops.firemud.common.security.GatewayConnectContextCodec; import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; import net.firedevops.firemud.test.SelectedTargetConnectContextTestVectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -547,6 +549,138 @@ void rejectsMillisecondTimesExpiredContextAndClockSkewLifetimeExtension() throws assertRejected(extendsLifetimeWithSkew); } + @Test + void verifiesExpiredAssertionOnlyAsExactImmutableHistoricalEvidence() throws Exception { + Map source = historicalSource(); + Map claims = historicalContext(source); + byte[] payload = json.writeValueAsBytes(claims); + String envelope = GatewayConnectContextSignature.sign(payload, KID, keyPair.getPrivate()); + + HistoricalGatewayConnectEvidence evidence = verifyHistorical(envelope); + + assertEquals(envelope, evidence.signedEnvelope()); + assertArrayEquals(payload, evidence.signedPayload()); + assertEquals(KID, evidence.kid()); + assertEquals(claims, evidence.claims()); + assertEquals(BigInteger.valueOf(NOW.getEpochSecond() - 100L), evidence.integer("issuedAt")); + assertTrue(evidence.integer("expiresAt").longValueExact() < NOW.getEpochSecond()); + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesHistoricalGatewayEvidence( + source, evidence); + + byte[] exposedPayload = evidence.signedPayload(); + exposedPayload[0] ^= 1; + assertArrayEquals(payload, evidence.signedPayload()); + assertThrows( + UnsupportedOperationException.class, () -> evidence.claims().put("audience", "other")); + @SuppressWarnings("unchecked") + Map authorityTuple = + (Map) evidence.claims().get("authorityTuple"); + assertThrows( + UnsupportedOperationException.class, + () -> authorityTuple.put("accountAuthorityGeneration", BigInteger.ZERO)); + assertFalse(evidence.toString().contains(envelope)); + assertFalse(evidence.toString().contains(new String(payload, StandardCharsets.UTF_8))); + + // This is the same old, validly signed assertion: the ordinary reader remains strict. + assertThrows(IllegalArgumentException.class, () -> verify(envelope)); + } + + @Test + void historicalEvidenceRejectsUnknownKeyAndForgedSignatureBeforePayloadInterpretation() + throws Exception { + String malformedJsonEnvelope = + GatewayConnectContextSignature.sign( + "{".getBytes(StandardCharsets.UTF_8), KID, keyPair.getPrivate()); + IllegalArgumentException unknownKey = + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.verifyHistoricalEvidence( + malformedJsonEnvelope, Map.of("another-key", keyPair.getPublic()))); + assertEquals("unknown Gateway verification key", unknownKey.getMessage()); + + // A different valid signing key gives a well-formed, wrong-key signature. Flipping a + // compressed-point byte can instead fail in the provider's point decoder. + KeyPair wrongKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + String forgedMalformedJsonEnvelope = + GatewayConnectContextSignature.sign( + "{".getBytes(StandardCharsets.UTF_8), KID, wrongKeyPair.getPrivate()); + IllegalArgumentException invalidSignature = + assertThrows( + IllegalArgumentException.class, () -> verifyHistorical(forgedMalformedJsonEnvelope)); + assertEquals("invalid Gateway context signature", invalidSignature.getMessage()); + } + + @Test + void historicalEvidenceRejectsWrongReceiverAndOpenOrMalformedSchema() throws Exception { + Map wrongAudience = historicalContext(historicalSource()); + wrongAudience.put("audience", "account-service"); + assertHistoricalRejected(wrongAudience); + + Map wrongRecipient = historicalContext(historicalSource()); + wrongRecipient.put("recipient", "another-service"); + assertHistoricalRejected(wrongRecipient); + + Map missingField = historicalContext(historicalSource()); + missingField.remove("realmId"); + assertHistoricalRejected(missingField); + + Map extraField = historicalContext(historicalSource()); + extraField.put("legacyTenantKey", "42"); + assertHistoricalRejected(extraField); + + Map invalidTarget = historicalContext(historicalSource()); + invalidTarget.put("tenantId", "not-a-canonical-uuid"); + assertHistoricalRejected(invalidTarget); + } + + @Test + void historicalEvidenceRejectsInvalidOriginalTimestampAndLifetimeGeometry() throws Exception { + long issuedAt = NOW.getEpochSecond() - 100L; + + Map zeroLifetime = historicalContext(historicalSource()); + zeroLifetime.put("expiresAt", BigInteger.valueOf(issuedAt)); + assertHistoricalRejected(zeroLifetime); + + Map excessiveLifetime = historicalContext(historicalSource()); + excessiveLifetime.put( + "expiresAt", + BigInteger.valueOf(issuedAt + GatewayConnectContextCodec.MAX_CONTEXT_LIFETIME_SECONDS + 1)); + assertHistoricalRejected(excessiveLifetime); + + Map verificationAtExpiry = historicalContext(historicalSource()); + verificationAtExpiry.put("verifiedAt", verificationAtExpiry.get("expiresAt")); + assertHistoricalRejected(verificationAtExpiry); + + Map excessiveFutureIssuedAt = historicalContext(historicalSource()); + excessiveFutureIssuedAt.put( + "issuedAt", + BigInteger.valueOf(issuedAt + GatewayConnectContextCodec.MAX_CLOCK_SKEW_SECONDS + 2)); + assertHistoricalRejected(excessiveFutureIssuedAt); + + Map unsupportedEpoch = historicalContext(historicalSource()); + BigInteger outsideInstantRange = new BigInteger("1000000000000000000000000"); + unsupportedEpoch.put("issuedAt", outsideInstantRange); + unsupportedEpoch.put("verifiedAt", outsideInstantRange); + unsupportedEpoch.put("expiresAt", outsideInstantRange.add(BigInteger.TEN)); + assertHistoricalRejected(unsupportedEpoch); + } + + @Test + void historicalSourceCorrespondenceRejectsChangedSourceAndSelectedTarget() throws Exception { + Map source = historicalSource(); + HistoricalGatewayConnectEvidence original = verifyHistorical(sign(historicalContext(source))); + + Map changedSource = historicalSource(); + changedSource.put("connectScopeId", "different-original-source-scope"); + assertHistoricalSourceMismatch(changedSource, original); + + Map changedTarget = historicalContext(source); + changedTarget.put("realmId", "018f8f0a-8c1d-7f9a-ad6a-bf4a312c0d8e"); + HistoricalGatewayConnectEvidence changedTargetEvidence = verifyHistorical(sign(changedTarget)); + assertHistoricalSourceMismatch(source, changedTargetEvidence); + } + @Test void rejectsUnknownGatewayKeyAndWrongSignature() throws Exception { String envelope = sign(validContext()); @@ -597,6 +731,11 @@ private GatewayConnectContext verify(String envelope) { envelope, Map.of(KID, keyPair.getPublic()), clock); } + private HistoricalGatewayConnectEvidence verifyHistorical(String envelope) { + return GatewayConnectContextCodec.verifyHistoricalEvidence( + envelope, Map.of(KID, keyPair.getPublic())); + } + private String sign(Map claims) throws Exception { return GatewayConnectContextSignature.sign( json.writeValueAsBytes(claims), KID, keyPair.getPrivate()); @@ -606,6 +745,10 @@ private void assertRejected(Map claims) throws Exception { assertThrows(IllegalArgumentException.class, () -> verify(sign(claims))); } + private void assertHistoricalRejected(Map claims) throws Exception { + assertThrows(IllegalArgumentException.class, () -> verifyHistorical(sign(claims))); + } + private void assertSourceMismatch( Map sourceClaims, GatewayConnectContext verifiedContext) { assertThrows( @@ -615,6 +758,15 @@ private void assertSourceMismatch( sourceClaims, verifiedContext)); } + private void assertHistoricalSourceMismatch( + Map sourceClaims, HistoricalGatewayConnectEvidence historicalEvidence) { + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesHistoricalGatewayEvidence( + sourceClaims, historicalEvidence)); + } + private static BigInteger nested( Map claims, String object, String nestedObject, String key) { @SuppressWarnings("unchecked") @@ -634,6 +786,19 @@ private static Map validContext() { return projectContext(SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims()); } + private static Map historicalSource() { + Map source = SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + long issuedAt = NOW.getEpochSecond() - 100L; + source.put("iat", BigInteger.valueOf(issuedAt)); + source.put("exp", BigInteger.valueOf(issuedAt + 20L)); + return source; + } + + private static Map historicalContext(Map source) { + long issuedAt = ((BigInteger) source.get("iat")).longValueExact(); + return projectContext(source, issuedAt + 1L); + } + private static Map projectContext(Map source) { return projectContext(source, SelectedTargetConnectContextTestVectors.GATEWAY_VERIFIED_AT); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java new file mode 100644 index 0000000000..7507fa590d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java @@ -0,0 +1,451 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local immutable selector-source registration and exact committed readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class GameAuthoredWorldSourceRepository { + private static final int SCHEMA_VERSION = 1; + private static final String NEW_GAME_ROW = "NEW_GAME_ROW"; + private static final String RETAINED_GAME_V30 = "RETAINED_GAME_V30"; + + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field GAME_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + private static final Table TENANT_SLUG_BINDING = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Field BINDING_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field BINDING_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field BINDING_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field BINDING_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + + private static final Table OPERATION = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field OPERATION_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field OPERATION_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); + private final DSLContext dsl; + + public GameAuthoredWorldSourceRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * Binds explicit authored-world selectors to one exact persisted Game Design tenant source. + * + *

The caller must own the encompassing Game Design transaction. The actual source game row is + * locked before request replay checks and selector claims, serializing registrations for one + * tenant without treating a template, display name, or legacy key as a selector. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AuthoredWorldSourceEvidence register( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + requireActiveOwnerTransaction(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + + GameSource source = lockGameSource(canonicalTenantId); + if (source == null) { + throw new RegistrationConflictException("Canonical tenant source game row is missing"); + } + requireConsistentGameSource(source); + + Record existingRequest = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (existingRequest != null) { + AuthoredWorldSourceEvidence receipt = toEvidence(existingRequest); + if (!requestDigest.equals(receipt.requestDigest()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !tenantSlug.equals(receipt.tenantSlug()) + || !worldSlug.equals(receipt.worldSlug()) + || !worldDisplayName.equals(receipt.worldDisplayName())) { + throw new RegistrationConflictException( + "Authored-world registration identity was reused with changed input"); + } + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + return receipt; + } + + ensureTenantSlugBinding(targetNamespace, tenantSlug, source); + UUID operationId = UUID.randomUUID(); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + source.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + + int inserted = + dsl.insertInto(OPERATION) + .set(OPERATION_ID, operationId) + .set(OPERATION_SCHEMA_VERSION, SCHEMA_VERSION) + .set(OPERATION_NAMESPACE, targetNamespace) + .set(REGISTRATION_REQUEST_ID, registrationRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(TENANT_SLUG, tenantSlug) + .set(WORLD_SLUG, worldSlug) + .set(WORLD_DISPLAY_NAME, worldDisplayName) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(PROVENANCE_KIND, source.provenanceKind()) + .set(EVIDENCE_DIGEST, evidenceDigest) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record requestConflict = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (requestConflict != null) { + throw new RegistrationConflictException( + "Authored-world registration identity was reused with changed input"); + } + Record selectorConflict = findByWorldSelector(targetNamespace, canonicalTenantId, worldSlug); + if (selectorConflict != null) { + throw new RegistrationConflictException( + "Authored-world selector is already owned by another source operation"); + } + throw new RegistrationConflictException( + "Authored-world source operation conflicts with an existing owner claim"); + } + + Record persisted = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (persisted == null) { + throw new IllegalStateException("Committed authored-world source operation is missing"); + } + AuthoredWorldSourceEvidence receipt = toEvidence(persisted); + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + return receipt; + } + + /** Reads one exact committed source operation without allocating or repairing selector state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID operationId, UUID canonicalTenantId, String worldSlug, String targetNamespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + if (operationId == null || operationId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("operationId must be a canonical non-nil UUID"); + } + Record record = + dsl.selectFrom(OPERATION) + .where( + OPERATION_ID + .eq(operationId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(OPERATION_NAMESPACE.eq(targetNamespace))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + AuthoredWorldSourceEvidence receipt = toEvidence(record); + GameSource source = findGameSourceByRow(receipt.sourceGameRowId()); + if (source == null) { + throw new InvalidSourceEvidenceException("Authored-world source row is missing"); + } + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + return Optional.of(receipt); + } + + private void ensureTenantSlugBinding( + String targetNamespace, String tenantSlug, GameSource source) { + Record existing = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(targetNamespace) + .and(BINDING_CANONICAL_TENANT_ID.eq(source.canonicalTenantId()))) + .fetchOne(); + if (existing != null) { + requireMatchingBinding(existing, targetNamespace, tenantSlug, source); + return; + } + + int inserted = + dsl.insertInto(TENANT_SLUG_BINDING) + .set(BINDING_NAMESPACE, targetNamespace) + .set(BINDING_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(BINDING_TENANT_SLUG, tenantSlug) + .set(BINDING_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(BINDING_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(BINDING_PROVENANCE_KIND, source.provenanceKind()) + .onConflictDoNothing() + .execute(); + if (inserted == 1) { + return; + } + + Record tenantBinding = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(targetNamespace) + .and(BINDING_CANONICAL_TENANT_ID.eq(source.canonicalTenantId()))) + .fetchOne(); + if (tenantBinding != null) { + requireMatchingBinding(tenantBinding, targetNamespace, tenantSlug, source); + return; + } + Record slugOwner = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where(BINDING_NAMESPACE.eq(targetNamespace).and(BINDING_TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + if (slugOwner != null) { + throw new RegistrationConflictException( + "Tenant selector is already owned by another canonical tenant"); + } + throw new RegistrationConflictException( + "Tenant selector binding conflicts with an owner claim"); + } + + private void requireTenantBinding(AuthoredWorldSourceEvidence receipt) { + Record binding = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(receipt.targetNamespace()) + .and(BINDING_CANONICAL_TENANT_ID.eq(receipt.canonicalTenantId()))) + .fetchOne(); + if (binding == null) { + throw new InvalidSourceEvidenceException("Tenant selector binding is missing"); + } + requireMatchingBinding( + binding, + receipt.targetNamespace(), + receipt.tenantSlug(), + new GameSource( + receipt.sourceGameRowId(), + receipt.canonicalTenantId(), + receipt.sourceGameTenantKey(), + receipt.provenanceKind())); + } + + private void requireMatchingBinding( + Record binding, String targetNamespace, String tenantSlug, GameSource source) { + if (!targetNamespace.equals(binding.get(BINDING_NAMESPACE)) + || !source.canonicalTenantId().equals(binding.get(BINDING_CANONICAL_TENANT_ID)) + || !tenantSlug.equals(binding.get(BINDING_TENANT_SLUG)) + || source.sourceGameRowId() != binding.get(BINDING_SOURCE_GAME_ROW_ID) + || !source.sourceGameTenantKey().equals(binding.get(BINDING_SOURCE_GAME_TENANT_KEY)) + || !source.provenanceKind().equals(binding.get(BINDING_PROVENANCE_KIND))) { + throw new RegistrationConflictException( + "Canonical tenant already has a different stable tenant selector or source tuple"); + } + } + + private Record findByRegistrationRequest(String targetNamespace, UUID registrationRequestId) { + return dsl.selectFrom(OPERATION) + .where( + OPERATION_NAMESPACE + .eq(targetNamespace) + .and(REGISTRATION_REQUEST_ID.eq(registrationRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector( + String targetNamespace, UUID canonicalTenantId, String worldSlug) { + return dsl.selectFrom(OPERATION) + .where( + OPERATION_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private GameSource lockGameSource(UUID canonicalTenantId) { + Record row = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .forUpdate() + .fetchOne(); + return row == null ? null : gameSource(row); + } + + private GameSource findGameSourceByRow(long sourceGameRowId) { + Record row = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_ID.eq(sourceGameRowId)) + .fetchOne(); + return row == null ? null : gameSource(row); + } + + private GameSource gameSource(Record row) { + Long id = row.get(GAME_ID); + String tenantKey = row.get(GAME_TENANT_ID); + UUID canonicalTenantId = row.get(GAME_CANONICAL_TENANT_ID); + String provenanceKind = row.get(GAME_PROVENANCE_KIND); + Long provenanceRowId = row.get(GAME_SOURCE_ROW_ID); + String provenanceTenantKey = row.get(GAME_SOURCE_TENANT_KEY); + if (id == null + || tenantKey == null + || canonicalTenantId == null + || provenanceKind == null + || provenanceRowId == null + || provenanceTenantKey == null + || !id.equals(provenanceRowId) + || !tenantKey.equals(provenanceTenantKey)) { + throw new InvalidSourceEvidenceException( + "Game Design tenant source provenance does not match its game row"); + } + return new GameSource(id, canonicalTenantId, tenantKey, provenanceKind); + } + + private void requireConsistentGameSource(GameSource source) { + if (!NEW_GAME_ROW.equals(source.provenanceKind()) + && !RETAINED_GAME_V30.equals(source.provenanceKind())) { + throw new InvalidSourceEvidenceException("Game Design tenant provenance is not recognized"); + } + } + + private void requireReceiptSource(AuthoredWorldSourceEvidence receipt, GameSource source) { + if (receipt.sourceGameRowId() != source.sourceGameRowId() + || !receipt.canonicalTenantId().equals(source.canonicalTenantId()) + || !receipt.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !receipt.provenanceKind().equals(source.provenanceKind())) { + throw new InvalidSourceEvidenceException( + "Authored-world source tuple no longer matches its Game Design row"); + } + } + + private AuthoredWorldSourceEvidence toEvidence(Record row) { + try { + return new AuthoredWorldSourceEvidence( + row.get(OPERATION_SCHEMA_VERSION), + row.get(OPERATION_NAMESPACE), + row.get(REGISTRATION_REQUEST_ID), + row.get(OPERATION_ID), + row.get(REQUEST_DIGEST), + row.get(CANONICAL_TENANT_ID), + row.get(TENANT_SLUG), + row.get(WORLD_SLUG), + row.get(WORLD_DISPLAY_NAME), + row.get(SOURCE_GAME_ROW_ID), + row.get(SOURCE_GAME_TENANT_KEY), + row.get(PROVENANCE_KIND), + row.get(EVIDENCE_DIGEST)); + } catch (RuntimeException exception) { + throw new InvalidSourceEvidenceException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source registration requires an active Game Design owner transaction"); + } + } + + private record GameSource( + long sourceGameRowId, + UUID canonicalTenantId, + String sourceGameTenantKey, + String provenanceKind) {} + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidSourceEvidenceException extends IllegalStateException { + public InvalidSourceEvidenceException(String message) { + super(message); + } + + public InvalidSourceEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java index 94e35866c9..c911e08d48 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java @@ -125,6 +125,24 @@ public Optional findTenantIdentityByLegacyTenantId(String le .fetchOptional(record -> toTenantIdentity(record, legacyTenantId)); } + /** Reads one persisted tenant UUID and verifies its provenance against the actual owner row. */ + public Optional findRuntimeTenantIdentityByCanonicalTenantId( + UUID canonicalTenantId) { + if (canonicalTenantId == null) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + return dsl.select( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID) + .from(GAME_TABLE) + .where(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .fetchOptional(this::toRuntimeTenantIdentity); + } + public Game findByTenantIdForUpdate(String tenantId) { return dsl.selectFrom(GAME_TABLE) .where(TENANT_ID.eq(tenantId)) @@ -174,4 +192,36 @@ private GameTenantIdentity toTenantIdentity(Record record, String expectedLegacy return new GameTenantIdentity( canonicalTenantId, provenanceKind, sourceGameId, sourceLegacyTenantId); } + + private GameTenantIdentity toRuntimeTenantIdentity(Record record) { + Long actualGameId = record.get(ID); + String actualTenantKey = record.get(TENANT_ID); + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); + String provenanceKindValue = record.get(TENANT_IDENTITY_PROVENANCE_KIND); + Long sourceGameId = record.get(TENANT_IDENTITY_SOURCE_GAME_ID); + String sourceTenantKey = record.get(TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID); + if (actualGameId == null + || actualGameId <= 0 + || actualTenantKey == null + || actualTenantKey.isBlank() + || canonicalTenantId == null + || provenanceKindValue == null + || sourceGameId == null + || sourceGameId <= 0 + || sourceTenantKey == null + || !actualGameId.equals(sourceGameId) + || !actualTenantKey.equals(sourceTenantKey)) { + throw new IllegalStateException( + "Persisted runtime tenant identity provenance does not match its game row"); + } + + GameTenantIdentity.ProvenanceKind provenanceKind; + try { + provenanceKind = GameTenantIdentity.ProvenanceKind.valueOf(provenanceKindValue); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Persisted runtime tenant identity provenance kind is unknown", exception); + } + return new GameTenantIdentity(canonicalTenantId, provenanceKind, actualGameId, actualTenantKey); + } } 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 new file mode 100644 index 0000000000..4425e3be94 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java @@ -0,0 +1,426 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.entity.Game; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local persistence for immutable fresh Game Design tenant creation operations. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected jOOQ and repository collaborators are internal Spring components.") +public class GameTenantCreationRepository { + private static final int SCHEMA_VERSION = 1; + private static final String COMPLETED = "COMPLETED"; + private static final String PENDING = "PENDING"; + private static final String NEW_GAME_ROW = "NEW_GAME_ROW"; + 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 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); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CREATION_REQUEST_ID = + DSL.field(DSL.name("creation_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field NAME = DSL.field(DSL.name("name"), String.class); + private static final Field DESCRIPTION = DSL.field(DSL.name("description"), String.class); + private static final Field STATUS = DSL.field(DSL.name("status"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); + + private final DSLContext dsl; + private final GameRepository gameRepository; + + public GameTenantCreationRepository(DSLContext dsl, GameRepository gameRepository) { + this.dsl = dsl; + this.gameRepository = gameRepository; + } + + /** + * Claims and completes a fresh tenant operation in the caller's owner transaction. + * + *

The runtime transaction check protects direct construction as well as Spring-proxied use; + * the database's deferred completion trigger also prevents a claim-only transaction from + * committing. + */ + @Transactional(propagation = Propagation.MANDATORY) + public FreshTenantCreationEvidence createCandidate( + String targetNamespace, + UUID creationRequestId, + String sourceGameTenantKey, + String name, + String description) { + 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) + .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"); + } + return toReceipt(existing); + } + + 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"); + } + return toReceipt(completedRecord); + } + + /** Reads only a complete operation whose persisted source tuple still matches its game row. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID creationRequestId, String targetNamespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Fresh tenant creation read requires a committed-outcome owner read"); + } + validateSelector(targetNamespace, creationRequestId); + Record record = + dsl.selectFrom(OPERATION_TABLE) + .where( + TARGET_NAMESPACE.eq(targetNamespace).and(CREATION_REQUEST_ID.eq(creationRequestId))) + .fetchOne(); + return record == null ? Optional.empty() : Optional.of(toReceipt(record)); + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Fresh tenant creation requires an active Game Design owner transaction"); + } + } + + private void validateInput( + String targetNamespace, + UUID creationRequestId, + String sourceGameTenantKey, + String name, + String description) { + validateSelector(targetNamespace, creationRequestId); + Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); + Objects.requireNonNull(name, "name"); + if (sourceGameTenantKey.length() > 72) { + throw new IllegalArgumentException("sourceGameTenantKey must fit the game tenant key bound"); + } + if (name.length() > 200) { + throw new IllegalArgumentException("name must fit the game name bound"); + } + if (description != null && description.length() > 510) { + throw new IllegalArgumentException("description must fit the game description bound"); + } + if (sourceGameTenantKey.isBlank() + || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey must fit the game tenant key bound"); + } + if (name.codePointCount(0, name.length()) > 100) { + throw new IllegalArgumentException("name must fit the game name bound"); + } + if (description != null && description.codePointCount(0, description.length()) > 255) { + throw new IllegalArgumentException("description must fit the game description bound"); + } + if (description != null && GameTenantCreationDigest.utf8ByteLength(description) > 1020) { + throw new IllegalArgumentException("description must fit the game description byte bound"); + } + } + + private void validateSelector(String targetNamespace, UUID creationRequestId) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(creationRequestId, "creationRequestId"); + if (!DNS_LABEL.matcher(targetNamespace).matches()) { + throw new IllegalArgumentException("targetNamespace must be one lowercase DNS label"); + } + if (creationRequestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("creationRequestId must not be nil"); + } + } + + private void requireNewGameSource(Game saved, String sourceGameTenantKey) { + if (saved == null + || saved.getId() == null + || saved.getId() <= 0 + || saved.getCanonicalTenantId() == null + || saved.getCanonicalTenantId().equals(new UUID(0L, 0L)) + || !sourceGameTenantKey.equals(saved.getTenantId())) { + throw new IllegalStateException("Game Design did not issue a complete new game source row"); + } + GameTenantIdentity source; + try { + source = + gameRepository + .findTenantIdentityByLegacyTenantId(sourceGameTenantKey) + .orElseThrow( + () -> + new IllegalStateException( + "New game source identity did not read back after insert")); + } catch (IllegalStateException exception) { + throw new IllegalStateException("New game source identity did not read back", exception); + } + if (source.provenanceKind() != GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW + || !source.canonicalTenantId().equals(saved.getCanonicalTenantId()) + || !source.sourceGameId().equals(saved.getId()) + || !sourceGameTenantKey.equals(source.sourceLegacyTenantId())) { + throw new IllegalStateException("New game source identity readback did not match issuance"); + } + } + + private FreshTenantCreationEvidence toReceipt(Record record) { + Integer schemaVersion = record.get(SCHEMA_VERSION_FIELD); + String namespace = record.get(TARGET_NAMESPACE); + UUID creationRequestId = record.get(CREATION_REQUEST_ID); + UUID operationId = record.get(OPERATION_ID); + String requestDigest = record.get(REQUEST_DIGEST); + String sourceGameTenantKey = record.get(SOURCE_GAME_TENANT_KEY); + String name = record.get(NAME); + String description = record.get(DESCRIPTION); + String status = record.get(STATUS); + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); + Long sourceGameRowId = record.get(SOURCE_GAME_ROW_ID); + String provenanceKind = record.get(PROVENANCE_KIND); + String evidenceDigest = record.get(EVIDENCE_DIGEST); + + if (schemaVersion == null || schemaVersion != SCHEMA_VERSION) { + throw invalidEvidence("Stored creation operation has an unsupported schema version"); + } + if (!COMPLETED.equals(status)) { + throw invalidEvidence("Stored creation operation is not complete"); + } + if (!validStoredInput(namespace, creationRequestId, sourceGameTenantKey, name, description)) { + throw invalidEvidence("Stored creation operation has invalid immutable input"); + } + if (operationId == null + || operationId.equals(new UUID(0L, 0L)) + || canonicalTenantId == null + || canonicalTenantId.equals(new UUID(0L, 0L)) + || sourceGameRowId == null + || sourceGameRowId <= 0 + || !NEW_GAME_ROW.equals(provenanceKind) + || !GameTenantCreationDigest.isDigest(requestDigest) + || !GameTenantCreationDigest.isDigest(evidenceDigest)) { + throw invalidEvidence("Stored creation operation evidence is incomplete or malformed"); + } + + String expectedRequestDigest; + try { + expectedRequestDigest = + GameTenantCreationDigest.requestDigest( + namespace, creationRequestId, sourceGameTenantKey, name, description); + } catch (IllegalArgumentException exception) { + throw invalidEvidence("Stored creation operation input is not valid Unicode", exception); + } + if (!expectedRequestDigest.equals(requestDigest)) { + throw invalidEvidence("Stored creation operation request digest does not match its input"); + } + + Optional source; + try { + source = gameRepository.findTenantIdentityByLegacyTenantId(sourceGameTenantKey); + } catch (IllegalStateException exception) { + throw invalidEvidence("Stored creation operation source row is corrupt", exception); + } + if (source.isEmpty()) { + throw invalidEvidence("Stored creation operation source row is missing"); + } + GameTenantIdentity identity = source.get(); + if (identity.provenanceKind() != GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW + || !identity.canonicalTenantId().equals(canonicalTenantId) + || !identity.sourceGameId().equals(sourceGameRowId) + || !sourceGameTenantKey.equals(identity.sourceLegacyTenantId())) { + throw invalidEvidence( + "Stored creation operation source tuple no longer matches its game row"); + } + + String expectedEvidenceDigest; + try { + expectedEvidenceDigest = + GameTenantCreationDigest.evidenceDigest( + namespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + } catch (IllegalArgumentException exception) { + throw invalidEvidence("Stored creation operation evidence cannot be digested", exception); + } + if (!expectedEvidenceDigest.equals(evidenceDigest)) { + throw invalidEvidence("Stored creation operation evidence digest does not match its tuple"); + } + + return new FreshTenantCreationEvidence( + schemaVersion, + namespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } + + private boolean validStoredInput( + String namespace, + UUID creationRequestId, + String sourceGameTenantKey, + String name, + String description) { + if (namespace == null + || creationRequestId == null + || sourceGameTenantKey == null + || name == null) { + return false; + } + try { + validateInput(namespace, creationRequestId, sourceGameTenantKey, name, description); + return true; + } catch (IllegalArgumentException exception) { + return false; + } + } + + private boolean sameRequest( + Record record, + String sourceGameTenantKey, + String name, + String description, + String requestDigest) { + return requestDigest.equals(record.get(REQUEST_DIGEST)) + && sourceGameTenantKey.equals(record.get(SOURCE_GAME_TENANT_KEY)) + && name.equals(record.get(NAME)) + && Objects.equals(description, record.get(DESCRIPTION)); + } + + private UUID newNonNilUuid() { + UUID id; + do { + id = UUID.randomUUID(); + } while (id.equals(new UUID(0L, 0L))); + return id; + } + + private InvalidCreationEvidenceException invalidEvidence(String message) { + return new InvalidCreationEvidenceException(message); + } + + private InvalidCreationEvidenceException invalidEvidence(String message, Throwable cause) { + return new InvalidCreationEvidenceException(message, cause); + } + + /** Indicates a stored operation or source tuple that cannot be trusted as creation evidence. */ + public static final class InvalidCreationEvidenceException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public InvalidCreationEvidenceException(String message) { + super(message); + } + + public InvalidCreationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } + + /** Indicates an expected creation-request identity or private source-key collision. */ + public static final class CreationRequestConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public CreationRequestConflictException(String message) { + super(message); + } + } +} 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 7ff3a9aaac..5dca189c3f 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 @@ -2,19 +2,36 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.Base64; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.GameTenantCreationDigest; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; +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.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.ResolveLegacyAccountTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.jooq.exception.DataAccessException; import org.jooq.exception.TooManyRowsException; import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.grpc.server.service.GrpcService; /** Authenticated read of Game Design's own retained tenant identity provenance. */ @@ -23,14 +40,20 @@ public class TenantIdentityGrpcService extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { private final GameRepository gameRepository; private final TenantAssociationMigrationService associationService; + private final GameTenantCreationRepository creationRepository; + private final GameAuthoredWorldSourceRepository authoredWorldRepository; private final String workloadNamespace; public TenantIdentityGrpcService( GameRepository gameRepository, TenantAssociationMigrationService associationService, + GameTenantCreationRepository creationRepository, + GameAuthoredWorldSourceRepository authoredWorldRepository, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.gameRepository = gameRepository; this.associationService = associationService; + this.creationRepository = creationRepository; + this.authoredWorldRepository = authoredWorldRepository; this.workloadNamespace = workloadNamespace; } @@ -170,6 +193,333 @@ public void resolveLegacyAccountTenantAssociation( responseObserver.onCompleted(); } + @Override + public void resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest request, + StreamObserver responseObserver) { + if (!isAccountPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Account workload identity is required") + .asRuntimeException()); + return; + } + + String expectedRequestDigest = request.getExpectedRequestDigest(); + if (!isSha256Digest(expectedRequestDigest)) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical expected request digest is required") + .asRuntimeException()); + return; + } + UUID creationRequestId = parseCanonicalNonNilUuid(request.getCreationRequestId()); + if (creationRequestId == null) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical nonnil creation request ID is required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = creationRepository.read(creationRequestId, workloadNamespace); + } catch (GameTenantCreationRepository.InvalidCreationEvidenceException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Fresh tenant creation evidence is incomplete or inconsistent") + .asRuntimeException()); + return; + } catch (TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Fresh tenant creation evidence is ambiguous") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Fresh tenant creation 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( + code == Status.Code.UNAVAILABLE + ? "Fresh tenant creation evidence is temporarily unavailable" + : "Fresh tenant creation evidence could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Fresh tenant creation evidence could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No fresh tenant creation for exact request ID") + .asRuntimeException()); + return; + } + + FreshTenantCreationEvidence receipt = resolved.orElseThrow(); + boolean exactReceipt = + receipt.schemaVersion() == 1 + && workloadNamespace.equals(receipt.targetNamespace()) + && creationRequestId.equals(receipt.creationRequestId()) + && isCanonicalNonNilUuid(receipt.operationId()) + && expectedRequestDigest.equals(receipt.requestDigest()) + && isSha256Digest(receipt.requestDigest()) + && isCanonicalNonNilUuid(receipt.canonicalTenantId()) + && receipt.sourceGameRowId() > 0 + && receipt.sourceGameTenantKey() != null + && !receipt.sourceGameTenantKey().isBlank() + && "NEW_GAME_ROW".equals(receipt.provenanceKind()) + && isSha256Digest(receipt.evidenceDigest()); + if (exactReceipt) { + try { + String expectedEvidenceDigest = + GameTenantCreationDigest.evidenceDigest( + receipt.targetNamespace(), + receipt.creationRequestId(), + receipt.operationId(), + receipt.requestDigest(), + receipt.canonicalTenantId(), + receipt.sourceGameRowId(), + receipt.sourceGameTenantKey(), + receipt.provenanceKind()); + exactReceipt = expectedEvidenceDigest.equals(receipt.evidenceDigest()); + } catch (IllegalArgumentException ex) { + exactReceipt = false; + } + } + if (!exactReceipt) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Fresh tenant creation readback does not match the exact request") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveFreshTenantCreationResponse.newBuilder() + .setSchemaVersion(receipt.schemaVersion()) + .setTargetNamespace(receipt.targetNamespace()) + .setCreationRequestId(receipt.creationRequestId().toString()) + .setOperationId(receipt.operationId().toString()) + .setRequestDigest(receipt.requestDigest()) + .setCanonicalTenantId(receipt.canonicalTenantId().toString()) + .setSourceGameRowId(receipt.sourceGameRowId()) + .setSourceGameTenantKey(receipt.sourceGameTenantKey()) + .setProvenanceKind(receipt.provenanceKind()) + .setEvidenceDigest(receipt.evidenceDigest()) + .build()); + responseObserver.onCompleted(); + } + + @Override + public void resolveRuntimeTenantIdentity( + ResolveRuntimeTenantIdentityRequest request, + StreamObserver responseObserver) { + if (!isGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + if (canonicalTenantId == null + || requestId == null + || !request.getUnknownFields().asMap().isEmpty()) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription( + "Canonical nonnil IDs and the exact metadata request schema are required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = gameRepository.findRuntimeTenantIdentityByCanonicalTenantId(canonicalTenantId); + } catch (IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design tenant identity provenance is ambiguous or invalid") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design tenant identity 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( + code == Status.Code.UNAVAILABLE + ? "Game Design tenant identity is temporarily unavailable" + : "Game Design tenant identity could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Game Design tenant identity could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No Game Design tenant identity for exact canonical tenant ID") + .asRuntimeException()); + return; + } + + GameTenantIdentity identity = resolved.orElseThrow(); + RuntimeTenantIdentityEvidence evidence; + try { + if (!canonicalTenantId.equals(identity.canonicalTenantId())) { + throw new IllegalArgumentException("Resolved tenant UUID does not match the request"); + } + evidence = + new RuntimeTenantIdentityEvidence( + 1, + workloadNamespace, + requestId, + identity.canonicalTenantId(), + identity.sourceGameId() == null ? 0L : identity.sourceGameId(), + identity.sourceLegacyTenantId(), + identity.provenanceKind() == null ? null : identity.provenanceKind().name()); + } catch (RuntimeException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design tenant identity readback is incomplete or inconsistent") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveRuntimeTenantIdentityResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(evidence.requestId().toString()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .build()); + responseObserver.onCompleted(); + } + + @Override + public void resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest request, + StreamObserver responseObserver) { + if (!isGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID operationId = parseCanonicalNonNilUuid(request.getOperationId()); + UUID tenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + try { + if (requestId == null + || operationId == null + || tenantId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical exact source request is required"); + } + AuthoredWorldSourceDigest.validateReadSelector( + workloadNamespace, tenantId, request.getWorldSlug()); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical exact source request is required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = + authoredWorldRepository.read( + operationId, tenantId, request.getWorldSlug(), workloadNamespace); + } catch (IllegalArgumentException | IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source evidence is inconsistent") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Authored-world source 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("Authored-world source could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No authored-world source for the exact operation and scope") + .asRuntimeException()); + return; + } + AuthoredWorldSourceEvidence evidence = resolved.orElseThrow(); + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !operationId.equals(evidence.operationId()) + || !tenantId.equals(evidence.canonicalTenantId()) + || !request.getWorldSlug().equals(evidence.worldSlug())) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source readback does not match the request") + .asRuntimeException()); + return; + } + responseObserver.onNext( + ResolveAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(requestId.toString()) + .setRegistrationRequestId(evidence.registrationRequestId().toString()) + .setOperationId(evidence.operationId().toString()) + .setRequestDigest(evidence.requestDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setTenantSlug(evidence.tenantSlug()) + .setWorldSlug(evidence.worldSlug()) + .setWorldDisplayName(evidence.worldDisplayName()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setEvidenceDigest(evidence.evidenceDigest()) + .build()); + responseObserver.onCompleted(); + } + private boolean isAccountPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null @@ -187,6 +537,46 @@ private boolean isAccountTenantMigratorPeer() { .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-tenant-migrator"); } + private boolean isGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"); + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return isCanonicalNonNilUuid(parsed) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException ex) { + return null; + } + } + + private static boolean isCanonicalNonNilUuid(UUID value) { + return value != null && !new UUID(0L, 0L).equals(value); + } + + private static boolean isSha256Digest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } + private static boolean validSignature(String value) { if (value == null) { return false; 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 b6a7fd1f31..b114e36138 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -51,6 +51,9 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation + - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity + - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index ef3a36676c..865da4ed6d 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -74,6 +74,9 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation + - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity + - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/db/migration/V32__game_tenant_creation_operations.sql b/services/game-design-service/src/main/resources/db/migration/V32__game_tenant_creation_operations.sql new file mode 100644 index 0000000000..2701d42fb1 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V32__game_tenant_creation_operations.sql @@ -0,0 +1,153 @@ +CREATE TABLE game_tenant_creation_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + creation_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + name VARCHAR(100) NOT NULL, + description TEXT, + status VARCHAR(16) NOT NULL, + canonical_tenant_id UUID, + source_game_row_id BIGINT REFERENCES game(id), + provenance_kind VARCHAR(32), + evidence_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_game_tenant_creation_request UNIQUE (target_namespace, creation_request_id), + CONSTRAINT uq_game_tenant_creation_source_key UNIQUE (source_game_tenant_key), + CONSTRAINT uq_game_tenant_creation_source_row UNIQUE (source_game_row_id), + CONSTRAINT uq_game_tenant_creation_canonical_tenant UNIQUE (canonical_tenant_id), + CONSTRAINT chk_game_tenant_creation_operation_id_non_nil + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_game_tenant_creation_request_id_non_nil + CHECK (creation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_game_tenant_creation_namespace_dns_label + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT chk_game_tenant_creation_request_digest_shape + CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_game_tenant_creation_source_key_length + CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + CONSTRAINT chk_game_tenant_creation_name_length + CHECK (char_length(name) <= 100), + CONSTRAINT chk_game_tenant_creation_description_bytes + CHECK ( + description IS NULL + OR (char_length(description) <= 255 AND octet_length(description) <= 1020) + ), + CONSTRAINT chk_game_tenant_creation_status + CHECK (status IN ('PENDING', 'COMPLETED')), + CONSTRAINT chk_game_tenant_creation_completion_shape CHECK ( + (status = 'PENDING' + AND canonical_tenant_id IS NULL + AND source_game_row_id IS NULL + AND provenance_kind IS NULL + AND evidence_digest IS NULL) + OR + (status = 'COMPLETED' + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_game_row_id IS NOT NULL + AND source_game_row_id > 0 + AND provenance_kind IS NOT NULL + AND provenance_kind = 'NEW_GAME_ROW' + AND evidence_digest IS NOT NULL + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$') + ) +); + +-- [jooq ignore start] +CREATE 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 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 TRIGGER game_tenant_creation_operation_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_tenant_creation_operations + FOR EACH ROW EXECUTE FUNCTION enforce_game_tenant_creation_operation(); + +CREATE FUNCTION reject_game_tenant_creation_operation_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game tenant creation operation evidence cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_tenant_creation_operation_no_truncate + BEFORE TRUNCATE ON game_tenant_creation_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_tenant_creation_operation_truncate(); + +CREATE FUNCTION require_completed_game_tenant_creation_operation() RETURNS trigger AS $$ +DECLARE + current_status VARCHAR(16); +BEGIN + SELECT status INTO 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; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER game_tenant_creation_operation_must_complete + AFTER INSERT OR UPDATE ON game_tenant_creation_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_completed_game_tenant_creation_operation(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V33__authored_world_source_operations.sql b/services/game-design-service/src/main/resources/db/migration/V33__authored_world_source_operations.sql new file mode 100644 index 0000000000..e9506bbaca --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V33__authored_world_source_operations.sql @@ -0,0 +1,224 @@ +CREATE TABLE game_design_tenant_slug_binding ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_tenant_slug_binding PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gd_tenant_slug_binding_slug UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_gd_tenant_slug_binding_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_gd_tenant_slug_binding_source UNIQUE ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_tenant_slug_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_tenant_slug_binding_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') + ) +); + +CREATE TABLE game_design_authored_world_source_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gd_authored_world_request UNIQUE (target_namespace, registration_request_id), + CONSTRAINT uq_gd_authored_world_selector UNIQUE ( + target_namespace, + canonical_tenant_id, + world_slug + ), + CONSTRAINT fk_gd_authored_world_tenant_binding FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ) REFERENCES game_design_tenant_slug_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_authored_world_operation_id CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_request_id CHECK ( + registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_tenant_id CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_digest_shape CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_world_tenant_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_world_slug CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gd_authored_world_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_tenant_slug_binding() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design tenant selector binding 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.provenance_kind + 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 Design tenant selector source does not match its game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_tenant_slug_binding + FOR EACH ROW EXECUTE FUNCTION enforce_gd_tenant_slug_binding(); + +CREATE FUNCTION enforce_gd_authored_world_source() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = NEW.target_namespace + AND b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.tenant_slug = NEW.tenant_slug + AND b.source_game_row_id = NEW.source_game_row_id + AND b.source_game_tenant_key = NEW.source_game_tenant_key + AND b.provenance_kind = NEW.provenance_kind + 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.provenance_kind + 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 Design authored-world source does not match its owner row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_operations + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source(); + +CREATE FUNCTION require_gd_tenant_slug_source() RETURNS trigger AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + WHERE o.target_namespace = NEW.target_namespace + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = NEW.provenance_kind + ) THEN + RAISE EXCEPTION 'Game Design tenant selector claim cannot commit without a world source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER gd_tenant_slug_binding_requires_source + AFTER INSERT ON game_design_tenant_slug_binding + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_gd_tenant_slug_source(); + +CREATE FUNCTION reject_gd_authored_world_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_no_truncate + BEFORE TRUNCATE ON game_design_tenant_slug_binding + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); + +CREATE TRIGGER gd_authored_world_source_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..015bd0aae8 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -0,0 +1,617 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +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 net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +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; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-test"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + 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); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final org.jooq.Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void registersAndReadsExactFreshAndRetainedV29ToV30Sources() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + + AuthoredWorldSourceEvidence retainedReceipt = + fixture.register( + uuid(1), fixture.retainedCanonicalTenantId(), "old-kingdom", "ember-coast", "Café 🐉"); + AuthoredWorldSourceEvidence freshReceipt = + fixture.register( + uuid(2), + fixture.freshCanonicalTenantId(), + "new-kingdom", + "silver-march", + "Silver March"); + + assertThat(retainedReceipt.provenanceKind()).isEqualTo("RETAINED_GAME_V30"); + assertThat(retainedReceipt.sourceGameRowId()).isEqualTo(fixture.retainedGameRowId()); + assertThat(retainedReceipt.sourceGameTenantKey()).isEqualTo("retained-authored-tenant"); + assertThat(freshReceipt.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(freshReceipt.sourceGameRowId()).isEqualTo(fixture.freshGameRowId()); + assertThat(freshReceipt.sourceGameTenantKey()).isEqualTo("fresh-authored-tenant"); + assertThat( + fixture.repository.read( + retainedReceipt.operationId(), + retainedReceipt.canonicalTenantId(), + retainedReceipt.worldSlug(), + retainedReceipt.targetNamespace())) + .contains(retainedReceipt); + assertThat( + fixture.repository.read( + freshReceipt.operationId(), + freshReceipt.canonicalTenantId(), + freshReceipt.worldSlug(), + freshReceipt.targetNamespace())) + .contains(freshReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(2); + } + + @Test + void exactRetryReusesBothDigestsAndChangedRequestLeavesNoSecondClaim() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID requestId = uuid(10); + AuthoredWorldSourceEvidence original = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + String gameXmin = gameXmin(fixture.dsl, "fresh-authored-tenant"); + + AuthoredWorldSourceEvidence retry = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + assertThat(retry).isEqualTo(original); + assertThat( + fixture.repository.read( + original.operationId(), + original.canonicalTenantId(), + original.worldSlug(), + original.targetNamespace())) + .contains(original); + + assertThatThrownBy( + () -> + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "Changed World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("reused with changed input"); + assertThat(gameXmin(fixture.dsl, "fresh-authored-tenant")).isEqualTo(gameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void registrationRequiresOwnerTransactionAndReadRequiresCommittedOutcome() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.repository.register( + NAMESPACE, + uuid(11), + fixture.freshCanonicalTenantId(), + "transaction-tenant", + "transaction-world", + "Transaction World")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> + fixture.repository.read( + uuid(12), + fixture.freshCanonicalTenantId(), + "transaction-world", + NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void tenantSlugAndWorldSlugCollisionsFailWithoutPartialAssignments() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + fixture.register( + uuid(20), fixture.freshCanonicalTenantId(), "claimed-tenant", "one-world", "One World"); + + assertThatThrownBy( + () -> + fixture.register( + uuid(21), + fixture.retainedCanonicalTenantId(), + "claimed-tenant", + "other-world", + "Other World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + + assertThatThrownBy( + () -> + fixture.register( + uuid(22), + fixture.freshCanonicalTenantId(), + "claimed-tenant", + "one-world", + "Different world metadata")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("selector is already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + } + + @Test + void failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture.repository.register( + NAMESPACE, + uuid(30), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World"); + throw new IllegalStateException("simulate failed owner commit"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate failed owner commit"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + assertThat( + fixture.register( + uuid(31), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")) + .isNotNull(); + } + + @Test + void databaseRejectsSelectorClaimsWithoutAnAtomicWorldSourceOperation() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set(DSL.field(DSL.name("tenant_slug"), String.class), "orphan-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "fresh-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("cannot commit without a world source"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void databaseRejectsTenantSelectorBoundToContradictoryGameProvenance() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set( + DSL.field(DSL.name("tenant_slug"), String.class), "mismatched-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "retained-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("does not match its game row"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void readIsExactAndPersistedBindingsAndSourceOperationsAreImmutable() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + AuthoredWorldSourceEvidence receipt = + fixture.register( + uuid(40), fixture.freshCanonicalTenantId(), "read-tenant", "read-world", "Read World"); + + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + "different-world", + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + fixture.retainedCanonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + "other-namespace")) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl + .update(OPERATIONS) + .set(WORLD_DISPLAY_NAME, "Mutated") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl + .deleteFrom(TENANT_BINDINGS) + .where( + DSL.field(DSL.name("target_namespace"), String.class) + .eq(receipt.targetNamespace()) + .and( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class) + .eq(receipt.canonicalTenantId()))) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("binding is immutable"); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .contains(receipt); + } + + @Test + void concurrentExactRegistrationRetriesReturnOnePersistedReceipt() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + Future second = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AuthoredWorldSourceEvidence firstReceipt = first.get(10, TimeUnit.SECONDS); + AuthoredWorldSourceEvidence secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat( + fixture.repository.read( + firstReceipt.operationId(), + firstReceipt.canonicalTenantId(), + firstReceipt.worldSlug(), + firstReceipt.targetNamespace())) + .contains(firstReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void concurrentDifferentTenantsCannotClaimTheSameTenantSlug() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID secondCanonicalTenantId = fixture.createFreshGame("second-fresh-authored-tenant"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freshTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(50), + fixture.freshCanonicalTenantId(), + "racing-tenant", + "fresh-world")); + Future secondTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(51), + secondCanonicalTenantId, + "racing-tenant", + "second-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat( + java.util.List.of( + freshTenant.get(10, TimeUnit.SECONDS), secondTenant.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(RegistrationOutcome.CREATED, RegistrationOutcome.CONFLICT); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(3); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private RegistrationOutcome raceRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + try { + fixture.register( + registrationRequestId, canonicalTenantId, tenantSlug, worldSlug, "Racing World"); + return RegistrationOutcome.CREATED; + } catch (GameAuthoredWorldSourceRepository.RegistrationConflictException conflict) { + return RegistrationOutcome.CONFLICT; + } + } + + private AuthoredWorldSourceEvidence concurrentRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + return fixture.register( + registrationRequestId, + fixture.freshCanonicalTenantId(), + tenantSlug, + worldSlug, + "Concurrent World"); + } + + private Fixture fixtureWithRetainedAndFreshGame() { + String schema = "game_design_authored_world_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("29")); + + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-authored-tenant") + .set(GAME_NAME, "Retained Source Game") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameRepository gameRepository = new GameRepository(dsl); + GameAuthoredWorldSourceRepository repository = new GameAuthoredWorldSourceRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId("fresh-authored-tenant"); + freshGame.setName("Fresh Source Game"); + freshGame.setDescription("Created after canonical tenant identity"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + dsl, + repository, + gameRepository, + transactionTemplate, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame.getId(), + persistedFreshGame.getCanonicalTenantId()); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private String gameXmin(DSLContext dsl, String tenantKey) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE tenant_id = ?", tenantKey) + .getFirst() + .get("xmin", String.class); + } + + private UUID uuid(int suffix) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", suffix)); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent registration"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for concurrent registration", exception); + } + } + + private enum RegistrationOutcome { + CREATED, + CONFLICT + } + + private record Fixture( + DSLContext dsl, + GameAuthoredWorldSourceRepository repository, + GameRepository gameRepository, + TransactionTemplate transactionTemplate, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + long freshGameRowId, + UUID freshCanonicalTenantId) { + AuthoredWorldSourceEvidence register( + UUID requestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence receipt = + transactionTemplate.execute( + status -> + repository.register( + NAMESPACE, + requestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(receipt); + } + + UUID createFreshGame(String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName(tenantKey); + game.setDescription("Concurrent source fixture"); + Game persisted = transactionTemplate.execute(status -> gameRepository.save(game)); + return java.util.Objects.requireNonNull(persisted).getCanonicalTenantId(); + } + } +} 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 new file mode 100644 index 0000000000..9a5200f9d2 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java @@ -0,0 +1,599 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.Map; +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.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +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; + +@Testcontainers(disabledWithoutDocker = true) +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 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); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final org.jooq.Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final org.jooq.Field CREATION_REQUEST_ID = + 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 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 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"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void createCandidateExactRetryReturnsCommittedReceiptWithoutSecondGameWrite() throws Exception { + Fixture fixture = fixture(); + FreshTenantCreationEvidence first = + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "The First World", "A description")); + String firstGameXmin = gameXmin(fixture.dsl, SOURCE_KEY); + + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).contains(first); + FreshTenantCreationEvidence exactRetry = + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "The First World", "A description")); + + assertThat(exactRetry).isEqualTo(first); + assertThat(gameXmin(fixture.dsl, SOURCE_KEY)).isEqualTo(firstGameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void runtimeIdentityLookupReadsOnlyExactNewAndRetainedGameDesignRows() throws Exception { + RetainedFixture retainedFixture = fixtureWithRetainedGame(); + Fixture fixture = retainedFixture.fixture(); + String retainedTenantKey = "retained-game-tenant-9001"; + UUID retainedTenantId = + fixture + .dsl + .select(CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedFixture.retainedGameRowId())) + .fetchOne(CANONICAL_TENANT_ID); + assertThat(retainedTenantId).isNotNull(); + String retainedXmin = gameXmin(fixture.dsl, retainedTenantKey); + + FreshTenantCreationEvidence freshReceipt = + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "Runtime Identity", null)); + String freshXmin = gameXmin(fixture.dsl, SOURCE_KEY); + + assertThat( + fixture.gameRepository.findRuntimeTenantIdentityByCanonicalTenantId( + freshReceipt.canonicalTenantId())) + .contains( + new GameTenantIdentity( + freshReceipt.canonicalTenantId(), + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + freshReceipt.sourceGameRowId(), + SOURCE_KEY)); + assertThat( + fixture.gameRepository.findRuntimeTenantIdentityByCanonicalTenantId(retainedTenantId)) + .contains( + new GameTenantIdentity( + retainedTenantId, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + retainedFixture.retainedGameRowId(), + retainedTenantKey)); + assertThat( + fixture.gameRepository.findRuntimeTenantIdentityByCanonicalTenantId( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"))) + .isEmpty(); + + assertThat(gameXmin(fixture.dsl, SOURCE_KEY)).isEqualTo(freshXmin); + assertThat(gameXmin(fixture.dsl, retainedTenantKey)).isEqualTo(retainedXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void changedPayloadConflictsAndNonTransactionalConstructionCannotWrite() throws Exception { + Fixture fixture = fixture(); + assertThatThrownBy( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> fixture.repository.read(REQUEST_ID, NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).isEmpty(); + assertThat(fixture.dsl.fetchCount(GAME)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + + fixture.inTransaction( + () -> fixture.repository.createCandidate(NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", null)); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "Changed World", null))) + .isInstanceOf(GameTenantCreationRepository.CreationRequestConflictException.class) + .hasMessageContaining("reused with changed input"); + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).isPresent(); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void candidateEnforcesGameBoundsAndAcceptsMaximalMultibyteDescription() throws Exception { + Fixture fixture = fixture(); + String malformedName = "bad" + (char) 0xD800; + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, "x".repeat(73), "World", null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sourceGameTenantKey"); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "x".repeat(201), null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("name"); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", "x".repeat(256)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("description"); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", "😀".repeat(256)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("description"); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, malformedName, null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("valid Unicode"); + + assertThat(fixture.dsl.fetchCount(GAME)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + String maximalMultibyteDescription = "😀".repeat(255); + assertThat( + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", maximalMultibyteDescription))) + .isNotNull(); + assertThat( + fixture + .dsl + .select(DESCRIPTION) + .from(GAME) + .where(TENANT_ID.eq(SOURCE_KEY)) + .fetchOne(DESCRIPTION)) + .isEqualTo(maximalMultibyteDescription); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void rollbackAndClaimOnlyAttemptsLeaveNoPersistedOperation() throws Exception { + Fixture fixture = fixture(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", null); + throw new IllegalStateException("simulate lost owner transaction"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate lost owner transaction"); + assertThat(fixture.dsl.fetchCount(GAME)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(OPERATIONS) + .set(OPERATION_ID, UUID.randomUUID()) + .set(SCHEMA_VERSION, 1) + .set(TARGET_NAMESPACE, NAMESPACE) + .set( + CREATION_REQUEST_ID, + UUID.fromString("22222222-2222-4222-8222-222222222222")) + .set( + REQUEST_DIGEST, + GameTenantCreationDigest.requestDigest( + NAMESPACE, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "claim-only", + "World", + null)) + .set(SOURCE_GAME_TENANT_KEY, "claim-only") + .set(NAME, "World") + .set(STATUS, "PENDING") + .execute(); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("cannot commit while pending"); + assertThat(fixture.dsl.fetchCount(GAME)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + + assertThat( + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", null))) + .isNotNull(); + } + + @Test + void completedOperationCannotBeUpdatedOrDeleted() throws Exception { + Fixture fixture = fixture(); + FreshTenantCreationEvidence receipt = + fixture.inTransaction( + () -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", null)); + + assertThatThrownBy( + () -> + fixture + .dsl + .update(OPERATIONS) + .set(NAME, "Changed") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl + .deleteFrom(OPERATIONS) + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).contains(receipt); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void readFailsClosedWhenGameSourceTupleChangesOrSourceRowDisappears() throws Exception { + Fixture changedFixture = fixture(); + FreshTenantCreationEvidence changedReceipt = + changedFixture.inTransaction( + () -> + changedFixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "Changed Source", null)); + try (Connection connection = changedFixture.dataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("ALTER TABLE game DISABLE TRIGGER trg_game_tenant_identity_immutable"); + changedFixture + .dsl + .update(GAME) + .set( + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class), + "RETAINED_GAME_V30") + .where(GAME_ID.eq(changedReceipt.sourceGameRowId())) + .execute(); + statement.execute("ALTER TABLE game ENABLE TRIGGER trg_game_tenant_identity_immutable"); + } + assertThatThrownBy( + () -> + changedFixture.inTransaction( + () -> + changedFixture.repository.createCandidate( + NAMESPACE, + REQUEST_ID, + SOURCE_KEY, + "Changed request against damaged source", + null))) + .isInstanceOf(GameTenantCreationRepository.CreationRequestConflictException.class) + .hasMessageContaining("reused with changed input"); + assertThatThrownBy(() -> changedFixture.repository.read(REQUEST_ID, NAMESPACE)) + .isInstanceOf(GameTenantCreationRepository.InvalidCreationEvidenceException.class) + .hasMessageContaining("source tuple no longer matches"); + + Fixture missingFixture = fixture(); + FreshTenantCreationEvidence missingReceipt = + missingFixture.inTransaction( + () -> + missingFixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "Missing Source", null)); + try (Connection connection = missingFixture.dataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("ALTER TABLE game DISABLE TRIGGER ALL"); + missingFixture + .dsl + .deleteFrom(GAME) + .where(GAME_ID.eq(missingReceipt.sourceGameRowId())) + .execute(); + statement.execute("ALTER TABLE game ENABLE TRIGGER ALL"); + } + assertThatThrownBy(() -> missingFixture.repository.read(REQUEST_ID, NAMESPACE)) + .isInstanceOf(GameTenantCreationRepository.InvalidCreationEvidenceException.class) + .hasMessageContaining("source row is missing"); + } + + @Test + void concurrentDuplicateCreationRequestsConvergeOnOneUuidAndReceipt() 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 -> { + FreshTenantCreationEvidence receipt = + fixture.repository.createCandidate( + NAMESPACE, + REQUEST_ID, + SOURCE_KEY, + "Concurrent World", + "same request"); + firstBackendPid.set(currentBackendPid(fixture.dsl)); + firstOperationCreated.countDown(); + awaitLatch(allowFirstCommit); + return receipt; + })); + assertThat(firstOperationCreated.await(10, TimeUnit.SECONDS)).isTrue(); + + Future second = + executor.submit( + () -> + fixture.transactionTemplate.execute( + status -> { + secondBackendPid.set(currentBackendPid(fixture.dsl)); + secondOperationStarted.countDown(); + return fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "Concurrent World", "same request"); + })); + assertThat(secondOperationStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitDatabaseBlocking(fixture.dataSource, secondBackendPid.get(), firstBackendPid.get()); + allowFirstCommit.countDown(); + + FreshTenantCreationEvidence firstReceipt = first.get(10, TimeUnit.SECONDS); + FreshTenantCreationEvidence secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat(secondReceipt.canonicalTenantId()).isEqualTo(firstReceipt.canonicalTenantId()); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } finally { + allowFirstCommit.countDown(); + executor.shutdownNow(); + } + } + + private Fixture fixture() { + String schema = "game_design_creation_" + 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) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + assertThat(dsl.select(DSL.field("current_schema()", String.class)).fetchSingle().value1()) + .isEqualTo(schema); + GameRepository gameRepository = new GameRepository(dsl); + GameTenantCreationRepository repository = new GameTenantCreationRepository(dsl, gameRepository); + return new Fixture(dataSource, dsl, gameRepository, repository, transactionTemplate); + } + + private RetainedFixture fixtureWithRetainedGame() { + String schema = + "game_design_retained_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + + migrate(dataSource, schema, MigrationVersion.fromVersion("29")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-game-tenant-9001") + .set(NAME, "Retained Game Design Row") + .set(DESCRIPTION, "Retained source identity fixture") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + assertThat(dsl.select(DSL.field("current_schema()", String.class)).fetchSingle().value1()) + .isEqualTo(schema); + GameRepository gameRepository = new GameRepository(dsl); + GameTenantCreationRepository repository = new GameTenantCreationRepository(dsl, gameRepository); + Fixture fixture = new Fixture(dataSource, dsl, gameRepository, repository, transactionTemplate); + return new RetainedFixture(fixture, retainedGameRowId); + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private String gameXmin(DSLContext dsl, String sourceGameTenantKey) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE tenant_id = ?", sourceGameTenantKey) + .getFirst() + .get("xmin", String.class); + } + + private int currentBackendPid(DSLContext dsl) { + var backendRecord = dsl.fetchOne("SELECT pg_backend_pid() AS pid"); + if (backendRecord == null) { + throw new IllegalStateException("Could not read the PostgreSQL backend id"); + } + Integer pid = backendRecord.get("pid", Integer.class); + if (pid == null || pid <= 0) { + throw new IllegalStateException("PostgreSQL returned an invalid backend id"); + } + return pid; + } + + private void awaitDatabaseBlocking( + DriverManagerDataSource dataSource, int blockedBackendPid, int blockerBackendPid) + throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = + connection.prepareStatement("SELECT ? = ANY(pg_blocking_pids(?))")) { + statement.setInt(1, blockerBackendPid); + statement.setInt(2, blockedBackendPid); + while (System.nanoTime() < deadline) { + try (ResultSet resultSet = statement.executeQuery()) { + resultSet.next(); + if (resultSet.getBoolean(1)) { + return; + } + } + Thread.yield(); + } + } + throw new AssertionError( + "PostgreSQL did not report the duplicate request blocked on the first writer"); + } + + private void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to commit the first tenant operation"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting to commit tenant operation", exception); + } + } + + private record Fixture( + DriverManagerDataSource dataSource, + DSLContext dsl, + GameRepository gameRepository, + GameTenantCreationRepository repository, + TransactionTemplate transactionTemplate) { + private T inTransaction(java.util.concurrent.Callable work) throws Exception { + return transactionTemplate.execute( + status -> { + try { + return work.call(); + } catch (RuntimeException exception) { + throw exception; + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + }); + } + } + + private record RetainedFixture(Fixture fixture, long retainedGameRowId) {} +} 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 new file mode 100644 index 0000000000..456b94e79f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java @@ -0,0 +1,126 @@ +package unit.net.firedevops.firemud.gamedesign.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Empty; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import java.io.IOException; +import java.util.List; +import java.util.Set; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.PropertySource; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.FileSystemResource; + +class TenantIdentityAuthConfigurationTest { + private static final String ACCOUNT_ASSOCIATION_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation"; + private static final String FRESH_CREATION_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation"; + private static final String RUNTIME_TENANT_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity"; + private static final String AUTHORED_WORLD_SOURCE_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource"; + private static final String ACCOUNT_LEGACY_IDENTITY_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameTenantIdentity"; + + @Test + void baseConfigurationExemptsOnlyTheIntendedTenantIdentityMethods() throws IOException { + assertConfiguration(loadProperties(false)); + } + + @Test + void productionConfigurationRetainsTheIntendedTenantIdentityMethods() throws IOException { + assertConfiguration(loadProperties(true)); + } + + private GrpcAuthProperties loadProperties(boolean production) throws IOException { + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + StandardEnvironment environment = new StandardEnvironment(); + ClassPathResource productionResource = new ClassPathResource("application-prod.yml"); + FileSystemResource baseResource = + new FileSystemResource( + productionResource.getFile().toPath().resolveSibling("application.yml")); + List> baseSources = loader.load("application", baseResource); + baseSources.forEach(environment.getPropertySources()::addFirst); + if (production) { + List> productionSources = + loader.load("application-prod", productionResource); + productionSources.forEach(environment.getPropertySources()::addFirst); + } + return Binder.get(environment) + .bind("firemud.auth.grpc", Bindable.of(GrpcAuthProperties.class)) + .orElseThrow(IllegalStateException::new); + } + + private void assertConfiguration(GrpcAuthProperties properties) { + assertThat(properties.getPublicMethods()) + .containsExactlyInAnyOrder( + ACCOUNT_ASSOCIATION_METHOD, + FRESH_CREATION_METHOD, + RUNTIME_TENANT_METHOD, + AUTHORED_WORLD_SOURCE_METHOD); + + AuthTokenInterceptor interceptor = + new AuthTokenInterceptor(null, Set.copyOf(properties.getPublicMethods())); + for (String method : properties.getPublicMethods()) { + assertMethodBypassesBearer(interceptor, method); + } + assertMethodRequiresBearer(interceptor, ACCOUNT_LEGACY_IDENTITY_METHOD); + } + + private void assertMethodBypassesBearer(AuthTokenInterceptor interceptor, String method) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = mock(ServerCall.class); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler next = mock(ServerCallHandler.class); + when(call.getMethodDescriptor()).thenReturn(unaryMethod(method)); + when(next.startCall(eq(call), any(Metadata.class))).thenReturn(new ServerCall.Listener<>() {}); + + interceptor.interceptCall(call, new Metadata(), next); + + verify(next).startCall(eq(call), any(Metadata.class)); + verify(call, never()).close(any(Status.class), any(Metadata.class)); + } + + private void assertMethodRequiresBearer(AuthTokenInterceptor interceptor, String method) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = mock(ServerCall.class); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler next = mock(ServerCallHandler.class); + when(call.getMethodDescriptor()).thenReturn(unaryMethod(method)); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor statusCaptor = ArgumentCaptor.forClass(Status.class); + verify(call).close(statusCaptor.capture(), any(Metadata.class)); + assertThat(statusCaptor.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verify(next, never()).startCall(any(), any(Metadata.class)); + } + + private MethodDescriptor unaryMethod(String fullMethodName) { + return MethodDescriptor.newBuilder() + .setFullMethodName(fullMethodName) + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(Empty.getDefaultInstance())) + .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameRepositoryTest.java new file mode 100644 index 0000000000..51c04c70da --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameRepositoryTest.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.DriverManager; +import java.util.Optional; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameRepositoryTest { + private static final Table GAME = DSL.table(DSL.name("game")); + private static final org.jooq.Field ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final org.jooq.Field SOURCE_GAME_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final org.jooq.Field SOURCE_TENANT_ID = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + private static final UUID NEW_CANONICAL_TENANT_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + + @Test + void findsNewAndRetainedIdentitiesByCanonicalUuidUsingTheirActualSourceRows() throws Exception { + try (Fixture fixture = fixture()) { + insert( + fixture.dsl, + 7L, + "new-game-key-7", + NEW_CANONICAL_TENANT_ID, + "NEW_GAME_ROW", + 7L, + "new-game-key-7"); + insert( + fixture.dsl, + 8L, + "retained-game-key-8", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "RETAINED_GAME_V30", + 8L, + "retained-game-key-8"); + + Optional newIdentity = + fixture.repository.findRuntimeTenantIdentityByCanonicalTenantId(NEW_CANONICAL_TENANT_ID); + Optional retainedIdentity = + fixture.repository.findRuntimeTenantIdentityByCanonicalTenantId( + UUID.fromString("22222222-2222-4222-8222-222222222222")); + + assertThat(newIdentity) + .contains( + new GameTenantIdentity( + NEW_CANONICAL_TENANT_ID, + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + 7L, + "new-game-key-7")); + assertThat(retainedIdentity) + .contains( + new GameTenantIdentity( + UUID.fromString("22222222-2222-4222-8222-222222222222"), + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + 8L, + "retained-game-key-8")); + } + } + + @Test + void missingCanonicalUuidReturnsEmptyAndNullRequestIsRejected() throws Exception { + try (Fixture fixture = fixture()) { + assertThat( + fixture.repository.findRuntimeTenantIdentityByCanonicalTenantId( + UUID.fromString("33333333-3333-4333-8333-333333333333"))) + .isEmpty(); + assertThatThrownBy( + () -> fixture.repository.findRuntimeTenantIdentityByCanonicalTenantId(null)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsSourceRowAndKeyContradictions() throws Exception { + try (Fixture rowFixture = fixture()) { + insert( + rowFixture.dsl, + 7L, + "game-key-7", + NEW_CANONICAL_TENANT_ID, + "NEW_GAME_ROW", + 9L, + "game-key-7"); + assertThatThrownBy( + () -> + rowFixture.repository.findRuntimeTenantIdentityByCanonicalTenantId( + NEW_CANONICAL_TENANT_ID)) + .isInstanceOf(IllegalStateException.class); + } + + try (Fixture keyFixture = fixture()) { + insert( + keyFixture.dsl, + 7L, + "actual-game-key-7", + NEW_CANONICAL_TENANT_ID, + "RETAINED_GAME_V30", + 7L, + "different-source-key"); + assertThatThrownBy( + () -> + keyFixture.repository.findRuntimeTenantIdentityByCanonicalTenantId( + NEW_CANONICAL_TENANT_ID)) + .isInstanceOf(IllegalStateException.class); + } + + try (Fixture kindFixture = fixture()) { + insert( + kindFixture.dsl, + 7L, + "game-key-7", + NEW_CANONICAL_TENANT_ID, + "UNRECOGNIZED_KIND", + 7L, + "game-key-7"); + assertThatThrownBy( + () -> + kindFixture.repository.findRuntimeTenantIdentityByCanonicalTenantId( + NEW_CANONICAL_TENANT_ID)) + .isInstanceOf(IllegalStateException.class); + } + } + + @Test + void rejectsAmbiguousCanonicalUuidLookup() throws Exception { + try (Fixture fixture = fixture()) { + insert( + fixture.dsl, + 7L, + "first-game-key", + NEW_CANONICAL_TENANT_ID, + "NEW_GAME_ROW", + 7L, + "first-game-key"); + insert( + fixture.dsl, + 8L, + "second-game-key", + NEW_CANONICAL_TENANT_ID, + "NEW_GAME_ROW", + 8L, + "second-game-key"); + + assertThatThrownBy( + () -> + fixture.repository.findRuntimeTenantIdentityByCanonicalTenantId( + NEW_CANONICAL_TENANT_ID)) + .isInstanceOf(org.jooq.exception.TooManyRowsException.class); + } + } + + private static Fixture fixture() throws Exception { + var connection = + DriverManager.getConnection( + "jdbc:h2:mem:game-repository-" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1"); + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE \"game\" (" + + "\"id\" BIGINT PRIMARY KEY, " + + "\"tenant_id\" VARCHAR(36) NOT NULL, " + + "\"canonical_tenant_id\" UUID NOT NULL, " + + "\"tenant_identity_provenance_kind\" VARCHAR(32), " + + "\"tenant_identity_source_game_id\" BIGINT, " + + "\"tenant_identity_source_legacy_tenant_id\" VARCHAR(36))"); + return new Fixture(connection, dsl, new GameRepository(dsl)); + } + + private static void insert( + DSLContext dsl, + long rowId, + String tenantKey, + UUID canonicalTenantId, + String provenanceKind, + long sourceGameId, + String sourceTenantKey) { + dsl.insertInto(GAME) + .set(ID, rowId) + .set(TENANT_ID, tenantKey) + .set(CANONICAL_TENANT_ID, canonicalTenantId) + .set(PROVENANCE_KIND, provenanceKind) + .set(SOURCE_GAME_ID, sourceGameId) + .set(SOURCE_TENANT_ID, sourceTenantKey) + .execute(); + } + + private record Fixture(java.sql.Connection connection, DSLContext dsl, GameRepository repository) + implements AutoCloseable { + @Override + public void close() throws Exception { + connection.close(); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationDigestTest.java new file mode 100644 index 0000000000..031da00026 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationDigestTest.java @@ -0,0 +1,78 @@ +package unit.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +class GameTenantCreationDigestTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + 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 String REQUEST_DIGEST = + "sha256:467cbe9641a3ad61d14969aece34b770629ae569641d69fb1aea6e3f1538a28a"; + + @Test + void requestDigestUsesUtf8ByteLengthsForMultibyteSegments() { + assertThat( + GameTenantCreationDigest.requestDigest( + "prod", REQUEST_ID, "legacy-α", "MUD 🎲", "café")) + .isEqualTo("sha256:467cbe9641a3ad61d14969aece34b770629ae569641d69fb1aea6e3f1538a28a"); + } + + @Test + void requestDigestSeparatesAbsentDescriptionFromEmptyDescription() { + String absent = + GameTenantCreationDigest.requestDigest("prod", REQUEST_ID, "legacy-α", "MUD 🎲", null); + String empty = + GameTenantCreationDigest.requestDigest("prod", REQUEST_ID, "legacy-α", "MUD 🎲", ""); + + assertThat(absent) + .isEqualTo("sha256:3fb24a9c0e7461c9a70183982a70faf22c7998bcd31b10aca803b938dd77c9df"); + assertThat(empty) + .isEqualTo("sha256:8f6e0a815262b0fc761f0ea623d1ff95acb0d852f0a8d6c76a283b3c2d270c6a"); + assertThat(absent).isNotEqualTo(empty); + } + + @Test + void requestDigestRejectsUnpairedUnicodeSurrogates() { + String malformedName = "bad" + (char) 0xD800; + assertThatThrownBy( + () -> + GameTenantCreationDigest.requestDigest( + "prod", REQUEST_ID, "tenant", malformedName, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("valid Unicode"); + } + + @Test + void evidenceDigestHasGoldenVectorAndChangesWhenTheSourceRowChanges() { + String expected = + GameTenantCreationDigest.evidenceDigest( + "prod", + REQUEST_ID, + OPERATION_ID, + REQUEST_DIGEST, + CANONICAL_TENANT_ID, + 42L, + "legacy-α", + "NEW_GAME_ROW"); + String changedSourceRow = + GameTenantCreationDigest.evidenceDigest( + "prod", + REQUEST_ID, + OPERATION_ID, + REQUEST_DIGEST, + CANONICAL_TENANT_ID, + 43L, + "legacy-α", + "NEW_GAME_ROW"); + + assertThat(expected) + .isEqualTo("sha256:533f0c6590aff359baa6bbaa1a4b9ab7cd6ebf68a3663ed6681053f5a8cc1955"); + assertThat(changedSourceRow).isNotEqualTo(expected); + } +} 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 02b8b8e9a9..11d89fd643 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 @@ -8,22 +8,38 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import com.google.protobuf.UnknownFieldSet; import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.Base64; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; +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.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.ResolveLegacyAccountTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +import org.jooq.exception.DataAccessException; import org.jooq.exception.TooManyRowsException; import org.junit.jupiter.api.Test; @@ -33,15 +49,176 @@ class TenantIdentityGrpcServiceTest { "spiffe://firemud/ns/test/sa/account-tenant-migrator"; private static final String WRONG_NAMESPACE_MIGRATOR_PEER = "spiffe://firemud/ns/other/sa/account-tenant-migrator"; + private static final String WRONG_NAMESPACE_ACCOUNT_PEER = + "spiffe://firemud/ns/other/sa/account-service"; private static final String WRONG_PEER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String GAME_SESSION_PEER = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String WRONG_NAMESPACE_GAME_SESSION_PEER = + "spiffe://firemud/ns/other/sa/game-session-service"; private static final UUID CANONICAL_TENANT_ID = UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); + private static final UUID FRESH_CREATION_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID FRESH_OPERATION_ID = + 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 RUNTIME_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID RUNTIME_TENANT_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String FRESH_SOURCE_GAME_TENANT_KEY = "fresh-owner-key-91"; + private static final String FRESH_REQUEST_DIGEST = + GameTenantCreationDigest.requestDigest( + "test", FRESH_CREATION_REQUEST_ID, FRESH_SOURCE_GAME_TENANT_KEY, "Fresh Realm", null); private final GameRepository repository = mock(GameRepository.class); private final TenantAssociationMigrationService associationService = mock(TenantAssociationMigrationService.class); + private final GameTenantCreationRepository creationRepository = + mock(GameTenantCreationRepository.class); + private final GameAuthoredWorldSourceRepository authoredWorldRepository = + mock(GameAuthoredWorldSourceRepository.class); private final TenantIdentityGrpcService service = - new TenantIdentityGrpcService(repository, associationService, "test"); + new TenantIdentityGrpcService( + repository, associationService, creationRepository, authoredWorldRepository, "test"); + + @Test + void authoredSourceReadRequiresExactGameSessionPeerBeforeOwnerAccess() { + for (String peer : + new String[] { + null, ACCOUNT_PEER, ACCOUNT_MIGRATOR_PEER, WRONG_NAMESPACE_GAME_SESSION_PEER + }) { + AuthoredSourceObserver observer = authoredSourceCall(authoredSourceRequest(), peer); + assertEquals(Status.Code.PERMISSION_DENIED, observer.errorCode); + assertNull(observer.value); + assertFalse(observer.completed); + } + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void authoredSourceRejectsMalformedTupleAndUnknownFieldsBeforeRead() { + ResolveAuthoredWorldSourceRequest exact = authoredSourceRequest(); + for (ResolveAuthoredWorldSourceRequest request : + new ResolveAuthoredWorldSourceRequest[] { + exact.toBuilder().setOperationId("19").build(), + exact.toBuilder().setCanonicalTenantId("00000000-0000-0000-0000-000000000000").build(), + exact.toBuilder().setRequestId("1-1-1-1-1").build(), + exact.toBuilder().setWorldSlug(" World").build(), + exact.toBuilder().setWorldSlug("w".repeat(121)).build(), + exact.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build() + }) { + AuthoredSourceObserver observer = authoredSourceCall(request, GAME_SESSION_PEER); + assertEquals(Status.Code.INVALID_ARGUMENT, observer.errorCode); + assertNull(observer.value); + } + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void authoredSourceEchoesDistinctReadIdentityAndCompleteImmutableReceipt() { + AuthoredWorldSourceEvidence evidence = authoredSourceEvidence("test"); + when(authoredWorldRepository.read(FRESH_OPERATION_ID, RUNTIME_TENANT_ID, "world-one", "test")) + .thenReturn(Optional.of(evidence)); + AuthoredSourceObserver first = authoredSourceCall(authoredSourceRequest(), GAME_SESSION_PEER); + AuthoredSourceObserver retry = authoredSourceCall(authoredSourceRequest(), GAME_SESSION_PEER); + assertNull(first.errorCode); + assertTrue(first.completed); + assertEquals(first.value, retry.value); + assertEquals(RUNTIME_REQUEST_ID.toString(), first.value.getRequestId()); + assertEquals(FRESH_CREATION_REQUEST_ID.toString(), first.value.getRegistrationRequestId()); + assertEquals(evidence.evidenceDigest(), first.value.getEvidenceDigest()); + assertEquals("tenant-one", first.value.getTenantSlug()); + assertEquals("world-one", first.value.getWorldSlug()); + assertEquals("Wörld", first.value.getWorldDisplayName()); + assertEquals(19L, first.value.getSourceGameRowId()); + verifyNoInteractions(repository, associationService, creationRepository); + } + + @Test + void authoredSourceReadDoesNotReturnAbsentChangedOrUnavailableEvidence() { + when(authoredWorldRepository.read(FRESH_OPERATION_ID, RUNTIME_TENANT_ID, "world-one", "test")) + .thenReturn(Optional.empty()) + .thenReturn(Optional.of(authoredSourceEvidence("other"))) + .thenThrow(new IllegalStateException("contradictory source")) + .thenThrow(new DataAccessException("db", new SQLException("offline", "08006"))); + for (Status.Code expected : + new Status.Code[] { + Status.Code.NOT_FOUND, Status.Code.FAILED_PRECONDITION, + Status.Code.FAILED_PRECONDITION, Status.Code.UNAVAILABLE + }) { + AuthoredSourceObserver observer = + authoredSourceCall(authoredSourceRequest(), GAME_SESSION_PEER); + assertEquals(expected, observer.errorCode); + assertNull(observer.value); + assertFalse(observer.completed); + } + } + + private static ResolveAuthoredWorldSourceRequest authoredSourceRequest() { + return ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId(RUNTIME_REQUEST_ID.toString()) + .setOperationId(FRESH_OPERATION_ID.toString()) + .setCanonicalTenantId(RUNTIME_TENANT_ID.toString()) + .setWorldSlug("world-one") + .build(); + } + + private static AuthoredWorldSourceEvidence authoredSourceEvidence(String namespace) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, + FRESH_CREATION_REQUEST_ID, + RUNTIME_TENANT_ID, + "tenant-one", + "world-one", + "Wörld"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + FRESH_CREATION_REQUEST_ID, + FRESH_OPERATION_ID, + requestDigest, + RUNTIME_TENANT_ID, + "tenant-one", + "world-one", + "Wörld", + 19L, + "source-key", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + FRESH_CREATION_REQUEST_ID, + FRESH_OPERATION_ID, + requestDigest, + RUNTIME_TENANT_ID, + "tenant-one", + "world-one", + "Wörld", + 19L, + "source-key", + "NEW_GAME_ROW", + evidenceDigest); + } + + private AuthoredSourceObserver authoredSourceCall( + ResolveAuthoredWorldSourceRequest request, String peer) { + AuthoredSourceObserver observer = new AuthoredSourceObserver(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + peer == null ? null : GrpcPeerIdentity.parseUri(peer).orElseThrow()) + .run(() -> service.resolveAuthoredWorldSource(request, observer)); + return observer; + } @Test void approvedAccountAssociationReadBindsExactOwnerAndManifestEvidence() { @@ -176,6 +353,408 @@ void duplicateRetainedLegacyTenantKeyFailsAsPrecondition() { assertFalse(observer.completed); } + @Test + void freshCreationReadRequiresExactAccountPeerBeforeOwnerRead() { + assertEquals( + Status.Code.PERMISSION_DENIED, freshCreationStatus(freshCreationCall("", "", null))); + assertEquals( + Status.Code.PERMISSION_DENIED, freshCreationStatus(freshCreationCall("", "", WRONG_PEER))); + assertEquals( + Status.Code.PERMISSION_DENIED, + freshCreationStatus(freshCreationCall("", "", WRONG_NAMESPACE_ACCOUNT_PEER))); + assertEquals( + Status.Code.PERMISSION_DENIED, + freshCreationStatus(freshCreationCall("", "", ACCOUNT_MIGRATOR_PEER))); + assertEquals( + Status.Code.PERMISSION_DENIED, + freshCreationStatus(freshCreationCall("", "", WRONG_NAMESPACE_MIGRATOR_PEER))); + verifyNoInteractions(creationRepository); + } + + @Test + void freshCreationReadRejectsEmptyAlternateAndNilIdsOrDigestsBeforeOwnerRead() { + String digest = "sha256:" + "c".repeat(64); + assertEquals( + Status.Code.INVALID_ARGUMENT, + freshCreationStatus(freshCreationCall("", digest, ACCOUNT_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + freshCreationStatus( + freshCreationCall("87426BB3-A733-43F0-9C8E-2E379CBDF7EC", digest, ACCOUNT_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + freshCreationStatus( + freshCreationCall("00000000-0000-0000-0000-000000000000", digest, ACCOUNT_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + freshCreationStatus( + freshCreationCall("11111111-1111-4111-8111-111111111111", "", ACCOUNT_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + freshCreationStatus( + freshCreationCall( + "11111111-1111-4111-8111-111111111111", "SHA256:" + "c".repeat(64), ACCOUNT_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + freshCreationStatus( + freshCreationCall( + "11111111-1111-4111-8111-111111111111", "c".repeat(64), ACCOUNT_PEER))); + verifyNoInteractions(creationRepository); + } + + @Test + void freshCreationReadReturnsNotFoundOnlyForExactAbsentRequest() { + UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String digest = "sha256:" + "c".repeat(64); + when(creationRepository.read(requestId, "test")).thenReturn(Optional.empty()); + + FreshCreationObserver observer = freshCreationCall(requestId.toString(), digest, ACCOUNT_PEER); + + assertEquals(Status.Code.NOT_FOUND, freshCreationStatus(observer)); + assertNull(observer.value); + verify(creationRepository).read(requestId, "test"); + } + + @Test + void freshCreationReadFailsClosedForPendingCorruptOrChangedSourceEvidence() { + UUID pendingRequestId = UUID.fromString("77777777-7777-4777-8777-777777777777"); + UUID corruptRequestId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + UUID changedSourceRequestId = UUID.fromString("99999999-9999-4999-8999-999999999999"); + when(creationRepository.read(pendingRequestId, "test")) + .thenThrow( + new GameTenantCreationRepository.InvalidCreationEvidenceException( + "incomplete operation")); + when(creationRepository.read(corruptRequestId, "test")) + .thenThrow( + new GameTenantCreationRepository.InvalidCreationEvidenceException("corrupt receipt")); + when(creationRepository.read(changedSourceRequestId, "test")) + .thenThrow( + new GameTenantCreationRepository.InvalidCreationEvidenceException( + "changed source tuple")); + + FreshCreationObserver pending = + freshCreationCall( + pendingRequestId.toString(), + GameTenantCreationDigest.requestDigest( + "test", pendingRequestId, FRESH_SOURCE_GAME_TENANT_KEY, "Pending", null), + ACCOUNT_PEER); + FreshCreationObserver corrupt = + freshCreationCall( + corruptRequestId.toString(), + GameTenantCreationDigest.requestDigest( + "test", corruptRequestId, FRESH_SOURCE_GAME_TENANT_KEY, "Corrupt", null), + ACCOUNT_PEER); + FreshCreationObserver changedSource = + freshCreationCall( + changedSourceRequestId.toString(), + GameTenantCreationDigest.requestDigest( + "test", changedSourceRequestId, FRESH_SOURCE_GAME_TENANT_KEY, "Changed", null), + ACCOUNT_PEER); + + assertEquals(Status.Code.FAILED_PRECONDITION, freshCreationStatus(pending)); + assertEquals(Status.Code.FAILED_PRECONDITION, freshCreationStatus(corrupt)); + assertEquals(Status.Code.FAILED_PRECONDITION, freshCreationStatus(changedSource)); + assertNull(pending.value); + assertNull(corrupt.value); + assertNull(changedSource.value); + } + + @Test + void exactAccountPeerReadsFreshCreationReceiptAndReplaysTheSameResponse() { + when(creationRepository.read(FRESH_CREATION_REQUEST_ID, "test")) + .thenReturn(Optional.of(freshCreationReceipt())); + + FreshCreationObserver first = + freshCreationCall(FRESH_CREATION_REQUEST_ID.toString(), FRESH_REQUEST_DIGEST, ACCOUNT_PEER); + FreshCreationObserver retry = + freshCreationCall(FRESH_CREATION_REQUEST_ID.toString(), FRESH_REQUEST_DIGEST, ACCOUNT_PEER); + + assertNull(first.errorCode); + assertTrue(first.completed); + assertNotNull(first.value); + assertEquals(1, first.value.getSchemaVersion()); + assertEquals("test", first.value.getTargetNamespace()); + assertEquals(FRESH_CREATION_REQUEST_ID.toString(), first.value.getCreationRequestId()); + assertEquals(FRESH_OPERATION_ID.toString(), first.value.getOperationId()); + assertEquals(FRESH_REQUEST_DIGEST, first.value.getRequestDigest()); + assertEquals(FRESH_CANONICAL_TENANT_ID.toString(), first.value.getCanonicalTenantId()); + assertEquals(91L, first.value.getSourceGameRowId()); + assertEquals(FRESH_SOURCE_GAME_TENANT_KEY, first.value.getSourceGameTenantKey()); + assertEquals("NEW_GAME_ROW", first.value.getProvenanceKind()); + assertEquals( + GameTenantCreationDigest.evidenceDigest( + "test", + FRESH_CREATION_REQUEST_ID, + FRESH_OPERATION_ID, + FRESH_REQUEST_DIGEST, + FRESH_CANONICAL_TENANT_ID, + 91L, + FRESH_SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW"), + first.value.getEvidenceDigest()); + assertNull(retry.errorCode); + assertTrue(retry.completed); + assertEquals(first.value, retry.value); + verify(creationRepository, org.mockito.Mockito.times(2)) + .read(FRESH_CREATION_REQUEST_ID, "test"); + verifyNoMoreInteractions(creationRepository); + } + + @Test + void freshCreationReadRejectsChangedDigestAndMismatchedReceiptBindings() { + UUID anotherRequestId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + String changedDigest = + GameTenantCreationDigest.requestDigest( + "test", FRESH_CREATION_REQUEST_ID, FRESH_SOURCE_GAME_TENANT_KEY, "Changed Realm", null); + String otherNamespaceDigest = + GameTenantCreationDigest.requestDigest( + "other", FRESH_CREATION_REQUEST_ID, FRESH_SOURCE_GAME_TENANT_KEY, "Fresh Realm", null); + String otherRequestDigest = + GameTenantCreationDigest.requestDigest( + "test", anotherRequestId, FRESH_SOURCE_GAME_TENANT_KEY, "Fresh Realm", null); + when(creationRepository.read(FRESH_CREATION_REQUEST_ID, "test")) + .thenReturn(Optional.of(freshCreationReceipt())) + .thenReturn(Optional.of(freshCreationReceipt("other", FRESH_CREATION_REQUEST_ID))) + .thenReturn(Optional.of(freshCreationReceipt("test", anotherRequestId))); + + FreshCreationObserver changedExpectedDigest = + freshCreationCall(FRESH_CREATION_REQUEST_ID.toString(), changedDigest, ACCOUNT_PEER); + FreshCreationObserver otherNamespace = + freshCreationCall(FRESH_CREATION_REQUEST_ID.toString(), otherNamespaceDigest, ACCOUNT_PEER); + FreshCreationObserver otherRequest = + freshCreationCall(FRESH_CREATION_REQUEST_ID.toString(), otherRequestDigest, ACCOUNT_PEER); + assertEquals(Status.Code.FAILED_PRECONDITION, freshCreationStatus(changedExpectedDigest)); + assertEquals(Status.Code.FAILED_PRECONDITION, freshCreationStatus(otherNamespace)); + assertEquals(Status.Code.FAILED_PRECONDITION, freshCreationStatus(otherRequest)); + assertNull(changedExpectedDigest.value); + assertNull(otherNamespace.value); + assertNull(otherRequest.value); + } + + @Test + void freshCreationReadMapsConnectionSqlStateToUnavailableOnly() { + UUID unavailableRequestId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + UUID syntaxRequestId = UUID.fromString("66666666-6666-4666-8666-666666666666"); + String unavailableDigest = + GameTenantCreationDigest.requestDigest( + "test", unavailableRequestId, FRESH_SOURCE_GAME_TENANT_KEY, "Unavailable", null); + String syntaxDigest = + GameTenantCreationDigest.requestDigest( + "test", syntaxRequestId, FRESH_SOURCE_GAME_TENANT_KEY, "Syntax", null); + when(creationRepository.read(unavailableRequestId, "test")) + .thenThrow( + new DataAccessException( + "connection failed", new SQLException("connection failed", "08006"))); + when(creationRepository.read(syntaxRequestId, "test")) + .thenThrow( + new DataAccessException("query failed", new SQLException("syntax error", "42601"))); + + FreshCreationObserver unavailable = + freshCreationCall(unavailableRequestId.toString(), unavailableDigest, ACCOUNT_PEER); + FreshCreationObserver syntaxFailure = + freshCreationCall(syntaxRequestId.toString(), syntaxDigest, ACCOUNT_PEER); + + assertEquals(Status.Code.UNAVAILABLE, freshCreationStatus(unavailable)); + assertEquals(Status.Code.INTERNAL, freshCreationStatus(syntaxFailure)); + assertNull(unavailable.value); + assertNull(syntaxFailure.value); + } + + @Test + void exactGameSessionPeerReadsNewAndRetainedIdentityAndRetryKeepsOwnerSource() { + GameTenantIdentity newRowIdentity = + new GameTenantIdentity( + RUNTIME_TENANT_ID, + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + 19L, + "new-game-tenant-19"); + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(RUNTIME_TENANT_ID)) + .thenReturn(Optional.of(newRowIdentity)); + + RuntimeIdentityObserver first = + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + RuntimeIdentityObserver retry = + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + + assertNull(first.errorCode); + assertTrue(first.completed); + assertEquals(first.value, retry.value); + assertEquals(1, first.value.getSchemaVersion()); + assertEquals("test", first.value.getTargetNamespace()); + assertEquals(RUNTIME_REQUEST_ID.toString(), first.value.getRequestId()); + assertEquals(RUNTIME_TENANT_ID.toString(), first.value.getCanonicalTenantId()); + assertEquals(19L, first.value.getSourceGameRowId()); + assertEquals("new-game-tenant-19", first.value.getSourceGameTenantKey()); + assertEquals("NEW_GAME_ROW", first.value.getProvenanceKind()); + verify(repository, org.mockito.Mockito.times(2)) + .findRuntimeTenantIdentityByCanonicalTenantId(RUNTIME_TENANT_ID); + + UUID retainedTenantId = UUID.fromString("66666666-6666-4666-8666-666666666666"); + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(retainedTenantId)) + .thenReturn( + Optional.of( + new GameTenantIdentity( + retainedTenantId, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + 20L, + "retained-game-tenant-20"))); + RuntimeIdentityObserver retained = + runtimeIdentityCall( + retainedTenantId.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + RuntimeIdentityObserver retainedRetry = + runtimeIdentityCall( + retainedTenantId.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + assertNull(retained.errorCode); + assertEquals(retained.value, retainedRetry.value); + assertEquals("RETAINED_GAME_V30", retained.value.getProvenanceKind()); + assertEquals(20L, retained.value.getSourceGameRowId()); + assertEquals("retained-game-tenant-20", retained.value.getSourceGameTenantKey()); + } + + @Test + void runtimeIdentityRequiresExactGameSessionPeerBeforeRequestValidationOrOwnerRead() { + assertEquals( + Status.Code.PERMISSION_DENIED, runtimeIdentityStatus(runtimeIdentityCall("", "", null))); + assertEquals( + Status.Code.PERMISSION_DENIED, + runtimeIdentityStatus(runtimeIdentityCall("", "", ACCOUNT_PEER))); + assertEquals( + Status.Code.PERMISSION_DENIED, + runtimeIdentityStatus(runtimeIdentityCall("", "", WRONG_NAMESPACE_GAME_SESSION_PEER))); + verifyNoInteractions(repository); + } + + @Test + void runtimeIdentityRejectsMissingNilNoncanonicalAndUnknownRequestFieldsBeforeOwnerRead() { + String nil = "00000000-0000-0000-0000-000000000000"; + assertEquals( + Status.Code.INVALID_ARGUMENT, + runtimeIdentityStatus( + runtimeIdentityCall("", RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + runtimeIdentityStatus( + runtimeIdentityCall(nil, RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + runtimeIdentityStatus( + runtimeIdentityCall("55555555-5555-4555-8555-555555555555", nil, GAME_SESSION_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + runtimeIdentityStatus( + runtimeIdentityCall( + CANONICAL_TENANT_ID.toString().toUpperCase(), + RUNTIME_REQUEST_ID.toString(), + GAME_SESSION_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + runtimeIdentityStatus( + runtimeIdentityCall( + "55555555-5555-4555-8555-55555555555", + RUNTIME_REQUEST_ID.toString(), + GAME_SESSION_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + runtimeIdentityStatus( + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), + "44444444-4444-4444-8444-44444444444", + GAME_SESSION_PEER))); + + RuntimeIdentityObserver unknownFields = new RuntimeIdentityObserver(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(GAME_SESSION_PEER).orElseThrow()) + .run( + () -> + service.resolveRuntimeTenantIdentity( + ResolveRuntimeTenantIdentityRequest.newBuilder() + .setCanonicalTenantId(RUNTIME_TENANT_ID.toString()) + .setRequestId(RUNTIME_REQUEST_ID.toString()) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(), + unknownFields)); + assertEquals(Status.Code.INVALID_ARGUMENT, runtimeIdentityStatus(unknownFields)); + verifyNoInteractions(repository); + } + + @Test + void runtimeIdentityFailsClosedForAbsentMismatchedOrInvalidOwnerEvidence() { + UUID otherTenantId = UUID.fromString("77777777-7777-4777-8777-777777777777"); + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(RUNTIME_TENANT_ID)) + .thenReturn(Optional.empty()) + .thenReturn( + Optional.of( + new GameTenantIdentity( + otherTenantId, + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + 19L, + "new-game-tenant-19"))) + .thenReturn( + Optional.of( + new GameTenantIdentity( + RUNTIME_TENANT_ID, + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + 0L, + "new-game-tenant-19"))) + .thenReturn( + Optional.of( + new GameTenantIdentity( + RUNTIME_TENANT_ID, GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, 19L, " "))); + + RuntimeIdentityObserver absent = + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + RuntimeIdentityObserver mismatched = + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + RuntimeIdentityObserver invalid = + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + RuntimeIdentityObserver invalidKey = + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + + assertEquals(Status.Code.NOT_FOUND, runtimeIdentityStatus(absent)); + assertEquals(Status.Code.FAILED_PRECONDITION, runtimeIdentityStatus(mismatched)); + assertEquals(Status.Code.FAILED_PRECONDITION, runtimeIdentityStatus(invalid)); + assertEquals(Status.Code.FAILED_PRECONDITION, runtimeIdentityStatus(invalidKey)); + assertNull(absent.value); + assertNull(mismatched.value); + assertNull(invalid.value); + assertNull(invalidKey.value); + } + + @Test + void runtimeIdentityMapsAmbiguousOrContradictoryRowsToSafePrecondition() { + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(RUNTIME_TENANT_ID)) + .thenThrow(new TooManyRowsException("internal duplicate detail")) + .thenThrow(new IllegalStateException("internal source row/key mismatch")); + + RuntimeIdentityObserver ambiguous = + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + RuntimeIdentityObserver contradictory = + runtimeIdentityCall( + RUNTIME_TENANT_ID.toString(), RUNTIME_REQUEST_ID.toString(), GAME_SESSION_PEER); + + assertEquals(Status.Code.FAILED_PRECONDITION, runtimeIdentityStatus(ambiguous)); + assertEquals(Status.Code.FAILED_PRECONDITION, runtimeIdentityStatus(contradictory)); + assertEquals( + "Game Design tenant identity provenance is ambiguous or invalid", + ambiguous.errorDescription); + assertEquals( + "Game Design tenant identity provenance is ambiguous or invalid", + contradictory.errorDescription); + } + private TestObserver call(String sourceKey, String peerUri) { TestObserver observer = new TestObserver(); Context context = Context.current(); @@ -212,6 +791,46 @@ private AssociationObserver associationCall(long accountTenantId, String peerUri return observer; } + private FreshCreationObserver freshCreationCall( + String creationRequestId, String expectedRequestDigest, String peerUri) { + FreshCreationObserver observer = new FreshCreationObserver(); + Context context = Context.current(); + if (peerUri != null) { + context = + context.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + } + context.run( + () -> + service.resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(creationRequestId) + .setExpectedRequestDigest(expectedRequestDigest) + .build(), + observer)); + return observer; + } + + private RuntimeIdentityObserver runtimeIdentityCall( + String canonicalTenantId, String requestId, String peerUri) { + RuntimeIdentityObserver observer = new RuntimeIdentityObserver(); + Context context = Context.current(); + if (peerUri != null) { + context = + context.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + } + context.run( + () -> + service.resolveRuntimeTenantIdentity( + ResolveRuntimeTenantIdentityRequest.newBuilder() + .setCanonicalTenantId(canonicalTenantId) + .setRequestId(requestId) + .build(), + observer)); + return observer; + } + private ApprovedAssociation approvedAssociation() { return new ApprovedAssociation( 41L, @@ -231,11 +850,50 @@ private ApprovedAssociation approvedAssociation() { 1); } + private FreshTenantCreationEvidence freshCreationReceipt() { + return freshCreationReceipt("test", FRESH_CREATION_REQUEST_ID); + } + + private FreshTenantCreationEvidence freshCreationReceipt(String targetNamespace, UUID requestId) { + String requestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, requestId, FRESH_SOURCE_GAME_TENANT_KEY, "Fresh Realm", null); + return new FreshTenantCreationEvidence( + 1, + targetNamespace, + requestId, + FRESH_OPERATION_ID, + requestDigest, + FRESH_CANONICAL_TENANT_ID, + 91L, + FRESH_SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + requestId, + FRESH_OPERATION_ID, + requestDigest, + FRESH_CANONICAL_TENANT_ID, + 91L, + FRESH_SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW")); + } + private static Status.Code associationStatus(AssociationObserver observer) { assertNotNull(observer.errorCode); return observer.errorCode; } + private static Status.Code freshCreationStatus(FreshCreationObserver observer) { + assertNotNull(observer.errorCode); + return observer.errorCode; + } + + private static Status.Code runtimeIdentityStatus(RuntimeIdentityObserver observer) { + assertNotNull(observer.errorCode); + return observer.errorCode; + } + private static Status.Code status(TestObserver observer) { assertNotNull(observer.errorCode); return observer.errorCode; @@ -284,4 +942,73 @@ public void onCompleted() { completed = true; } } + + private static final class FreshCreationObserver + implements StreamObserver { + private ResolveFreshTenantCreationResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ResolveFreshTenantCreationResponse 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; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ResolveAuthoredWorldSourceResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class RuntimeIdentityObserver + implements StreamObserver { + private ResolveRuntimeTenantIdentityResponse value; + private Status.Code errorCode; + private String errorDescription; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeTenantIdentityResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + Status status = Status.fromThrowable(failure); + errorCode = status.getCode(); + errorDescription = status.getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index cd6ec5a54d..4f7c542758 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -6,6 +6,7 @@ import java.time.Clock; import java.time.Instant; import java.util.Objects; +import java.util.UUID; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -320,13 +321,16 @@ private JoinPublicProductionMembershipResponse joinError(String code, String mes public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( PlayerExecutionContext playerContext) { + if (playerContext == null + || !isCanonicalNonNilUuid(playerContext.getAccountId()) + || !isCanonicalNonNilUuid(playerContext.getTenantId())) { + return membershipAuthorityUnavailable(); + } if (stub() == null) { return membershipAuthorityUnavailable(); } GetTenantMembershipForRuntimeRequest request = - GetTenantMembershipForRuntimeRequest.newBuilder() - .setPlayerContext(Objects.requireNonNull(playerContext, "playerContext is required")) - .build(); + GetTenantMembershipForRuntimeRequest.newBuilder().setPlayerContext(playerContext).build(); try { return callStub().getTenantMembershipForRuntime(request); } catch (StatusRuntimeException ex) { @@ -349,6 +353,18 @@ public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( return membershipAuthorityUnavailable(); } + private static boolean isCanonicalNonNilUuid(String value) { + if (value == null || value.isEmpty()) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } + private GetTenantMembershipForRuntimeResponse membershipAuthorityUnavailable() { return GetTenantMembershipForRuntimeResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 5fa2afce55..14b17cc986 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; @@ -48,6 +49,7 @@ import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; @@ -488,25 +490,28 @@ void emailLoginChallengeRequestHasNoTenantScopeField() throws Exception { @Test void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception { + String accountId = "9b80a81b-7971-44af-bd6b-18079027f47a"; + String tenantId = "cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1"; AccountServiceGrpc.AccountServiceBlockingStub stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); GetTenantMembershipForRuntimeResponse expected = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("00000000-0000-0000-0000-000000000042") - .setTenantId("00000000-0000-0000-0000-000000000007") + .setAccountId(accountId) + .setTenantId(tenantId) .setMembershipExists(true) .setGameplayAdmissionAllowed(true) - .putMembershipVersion("00000000-0000-0000-0000-000000000007", "12") + .putMembershipVersion(tenantId, "12") .setMembershipAuthorityGeneration("4") - .setRequestAccountId("42") - .setRequestTenantId("7") + .setRequestAccountId(accountId) + .setRequestTenantId(tenantId) .setEvaluatedAt("2026-07-31T00:00:00Z") .build(); when(stub.getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class))) .thenReturn(expected); AccountClient client = newClient(stub); - PlayerExecutionContext playerContext = runtimeMembershipContext("42", "7", "request-1"); + PlayerExecutionContext playerContext = + runtimeMembershipContext(accountId, tenantId, "request-1"); GetTenantMembershipForRuntimeResponse actual = client.getTenantMembershipForRuntime(playerContext); @@ -518,11 +523,58 @@ void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception assertThat(actual).isEqualTo(expected); } + @ParameterizedTest + @CsvSource({ + "42, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, 7", + "not-a-uuid, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, malformed", + "9B80A81B-7971-44AF-BD6B-18079027F47A, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, CC5E6D40-88C0-4F91-A6D3-A738F4F2F0A1", + "00000000-0000-0000-0000-000000000000, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, 00000000-0000-0000-0000-000000000000", + "'', cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, ''" + }) + void runtimeMembershipRejectsInvalidScopeBeforeStubOrChannelUse(String accountId, String tenantId) + throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountClient client = newClient(stub, channelFactory); + + GetTenantMembershipForRuntimeResponse response = + client.getTenantMembershipForRuntime( + runtimeMembershipContext(accountId, tenantId, "request-1")); + + assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); + verifyNoInteractions(stub, channelFactory); + } + + @Test + void runtimeMembershipRejectsNullContextBeforeStubOrChannelUse() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountClient client = newClient(stub, channelFactory); + + GetTenantMembershipForRuntimeResponse response = client.getTenantMembershipForRuntime(null); + + assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); + verifyNoInteractions(stub, channelFactory); + } + @Test void runtimeMembershipReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetTenantMembershipForRuntimeResponse response = newClient(null) - .getTenantMembershipForRuntime(runtimeMembershipContext("42", "7", "request-1")); + .getTenantMembershipForRuntime( + runtimeMembershipContext( + "9b80a81b-7971-44af-bd6b-18079027f47a", + "cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "request-1")); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); @@ -546,11 +598,11 @@ void runtimeMembershipRetriesOnceAfterUnavailableAndPreservesSuccess() throws Ex .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetTenantMembershipForRuntimeResponse expected = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("00000000-0000-0000-0000-000000000042") - .setTenantId("00000000-0000-0000-0000-000000000007") + .setAccountId("9b80a81b-7971-44af-bd6b-18079027f47a") + .setTenantId("cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) - .putMembershipVersion("00000000-0000-0000-0000-000000000007", "12") + .putMembershipVersion("cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", "12") .build(); when(fixture .retryStub() @@ -560,13 +612,26 @@ void runtimeMembershipRetriesOnceAfterUnavailableAndPreservesSuccess() throws Ex GetTenantMembershipForRuntimeResponse actual = fixture .client() - .getTenantMembershipForRuntime(runtimeMembershipContext("42", "7", "request-1")); + .getTenantMembershipForRuntime( + runtimeMembershipContext( + "9b80a81b-7971-44af-bd6b-18079027f47a", + "cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "request-1")); assertThat(actual).isEqualTo(expected); - verify(fixture.initialStub()) - .getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class)); - verify(fixture.retryStub()) - .getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class)); + ArgumentCaptor firstCaptor = + ArgumentCaptor.forClass(GetTenantMembershipForRuntimeRequest.class); + ArgumentCaptor retryCaptor = + ArgumentCaptor.forClass(GetTenantMembershipForRuntimeRequest.class); + verify(fixture.initialStub()).getTenantMembershipForRuntime(firstCaptor.capture()); + verify(fixture.retryStub()).getTenantMembershipForRuntime(retryCaptor.capture()); + assertThat(firstCaptor.getValue()).isEqualTo(retryCaptor.getValue()); + assertThat(firstCaptor.getValue().getPlayerContext()) + .isEqualTo( + runtimeMembershipContext( + "9b80a81b-7971-44af-bd6b-18079027f47a", + "cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "request-1")); verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); } @@ -585,7 +650,11 @@ void runtimeMembershipNormalizesExhaustedUnavailableToCanonicalUnavailable() thr GetTenantMembershipForRuntimeResponse response = fixture .client() - .getTenantMembershipForRuntime(runtimeMembershipContext("42", "7", "request-1")); + .getTenantMembershipForRuntime( + runtimeMembershipContext( + "9b80a81b-7971-44af-bd6b-18079027f47a", + "cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "request-1")); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); @@ -666,7 +735,11 @@ void runtimeMembershipNormalizesDeniedReadWithoutRetryOrChannelRebuild(String st AccountClient client = newClient(stub, channelFactory); GetTenantMembershipForRuntimeResponse response = - client.getTenantMembershipForRuntime(runtimeMembershipContext("42", "7", "request-1")); + client.getTenantMembershipForRuntime( + runtimeMembershipContext( + "9b80a81b-7971-44af-bd6b-18079027f47a", + "cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "request-1")); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable");