diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b170d156cf..0226f97a0b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1016,6 +1016,7 @@ jobs: --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 Account fresh UUID pair and snapshot PostgreSQL proof diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 4b68db2304..a263b70861 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -10,15 +10,25 @@ 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 smoke seeder and a legacy-manifest read do not supply this handoff. The selected owner-local operation/readback contract is specified below; its source/RPC boundary has earlier unit-level evidence, while the #2915 Account-consumer extension remains in progress and has no passing database proof. No production creation caller or Account handoff is enabled. +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 or a proved cross-owner Account legacy-key association, and no current player-facing selector resolution is claimed. The selected fresh-tenant source/RPC boundary has earlier unit-level evidence, but the #2915 Account-consumer extension has no passing database proof: its strict seven-case producer/readback suite executed with all seven failing after Flyway because the expected `game` and creation-operation relations were not found. The test-datasource correction described below is not yet validated. The owner-local UUID source/read remains a bounded prerequisite; neither it nor the candidate handoff makes the Account runtime membership snapshot RPC safe to enable. Hosted PostgreSQL, live caller/consumer, retained-row migration, mounted-certificate acceptance, and Account/Game Session proof remain separate gates. +**Implementation status:** Current Game Design data does not include a stable tenant slug or a proved deployed cross-owner Account legacy-key association, and 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. The Game Session tenant-source read and consumer remain a candidate, not 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). ### Fresh tenant creation operation and Account readback -**Selected target contract; local source/RPC unit proof complete, database proof pending.** 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, Account enrollment, 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. +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. @@ -28,7 +38,7 @@ The receipt digest uses the same framing and encoding rules, with ordered preima 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. The earlier local Game Design run executed 291 unit cases and discovered 28 integration cases, all skipped without Docker; those results predate the #2915 Account-consumer extension and do not prove its database path. On exact #2915 head `6299ea128e174a5a3f55f3478929f5db71d4eb2f`, [CI run 36791561008](https://github.com/benhook1013/FireMUD/actions/runs/36791561008) executed all seven strict creation-operation database cases and all seven failed after Flyway because the test connection did not select the migrated schema; the concurrent blocking predicate also failed. The diagnosed PostgreSQL JDBC URL issue is that appending `?currentSchema=` to the original `?loggerLevel=OFF` query leaves `currentSchema` unset. The proposed helper fix uses the original URL plus `setSchema` and asserts `current_schema()`, but corrected database proof has not yet run. Account and Game Session strict suites passed in that run, but they are not proof of the failed producer/readback or Account consumer. 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. +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/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index e079f13ac1..206f8fad01 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -14,6 +14,8 @@ The sections below define the target-state runtime contract. Current implementat - 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 `GameDesignRuntimeTenantIdentityClient` consumes 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. + - 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/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 525e7ddfe7..c04a5bfbb1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +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 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. @@ -51,7 +55,7 @@ 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 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: Game Design's fresh source/RPC operation is extended in #2915 with an Account normal-workload authenticated reader, immutable canonical-UUID association, and shared UUID claim index. Account commits the association only after exact operation/request/digest/source/receipt readback, then uses existing tenant-generation initialization without reset. The local implementation is in progress; no numeric Account alias, selector, membership enrollment, admission, credential, or runtime path is enabled, and the retained manifest must not be reused or inferred for a fresh tenant. Earlier local source/RPC results (291 unit cases; 28 integration cases discovered and skipped) predate this extension. Exact #2915 head `6299ea128e174a5a3f55f3478929f5db71d4eb2f` [CI run 36791561008](https://github.com/benhook1013/FireMUD/actions/runs/36791561008) executed all seven strict Game Design creation database cases and all seven failed after Flyway because the expected relations were not visible in the test schema; the concurrent blocking predicate also failed. A diagnosed JDBC URL schema-selection correction uses the original URL plus `setSchema` and an explicit `current_schema()` assertion, but has not yet been executed. Account and Game Session strict suites passed, but do not establish the new producer/readback or Account consumer proof. The wire/digest contract remains owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback). No composed owner/consumer snapshot or runtime admission proof is established, and Unit 1B remains provisional. +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. diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 3b40f55a6d..d032f2494c 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -15,6 +15,9 @@ service TenantIdentityService { // Exact immutable readback of a newly created tenant operation for Account. rpc ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse); + // Exact owner-local read of one persisted runtime tenant identity for Game Session. + rpc ResolveRuntimeTenantIdentity(ResolveRuntimeTenantIdentityRequest) + returns (ResolveRuntimeTenantIdentityResponse); } message ResolveLegacyGameTenantIdentityRequest { @@ -67,3 +70,18 @@ message ResolveFreshTenantCreationResponse { 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; +} 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/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/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/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index 471d57ef5c..9e0c67d479 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 @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; 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.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; @@ -19,6 +20,8 @@ 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; @@ -313,6 +316,107 @@ && isCanonicalNonNilUuid(receipt.canonicalTenantId()) 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(); + } + private boolean isAccountPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null @@ -330,6 +434,14 @@ 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; diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 894b4b7bea..ecb1fc978a 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -75,6 +75,7 @@ firemud: public-methods: - gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity 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/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java index 342b88b2d6..9a5200f9d2 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java @@ -19,7 +19,9 @@ 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; @@ -42,6 +44,8 @@ class GameTenantCreationRepositoryIntegrationTest { 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 = @@ -88,6 +92,56 @@ void createCandidateExactRetryReturnsCommittedReceiptWithoutSecondGameWrite() th 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(); @@ -415,7 +469,57 @@ private Fixture fixture() { .isEqualTo(schema); GameRepository gameRepository = new GameRepository(dsl); GameTenantCreationRepository repository = new GameTenantCreationRepository(dsl, gameRepository); - return new Fixture(dataSource, dsl, repository, transactionTemplate); + 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) { @@ -474,6 +578,7 @@ private void awaitLatch(CountDownLatch latch) { private record Fixture( DriverManagerDataSource dataSource, DSLContext dsl, + GameRepository gameRepository, GameTenantCreationRepository repository, TransactionTemplate transactionTemplate) { private T inTransaction(java.util.concurrent.Callable work) throws Exception { @@ -489,4 +594,6 @@ private T inTransaction(java.util.concurrent.Callable work) throws Except }); } } + + private record RetainedFixture(Fixture fixture, long retainedGameRowId) {} } 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/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index 55277312e4..64aed70ba3 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 @@ -11,6 +11,7 @@ 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; @@ -31,6 +32,8 @@ 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; @@ -44,6 +47,10 @@ class TenantIdentityGrpcServiceTest { 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 = @@ -52,6 +59,10 @@ class TenantIdentityGrpcServiceTest { UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID FRESH_CANONICAL_TENANT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID 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( @@ -405,6 +416,201 @@ void freshCreationReadMapsConnectionSqlStateToUnavailableOnly() { 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(); @@ -461,6 +667,26 @@ private FreshCreationObserver freshCreationCall( 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, @@ -519,6 +745,11 @@ private static Status.Code freshCreationStatus(FreshCreationObserver observer) { 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; @@ -589,4 +820,29 @@ 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/GameDesignRuntimeTenantIdentityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java new file mode 100644 index 0000000000..db038d822d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.gamesession.client; + +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.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; + +/** Unwired Game Session candidate for exact owner-local runtime tenant identity reads. */ +public final class GameDesignRuntimeTenantIdentityClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + + public GameDesignRuntimeTenantIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProps), + channelFactory, + GameDesignRuntimeTenantIdentityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes the client only when an explicit caller owns activation of this handoff. */ + 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(channel).withCompression("gzip"); + } + + /** Reads persisted Game Design identity and validates every returned owner field. */ + public RuntimeTenantIdentityEvidence resolveRuntimeTenantIdentity( + String canonicalTenantId, String requestId) { + UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonical tenant ID"); + UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Game Design runtime tenant identity client is not initialized"); + } + + ResolveRuntimeTenantIdentityResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveRuntimeTenantIdentity( + ResolveRuntimeTenantIdentityRequest.newBuilder() + .setCanonicalTenantId(tenantUuid.toString()) + .setRequestId(requestUuid.toString()) + .build()); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Game Design runtime tenant identity response contains unsupported fields"); + } + + RuntimeTenantIdentityEvidence evidence; + try { + evidence = + new RuntimeTenantIdentityEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"), + parseCanonicalNonNilUuid( + response.getCanonicalTenantId(), "response canonical tenant ID"), + response.getSourceGameRowId(), + response.getSourceGameTenantKey(), + response.getProvenanceKind()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design runtime tenant identity response is invalid", exception); + } + + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !requestUuid.equals(evidence.requestId()) + || !tenantUuid.equals(evidence.canonicalTenantId())) { + throw new IllegalStateException( + "Game Design runtime tenant identity response does not match the exact request"); + } + return evidence; + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static CommonGrpcClientProperties requireGameSessionMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Runtime tenant identity reads require Game Session workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Runtime tenant identity reads require Game Session certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Runtime tenant identity reads require file-backed Game Session workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java new file mode 100644 index 0000000000..5ffcc5c0b5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java @@ -0,0 +1,293 @@ +package net.firedevops.firemud.gamesession.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.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +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.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +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 GameDesignRuntimeTenantIdentityClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String SOURCE_KEY = "game-design-tenant-91"; + private static final long SOURCE_ROW_ID = 91L; + + @Test + void exactOwnerResponseIsTypedAndStableOnRetryForBothProvenanceKinds() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveRuntimeTenantIdentity(any())) + .thenReturn(validResponse("NEW_GAME_ROW")) + .thenReturn(validResponse("NEW_GAME_ROW")) + .thenReturn(validResponse("RETAINED_GAME_V30")) + .thenReturn(validResponse("RETAINED_GAME_V30")); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + RuntimeTenantIdentityEvidence first = + client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); + RuntimeTenantIdentityEvidence retry = + client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); + + assertThat(first).isEqualTo(retry); + assertThat(first.schemaVersion()).isEqualTo(1); + assertThat(first.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(first.requestId()).isEqualTo(REQUEST_ID); + assertThat(first.canonicalTenantId()).isEqualTo(TENANT_ID); + assertThat(first.sourceGameRowId()).isEqualTo(SOURCE_ROW_ID); + assertThat(first.sourceGameTenantKey()).isEqualTo(SOURCE_KEY); + assertThat(first.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ResolveRuntimeTenantIdentityRequest.class); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub, times(2)).resolveRuntimeTenantIdentity(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .allSatisfy( + request -> { + assertThat(request.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(request.getRequestId()).isEqualTo(REQUEST_ID.toString()); + }); + verify(stub, never()).resolveLegacyAccountTenantAssociation(any()); + verify(stub, never()).resolveLegacyGameTenantIdentity(any()); + verify(stub, never()).resolveFreshTenantCreation(any()); + + // A separate retained-row response remains typed owner provenance, not another authority. + RuntimeTenantIdentityEvidence retained = + client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); + RuntimeTenantIdentityEvidence retainedRetry = + client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); + assertThat(retained).isEqualTo(retainedRetry); + assertThat(retained.provenanceKind()).isEqualTo("RETAINED_GAME_V30"); + assertThat(retained.sourceGameRowId()).isEqualTo(SOURCE_ROW_ID); + assertThat(retained.sourceGameTenantKey()).isEqualTo(SOURCE_KEY); + } + + @Test + void rejectsMalformedRequestsBeforeAnyStubOrChannelUse() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignRuntimeTenantIdentityClient client = newClientWithoutStub(channelFactory); + List invalidRequests = + List.of( + new String[] {null, REQUEST_ID.toString()}, + new String[] {"", REQUEST_ID.toString()}, + new String[] {"AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", REQUEST_ID.toString()}, + new String[] {"11111111-1111-4111-8111-11111111111", REQUEST_ID.toString()}, + new String[] {"11111111-1111-4111-8111-111111111111", ""}, + new String[] {TENANT_ID.toString(), "22222222-2222-4222-8222-22222222222"}, + new String[] {TENANT_ID.toString(), "00000000-0000-0000-0000-000000000000"}); + + for (String[] invalid : invalidRequests) { + assertThatThrownBy(() -> client.resolveRuntimeTenantIdentity(invalid[0], invalid[1])) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsEveryResponseFieldThatDoesNotMatchTheExactRequestOrClosedSchema() throws Exception { + ResolveRuntimeTenantIdentityResponse valid = validResponse("NEW_GAME_ROW"); + assertRejected(valid.toBuilder().setSchemaVersion(2).build()); + assertRejected(valid.toBuilder().setTargetNamespace("other").build()); + assertRejected( + valid.toBuilder().setCanonicalTenantId("AB426BB3-A733-43F0-9C8E-2E379CBDF7EC").build()); + assertRejected(valid.toBuilder().setRequestId("33333333-3333-4333-8333-333333333333").build()); + assertRejected( + valid.toBuilder().setCanonicalTenantId("33333333-3333-4333-8333-333333333333").build()); + assertRejected(valid.toBuilder().setSourceGameRowId(0L).build()); + assertRejected(valid.toBuilder().setSourceGameTenantKey("").build()); + assertRejected(valid.toBuilder().setProvenanceKind("ACCOUNT_ASSOCIATION").build()); + assertRejected(valid.toBuilder().setRequestId("22222222-2222-4222-8222-22222222222").build()); + assertRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + } + + @Test + void propagatesTransportFailureWithBoundedDeadline() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Game Design unavailable")); + when(stub.resolveRuntimeTenantIdentity(any())).thenThrow(unavailable); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + assertThatThrownBy( + () -> client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString())) + .isSameAs(unavailable); + + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsPlaintextIncompleteAndClasspathTlsBeforeChannelCreation() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + for (CommonGrpcClientProperties incomplete : + List.of( + incompleteMtlsProperties(null, "client.key", "server-ca.crt"), + incompleteMtlsProperties("client.crt", null, "server-ca.crt"), + incompleteMtlsProperties("client.crt", "client.key", null))) { + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("certificate, key, and CA"); + } + + CommonGrpcClientProperties classpath = mtlsProperties(); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + verifyNoInteractions(channelFactory); + } + + @Test + void initUsesConfiguredGameDesignTargetAndFileBackedTls(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = mtlsProperties(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + GameDesignRuntimeTenantIdentityClient client = + new GameDesignRuntimeTenantIdentityClient(endpoints, tls, channelFactory, NAMESPACE); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static void assertRejected(ResolveRuntimeTenantIdentityResponse response) + throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveRuntimeTenantIdentity(any())).thenReturn(response); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + assertThatThrownBy( + () -> client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class); + } + + private static GameDesignRuntimeTenantIdentityClient newClient( + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) throws Exception { + GameDesignRuntimeTenantIdentityClient client = + newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static GameDesignRuntimeTenantIdentityClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); + } + + private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub mockStub() { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = + mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static ResolveRuntimeTenantIdentityResponse validResponse(String provenanceKind) { + return ResolveRuntimeTenantIdentityResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setSourceGameRowId(SOURCE_ROW_ID) + .setSourceGameTenantKey(SOURCE_KEY) + .setProvenanceKind(provenanceKind) + .build(); + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/game-design-ca.crt"); + return tls; + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.createFile(directory.resolve("game-session-client.crt")).toString()); + tls.setPrivateKey(Files.createFile(directory.resolve("game-session-client.key")).toString()); + tls.setCaCert(Files.createFile(directory.resolve("game-design-ca.crt")).toString()); + 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; + } +}