From ffd482a4e2f56bf902d6e236d7a410dcb0f84ae5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 12:57:54 +1200 Subject: [PATCH 01/28] fix(account): keep connect replay identity out of public metadata --- .../microservices/account-service/api-contracts.md | 4 ++-- .../firemud/accountservice/dto/ConnectTokenResponse.java | 2 -- services/account-service/src/main/resources/openapi.yaml | 2 -- .../firemud/accountservice/controller/AuthControllerTest.java | 2 +- 4 files changed, 3 insertions(+), 7 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index ace5d14609..2debc2e7dd 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -192,7 +192,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route is implementation drift only and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response without enforcing its emitted lifecycle state or generation, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response without enforcing its emitted lifecycle state or generation, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response boundary:** the live `ConnectTokenResponse` is metadata-only and exposes neither the internal `jti` nor any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | | `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope yields nonterminal `AUTH_UNAVAILABLE` without invented policy evidence or membership mutation; expiry alone never terminalizes the operation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. A bounded Account-owned worker revisits abandoned `PENDING` intents and terminalizes only from exact operation, membership, and audit readback; absent or uncertain evidence remains nonterminal with capped attempts and diagnostics. Exact-final-head PostgreSQL lost-acknowledgement and concurrency proof, direct text end-to-end proof, and membership-generation snapshot proof remain open. | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | @@ -202,7 +202,7 @@ These RPCs and schemas are accepted target state but are not present in the curr Current verification routing/auth status: `POST /auth/verify-email` inherits bearer authentication because both HTTP configurations allowlist only `GET /auth/verify-email`, while that allowlisted GET has no controller mapping; see the existing [verification-routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). -The target `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. **Current implementation drift:** `ConnectTokenResponse` currently includes `jti` in the body, despite this target metadata-only contract. The token is delivered only in the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. An exact retry with the same `(accountId, connectScopeId, requestId)` and digest replays the stored result; after the response envelope recovery horizon, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` and the caller must use a fresh `requestId`, while a changed digest returns `IDEMPOTENCY_CONFLICT`. No gRPC `IssueConnectToken` transport exists. +The current `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. The token is delivered only in the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. The target issuance contract makes an exact retry with the same `(accountId, connectScopeId, requestId)` and digest replay the stored result; after the response-envelope recovery horizon, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` and the caller must use a fresh `requestId`, while a changed digest returns `IDEMPOTENCY_CONFLICT`. That durable replay behavior is not yet implemented. No gRPC `IssueConnectToken` transport exists. The current executable REST and internal response examples use numeric account and tenant IDs. UUID wire identities are an ADR 0020 target-state migration and are not current executable examples. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ConnectTokenResponse.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ConnectTokenResponse.java index ef46d7fda0..c6de02b371 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ConnectTokenResponse.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ConnectTokenResponse.java @@ -7,7 +7,6 @@ public record ConnectTokenResponse( long gameInstanceId, String realmSlug, String connectScopeId, - String jti, String requestId, String issuedAt, String expiresAt, @@ -20,7 +19,6 @@ public static ConnectTokenResponse from(ConnectTokenResult result) { result.gameInstanceId(), result.realmSlug(), result.connectScopeId(), - result.jti(), result.requestId(), result.issuedAt(), result.expiresAt(), diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index f25061fd25..3f12f18cac 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -158,8 +158,6 @@ components: type: string connectScopeId: type: string - jti: - type: string requestId: type: string issuedAt: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 4841e24dff..078f3c2c7c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -132,7 +132,7 @@ void connectTokenSetsCookieAndReturnsMetadataOnly() throws Exception { .andExpect(jsonPath("$.data.gameInstanceId").value(42)) .andExpect(jsonPath("$.data.realmSlug").value("production")) .andExpect(jsonPath("$.data.connectScopeId").value("scope-1")) - .andExpect(jsonPath("$.data.jti").value("jti-1")) + .andExpect(jsonPath("$.data.jti").doesNotHaveJsonPath()) .andExpect(jsonPath("$.data.requestId").value("req-7")) .andExpect(jsonPath("$.data.issuedAt").value("2026-03-30T00:00:00Z")) .andExpect(jsonPath("$.data.expiresAt").value("2026-03-30T00:00:30Z")) From 67a2a6de24932093b9bb381fd7667c61f8065def Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:16:56 +1200 Subject: [PATCH 02/28] fix(admission): gate public join classification and fresh connect issuance --- .../account-service/api-contracts.md | 4 +- .../player-access-and-session.md | 6 +- .../service/impl/AccountServiceImpl.java | 25 ++ .../service/impl/AccountServiceImplTest.java | 224 ++++++++++++++++++ .../text/GameplayStageCommandConstants.java | 4 + .../command/text/PlayCommandHandler.java | 65 +++-- .../presentation-messages.properties | 1 + .../presentation-messages_fr.properties | 1 + .../command/text/PlayCommandHandlerTest.java | 212 ++++++++++++++++- 9 files changed, 517 insertions(+), 25 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2debc2e7dd..71093551ef 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -62,7 +62,7 @@ The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `Ver `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token issuance and text `PLAY` do not enforce the emitted lifecycle state or generation; they proceed only when the two admission booleans are true, and an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`. The consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Fresh connect-token issuance now treats `INACTIVE` membership as nonadmitting and checks the current four-field non-public grant row, but it lacks an atomic membership-version/authority-generation commit gate and lifecycle-qualified, expiring grant proof. Text `PLAY` still does not enforce the emitted lifecycle state or generation; its conditional entitlement/public-policy order is unit-tested, while live Account gRPC reads deny before data access. Current non-public or non-visible target handling remains split across discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Current vs Target Export Lifecycle @@ -192,7 +192,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route is implementation drift only and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response without enforcing its emitted lifecycle state or generation, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response boundary:** the live `ConnectTokenResponse` is metadata-only and exposes neither the internal `jti` nor any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** fresh issuance checks tenant `gameplayAvailable`, treats `INACTIVE` membership as nonadmitting, and checks public `allowPublicJoin` or the current four-field non-public grant. It does not yet enforce the atomic membership-version/authority-generation commit gate or the complete lifecycle-qualified private/playtest grant-and-entitlement target. **Current response boundary:** the live `ConnectTokenResponse` is metadata-only and exposes neither the internal `jti` nor any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | | `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope yields nonterminal `AUTH_UNAVAILABLE` without invented policy evidence or membership mutation; expiry alone never terminalizes the operation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. A bounded Account-owned worker revisits abandoned `PENDING` intents and terminalizes only from exact operation, membership, and audit readback; absent or uncertain evidence remains nonterminal with capped attempts and diagnostics. Exact-final-head PostgreSQL lost-acknowledgement and concurrency proof, direct text end-to-end proof, and membership-generation snapshot proof remain open. | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | 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 1a10be3529..6a812fd653 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -67,11 +67,11 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. A verified terminal minimized receiver receipt now compacts Account's producer payload while retaining audit identity and digest; cleanup of still-`COMMITTED` payloads awaits configured safe-watermark, hold, reference, and finite-retention proof. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rechecks fresh entitlement and public-join policy at the commit gate, binds a v1 digest to the verified caller/scope and policy evidence, and writes the membership, stored operation outcome, and tenant audit outbox evidence in one Account transaction. Global-only registration no longer creates an admitting membership. A bounded Account-owned worker now revisits abandoned `PENDING` intents and terminalizes only exact positive operation/scope/membership/audit readback; expiry, absent evidence, and uncertain authority remain nonterminal with capped attempt diagnostics and caller retry. This does not complete ADR 0025: PostgreSQL lost-acknowledgement, concurrent retry/reconciler and direct text-client end-to-end proof remain unclaimed. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rechecks fresh entitlement and public-join policy at the commit gate, binds a v1 digest to the verified caller/scope and policy evidence, and writes the membership, stored operation outcome, and tenant audit outbox evidence in one Account transaction. Global-only registration no longer creates an admitting membership. A bounded Account-owned worker now revisits abandoned `PENDING` intents and terminalizes only exact positive operation/scope/membership/audit readback; expiry, absent evidence, and uncertain authority remain nonterminal with capped attempt diagnostics and caller retry. This does not complete ADR 0025: PostgreSQL lost-acknowledgement, concurrent retry/reconciler and direct text-client end-to-end proof remain unclaimed. Membership authority generation in runtime admission, lifecycle-qualified and expiring grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; fresh connect-token issuance checks only the current four-field grant row. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation now use normalized email selectors and return neutral success for unknown accounts without token or delivery side effects; public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Every current `DeleteAccount` entry now fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation, including terminal subscriptions. The named pre-v1 Account `AA-1.3`/`DATA-01` successor must implement the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, finite approved schedules, restore/replay and proof before deletion is enabled. Password-reset and email-verification tokens now use conditional single-use consumption in the Account transaction; PostgreSQL concurrent-reuse proof is compiled but not locally executed. Reset-driven revocation remains a separate issuer successor. The legacy account/profile export is explicitly partial, the account-targeted tenant export is disabled before data reads, and JWKS foundations remain live; complete ADR 0050 export is a separate pre-v1 Account successor. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. Generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` gRPC handlers now deny with `FAILED_PRECONDITION` before service/provider calls, with focused repeated-call no-interaction proof; the underlying provider-mutating service and non-exposed purchase-workflow substrate remain unsupported. Exact authenticated workload/method authorization for any future internal generic call remains unproved. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior character, runtime route, playable scope, and connect scope before `PLAY`; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. The local Account JOIN route/RPC and Game Session text dispatch exist, but this does not prove the complete direct text-client flow; the membership-authority-generation reread at issuance, namespace- and policy-qualified Entity actor roster, typed Account runtime reads, and generic prompt-mode login remain gaps. The Unit 1B child requires a persisted account-roster actor after its simulated admission checks and disables unqualified `CHARS`; Account's live runtime reads still deny before data access. Account's bounded readback worker now revisits abandoned JOIN `PENDING` operations; executed PostgreSQL recovery/concurrency and direct-text proof remain open under ADR 0025. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior character, runtime route, playable scope, and connect scope before `PLAY`; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; fresh connect-token issuance requires `ACTIVE` membership and checks the current four-field non-public grant, but lacks lifecycle/expiry and commit-gate generation proof. The conditional `PLAY` path now checks entitlement availability and public-join policy before `JOIN_REQUIRED`, with focused unit proof; live Account gRPC reads still deny before data access, so this does not enable an actionable `PLAY` outcome. The local Account JOIN route/RPC and Game Session text dispatch exist, but this does not prove the complete direct text-client flow; the membership-authority-generation reread at issuance, namespace- and policy-qualified Entity actor roster, typed Account runtime reads, and generic prompt-mode login remain gaps. The Unit 1B child requires a persisted account-roster actor after its simulated admission checks and disables unqualified `CHARS`; Account's live runtime reads still deny before data access. Account's bounded readback worker now revisits abandoned JOIN `PENDING` operations; executed PostgreSQL recovery/concurrency and direct-text proof remain open under ADR 0025. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, durable post-logout episode fencing and complete fresh-edge `LOOK`/prompt proof are not complete. The Unit 1B local trigger prevents fresh first-party `PLAY` from replaying solely because a connect token exists, but durable terminal-episode/generation proof after logout remains absent. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and durable post-logout episode fencing is absent. | @@ -96,7 +96,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. Current connect-token issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target but does not revalidate the applicable non-public grant. Target issuance grant validation and its focused proof remain gaps. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). +`POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. Fresh connect-token issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership lifecycle, and current four-field non-public grant before token storage. This bounded lookup does not prove the target lifecycle-qualified, expiring five-field grant, atomic membership-generation reread, or cached-success freshness. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit `JOIN`/`Join & Play` is implemented locally through the canonical `JoinPublicProductionMembership` Account writer, including a policy-bound v1 digest and membership/audit outbox transaction. Its bounded `PENDING` readback worker is local, but PostgreSQL recovery/concurrency and direct text-client proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 8fb83c5621..61f3d8021b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1049,6 +1049,20 @@ private ConnectTokenResult issueConnectTokenFresh( throw new AuthenticationException( "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); } + if (membership.membershipExists() && "INACTIVE".equals(membership.membershipLifecycleState())) { + if (!isPublicProductionRealm(realm)) { + throw new AuthenticationException( + "NON_PUBLIC_ENROLLMENT_REQUIRED", + "Existing game membership is required for this non-public realm"); + } + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } if (!membership.membershipExists() || !membership.gameplayAdmissionAllowed()) { if (!isPublicProductionRealm(realm)) { if (membership.membershipExists()) { @@ -1068,6 +1082,17 @@ private ConnectTokenResult issueConnectTokenFresh( "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); } + if (!isPublicProductionRealm(realm) + && !hasRealmAccessGrant( + bootstrapContext.accountId(), + scopeContext.tenantId(), + scopeContext.worldSlug(), + scopeContext.realmSlug())) { + throw new AuthenticationException( + "REALM_ACCESS_DENIED", + "The selected non-public realm does not have an active access grant"); + } + String jti = stableId( "gameplay-connect", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 430bc72acb..ae00e6a901 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -2257,6 +2257,137 @@ void issueConnectTokenReturnsShortLivedConnectToken() { org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.eq(30000L)); + org.mockito.Mockito.verifyNoInteractions(accountRealmAccessGrantRepository); + } + + @Test + void issueConnectTokenRequiresCurrentGrantForNonPublicRealm() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + + ConnectTokenResult result = + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-private-grant")); + + assertNotNull(result.connectToken()); + assertFalse(result.replayed()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.times(2)) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + org.mockito.Mockito.verify(sessionService) + .storeSession( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.eq(30000L)); + } + + @Test + void issueConnectTokenRejectsNonPublicRealmWhenCurrentGrantIsMissing() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, false); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-private-grant-denied"))); + + assertEquals("REALM_ACCESS_DENIED", exception.getCode()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.times(2)) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(context.connectScopeId()), + org.mockito.ArgumentMatchers.eq("req-private-grant-denied"), + org.mockito.ArgumentMatchers.argThat( + replay -> !replay.success() && "REALM_ACCESS_DENIED".equals(replay.errorCode())), + org.mockito.ArgumentMatchers.longThat(ttl -> ttl > 0L)); + } + + @Test + void issueConnectTokenRequiresJoinForInactivePublicMembership() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePublicInactiveConnectTokenContext(account, true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-inactive-public-join"))); + + assertEquals("JOIN_REQUIRED", exception.getCode()); + verifyConnectTokenFailureDoesNotStoreSuccess( + context.connectScopeId(), "req-inactive-public-join", "JOIN_REQUIRED"); + } + + @Test + void issueConnectTokenRejectsInactivePublicMembershipWhenJoiningIsDisabled() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePublicInactiveConnectTokenContext(account, false); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest( + context.connectScopeId(), "req-inactive-public-policy-denied"))); + + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); + verifyConnectTokenFailureDoesNotStoreSuccess( + context.connectScopeId(), + "req-inactive-public-policy-denied", + "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + + @Test + void issueConnectTokenRequiresActiveMembershipForNonPublicRealm() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = + preparePrivateConnectTokenContext(account, true, "INACTIVE"); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-inactive-private"))); + + assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); + verifyConnectTokenFailureDoesNotStoreSuccess( + context.connectScopeId(), "req-inactive-private", "NON_PUBLIC_ENROLLMENT_REQUIRED"); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.times(1)) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @Test @@ -4358,6 +4489,99 @@ private static String hash(String password) { } } + private PrivateConnectTokenContext preparePrivateConnectTokenContext( + Account account, boolean grantAtIssuance) { + return preparePrivateConnectTokenContext(account, grantAtIssuance, "ACTIVE"); + } + + private PrivateConnectTokenContext preparePrivateConnectTokenContext( + Account account, boolean grantAtIssuance, String membershipLifecycleState) { + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership tenantMembership = membership(account, 7L); + tenantMembership.setLifecycleState(membershipLifecycleState); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(tenantMembership)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) + .setPointerVersion(19L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer(7L, "demo", "preview", "55", 19L, true, false, "SHARED", "ALLOW_NEW")); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(true, grantAtIssuance); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + return new PrivateConnectTokenContext(bootstrap.bootstrapToken(), connectScopeId); + } + + private PrivateConnectTokenContext preparePublicInactiveConnectTokenContext( + Account account, boolean publicJoiningAllowed) { + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership tenantMembership = membership(account, 7L); + tenantMembership.setLifecycleState("INACTIVE"); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(tenantMembership)); + Subscription subscription = new Subscription(); + subscription.setId(22L); + subscription.setTenantId(7L); + subscription.setStatus(publicJoiningAllowed ? "active" : "grace"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + return new PrivateConnectTokenContext(bootstrap.bootstrapToken(), connectScopeId); + } + + private void verifyConnectTokenFailureDoesNotStoreSuccess( + String connectScopeId, String requestId, String errorCode) { + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(connectScopeId), + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.argThat( + replay -> !replay.success() && errorCode.equals(replay.errorCode())), + org.mockito.ArgumentMatchers.longThat(ttl -> ttl > 0L)); + } + + private record PrivateConnectTokenContext(String bootstrapToken, String connectScopeId) {} + private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( long tenantId, String worldSlug, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java index 516147c63f..fd3ad7e5dc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java @@ -27,6 +27,10 @@ public final class GameplayStageCommandConstants { public static final String TENANT_BILLING_BLOCKED_CODE = "TENANT_BILLING_BLOCKED"; public static final String TENANT_BILLING_BLOCKED_MESSAGE = "That world is temporarily unavailable for gameplay."; + public static final String PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE = + "PUBLIC_PRODUCTION_ADMISSION_DENIED"; + public static final String PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE = + "Public entry to that world is currently unavailable."; public static final String AUTH_UNAVAILABLE_CODE = AuthenticationErrorCodes.UNAVAILABLE; public static final String AUTH_UNAVAILABLE_MESSAGE = "Gameplay authority is temporarily unavailable. Retry PLAY shortly."; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 007cf3f370..6e56ead86c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -633,32 +633,33 @@ private Optional validateRuntimeAdmission( && context.gameInstanceId() == selectedRealm.gameInstanceId() ? context.characterId() : 0L; - GetTenantMembershipForRuntimeResponse membershipResponse = - accountClient.getTenantMembershipForRuntime( - Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); - Optional membershipFailure = - validateMembershipResponse( - membershipResponse, + GetTenantEntitlementsForRuntimeResponse entitlementResponse = + accountClient.getTenantEntitlementsForRuntime( + Long.toString(selectedRealm.tenantId()), requestId); + Optional entitlementFailure = + validateEntitlementsResponse( + entitlementResponse, context, tenantTag, selectedWorld, selectedRealm, - requestedCharacterId, - requestId); - if (membershipFailure.isPresent()) { - return membershipFailure; + requestedCharacterId); + if (entitlementFailure.isPresent()) { + return entitlementFailure; } - GetTenantEntitlementsForRuntimeResponse entitlementResponse = - accountClient.getTenantEntitlementsForRuntime( - Long.toString(selectedRealm.tenantId()), requestId); - return validateEntitlementsResponse( - entitlementResponse, + GetTenantMembershipForRuntimeResponse membershipResponse = + accountClient.getTenantMembershipForRuntime( + Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); + return validateMembershipResponse( + membershipResponse, context, tenantTag, selectedWorld, selectedRealm, - requestedCharacterId); + requestedCharacterId, + entitlementResponse.getAllowPublicJoin(), + requestId); } private long requireResolvedCharacterId(String characterId) { @@ -695,6 +696,7 @@ private Optional validateMembershipResponse( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, long requestedCharacterId, + boolean allowPublicJoin, String requestId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { @@ -714,6 +716,11 @@ private Optional validateMembershipResponse( } if (!response.getMembershipExists() || !response.getGameplayAdmissionAllowed()) { if (isPublicProductionRealm(selectedRealm)) { + if (!allowPublicJoin) { + return Optional.of( + publicProductionAdmissionDeniedFailure( + context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + } recordResumeDeniedIfApplicable( context, selectedWorld.slug(), @@ -819,6 +826,32 @@ private Optional validateEntitlementsResponse( return Optional.empty(); } + private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( + SessionContext context, + String tenantTag, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + long requestedCharacterId) { + recordResumeDeniedIfApplicable( + context, + selectedWorld.slug(), + selectedRealm.slug(), + selectedRealm.pointerVersion(), + selectedRealm.gameInstanceId(), + requestedCharacterId, + tenantTag, + "public_admission_denied"); + return failure( + GameplayStageCommandConstants.PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE, + GameplayStageCommandConstants.PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE, + "error.play.public-production-admission-denied", + Map.of(), + tenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(requestedCharacterId), + null); + } + private PlayCommandHandlingResult tenantBillingBlockedFailure( SessionContext context, String tenantTag, diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index f076ab4f29..b6a3dddfbe 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -24,6 +24,7 @@ error.play.join-required=Membership is required before PLAY; joining this world error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. error.play.entitlement-unavailable=Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. error.play.billing-blocked=That world is temporarily unavailable for gameplay. +error.play.public-production-admission-denied=Public entry to that world is currently unavailable. error.look.room-not-found=Room not found. error.look.world-unavailable=World data is temporarily unavailable. error.look.entity-unavailable=Nearby entity state is temporarily unavailable. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 0aa662b68b..ddf61357e6 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -24,6 +24,7 @@ error.play.join-required=Une adhésion est requise avant PLAY ; rejoindre ce mon error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. error.play.entitlement-unavailable=L’autorité d’abonnement est temporairement indisponible. Réessayez PLAY sous peu. error.play.billing-blocked=Ce monde est temporairement indisponible pour le jeu. +error.play.public-production-admission-denied=L’accès public à ce monde est actuellement indisponible. error.look.room-not-found=Salle introuvable. error.look.world-unavailable=Les donnees du monde sont temporairement indisponibles. error.look.entity-unavailable=L’état des entités proches est temporairement indisponible. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 62f336a72d..49235e3182 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -116,6 +116,7 @@ void setUp() { GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") .setGameplayAvailable(true) + .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") @@ -505,7 +506,7 @@ void playRejectsEntityRosterErrorWithoutBinding() { } @Test - void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { + void playReadsEntitlementMembershipAndGrantBeforeActorRoster() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -524,6 +525,9 @@ void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); org.mockito.InOrder order = Mockito.inOrder(accountClient, entityManagementClient); + order + .verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); order .verify(accountClient) .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); @@ -535,9 +539,6 @@ void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); - order - .verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); order .verify(entityManagementClient) .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -1156,6 +1157,31 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.anyString()); } + @Test + void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(false) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + Mockito.verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq("123"), + Mockito.eq("22"), + Mockito.eq("sandbox"), + Mockito.eq("preview"), + Mockito.anyString()); + } + @Test void playInvisibleRealmWithDeniedGrantClearsBinding() { markPreviewRealmInvisible(); @@ -1317,6 +1343,184 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); } + @ParameterizedTest + @ValueSource(strings = {"ENTITLEMENT_UNAVAILABLE", "AUTH_UNAVAILABLE"}) + void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(0L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode(errorCode).build()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo( + "ENTITLEMENT_UNAVAILABLE".equals(errorCode) + ? GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE + : GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + Mockito.verify(accountClient, never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); + } + + @Test + void playBillingDenialMasksMissingPublicMembership() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(0L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(false) + .setAllowPublicJoin(true) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.TENANT_BILLING_BLOCKED_CODE); + Mockito.verify(accountClient, never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); + } + + @Test + void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(0L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(false) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.public-production-admission-denied"); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); + } + + @Test + void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(false) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + Mockito.verify(sessionContextService).save(Mockito.any(SessionContext.class)); + } + + @Test + void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEntityCalls() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(0L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + Mockito.verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); + } + @Test void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { SessionContext context = From 1ed5235223be4c751f6eb4b7fc27771af694d268 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:18:41 +1200 Subject: [PATCH 03/28] test(game-session): supply public join policy in resume fixture --- .../gamesession/command/text/SessionResumptionFlowTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index a1285a4638..2a5f7398a0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -191,6 +191,7 @@ void setUp() { GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") .setGameplayAvailable(true) + .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") From 09569444224d957d7005c0d8217b78a1a72eefb0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:23:01 +1200 Subject: [PATCH 04/28] docs(admission): align runtime read and response status --- .../microservices/account-service/runtime-and-data.md | 2 +- design/architecture/system-architecture-authz-route-matrix.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 156b79a8bb..1d894ad30d 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -197,7 +197,7 @@ Runtime caller contract: - For a selected target confirmed as public production, fresh Account entitlement (`allowPublicJoin`) and fresh selected-target catalog/pointer/public-production evidence are separate required gates. `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when that selected public-production joining policy denies entry. Missing, malformed, stale, or ambiguous routing remains `ADMISSION_POINTER_UNAVAILABLE`; a deliberate `CLOSED` realm remains `REALM_UNAVAILABLE`; and failure to establish fresh entitlement authority remains `ENTITLEMENT_UNAVAILABLE`. A non-public target uses its applicable grant/access outcome rather than public-production denial. `JOIN_REQUIRED` is returned only when both gates pass but the fresh membership snapshot is missing or `INACTIVE`. - Target issuance also requires the shared replay-readiness record to be `OPEN` and binds its exact `replayAdmissionFence` into the signed token. Missing, unreadable, quarantined, or changing readiness fails closed before the token is exposed. - Minimum request fields: `connectScopeId`, `requestId`. - - Target response fields for all clients are non-secret metadata only: `expiresAt`, `accountId`, `tenantId`, `realmSlug`, `playtestLifecycleId` and positive `playtestStateGeneration` when the selected target is non-public, `gameInstanceId`, and `issuedAt`; both playtest fields are absent for a non-grant public-production target. The token `jti` remains only in the dedicated issuance/replay record and access-controlled security audit evidence; it is not returned to clients. **Current implementation drift:** `ConnectTokenResponse` currently exposes `jti` in the HTTP response body, and the current `ConnectTokenResult`/`AccountServiceImpl` issuance path does not carry or return `playtestLifecycleId` or `playtestStateGeneration`; the live body is therefore not conformant to the target metadata-only/no-internal-jti target or the required non-public-target identity metadata. + - Target response fields for all clients are non-secret metadata only: `expiresAt`, `accountId`, `tenantId`, `realmSlug`, `playtestLifecycleId` and positive `playtestStateGeneration` when the selected target is non-public, `gameInstanceId`, and `issuedAt`; both playtest fields are absent for a non-grant public-production target. The token `jti` remains only in the dedicated issuance/replay record and access-controlled security audit evidence; it is not returned to clients. **Current implementation drift:** `ConnectTokenResponse` omits the internal `jti` and raw token, but the current `ConnectTokenResult`/`AccountServiceImpl` issuance path does not carry or return `playtestLifecycleId` or `playtestStateGeneration`; the live body therefore still lacks the required non-public-target identity metadata. - Account delivers the current connect token only as `Set-Cookie: Firemud-Connect-Token=...` with the gateway-required security attributes; the token is never returned in the response body or a response-header fallback. Browser/mobile clients and first-party non-browser clients with a protected cookie jar retain and use the cookie normally. A future explicitly classified public/non-first-party WebSocket integration may use a dedicated one-time secure-storage response and handshake header only through the separately registered `non_first_party_public` route-matrix variant on the canonical `/ws/game/**` path defined by ADR 0029; it does not convert this cookie endpoint into a header fallback. - Bootstrap discovery surfaces must return the target snapshot `connectScopeId`, which cryptographically binds the exact `tenantId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `catalogRevision`, `pointerVersion`, and `connectScopeExpiresAt`, together with `evaluatedAt`; every non-public target additionally binds exact `playtestLifecycleId` and positive `playtestStateGeneration`, while a non-grant public-production target omits both fields. - `connectScopeId` is short-lived cryptographic proof of the exact evaluated target, not a reservation. `catalogRevision` is the catalog/policy snapshot reference carried by the same authoritative Game Session routing record as `pointerVersion`; `allowPublicJoin` remains the separate Account entitlement field. `JoinPublicProductionMembership` accepts the unchanged `connectScopeId` and `requestId`; `connectScopeId` exclusively binds the target and exact `catalogRevision`/`pointerVersion` pair, so the request has no duplicate catalog or pointer fields. At the membership commit gate, Account verifies the scope's signature, expiry, and exact bound pair against the same fresh selected-target catalog/pointer/public-production routing snapshot. A missing, unavailable, malformed, stale, regressed, or ambiguous routing snapshot fails closed as `ADMISSION_POINTER_UNAVAILABLE`; a changed bound pair returns `CONNECT_SCOPE_MISMATCH`. Account must not silently re-resolve or select a newer target. Missing proto or caller support for carrying and proving this complete bound snapshot through that gate is implementation drift. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 5f9988c8ed..2c16878df1 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -25,7 +25,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] ## Implementation Status -- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the current adapter reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; the current adapter does not expose `membershipLifecycleState`, so the latter response cannot be classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. The local Account explicit `JOIN` operation and Game Session transport seam exist, but complete route enforcement, PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, and the final membership lifecycle/authority-generation reread remain incomplete; this matrix records the target route classification and those current gaps. +- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The conditional Game Session `PLAY` branch now evaluates entitlement and public-join policy before classifying a missing or nonadmitting membership as `JOIN_REQUIRED`, but Account runtime gRPC reads still deny before data access, so live `PLAY` returns `AUTH_UNAVAILABLE` rather than an actionable membership outcome. The current adapter does not expose `membershipLifecycleState`, and exact `ACTIVE`/`INACTIVE` consumer classification remains target-only. The local Account explicit `JOIN` operation and Game Session transport seam exist, but complete route enforcement, PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, and the final membership lifecycle/authority-generation reread remain incomplete; this matrix records the target route classification and those current gaps. - `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy in rows 260-261. Account development and production configuration no longer lists either as a public gRPC bypass. The current requests still lack verified typed caller/target binding, so the runtime membership, realm-grant, and entitlement handlers deny before data access even from the exact Game Session peer until their complete caller-policy alternative is implemented. Missing-token, wrong-workload, and arbitrary account/tenant negative tests establish containment, not a working admission path or the target snapshot. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. @@ -255,7 +255,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `DeleteAccount` (`DELETE /accounts/{accountId}`) | `account_scoped` | Current REST and direct service entries deny with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before mutation, after the route's subject or explicit platform-admin check. The target route additionally requires complete billing/provider/transfer clearance and the ADR 0043/`DATA-01` pending-deletion and retention workflow; it is not enabled by the old subscription-only precondition. | | Account Service | `ExportAccount` (`GET /accounts/{accountId}/export`) | `account_scoped` | **Status: `current_openapi_operator_surface`; synchronous Account/profile-local REST read only, not a second target operation.** The legacy account-ID gRPC export denies before data access. Target RPC semantics are protocol-equivalent to the sole canonical `POST /accounts/{accountId}/exports` route. The current local response and legacy `platformAdmin` override are known drift; the target canonical path is caller-subject-only. | | Account Service | `LinkExternalAccount` (`POST /accounts/{accountId}/external`) | `account_scoped` | **Target-only; currently unavailable.** Do not expose or advertise the current tenant-scoped caller-asserted scaffold. The target is the globally bound flow defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md), and requires server-verified provider authorization plus recent ordinary reauthentication before it becomes routable. | -| Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing, and private/playtest grant and entitlement enforcement are not complete. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Private/playtest targets require both membership and grant; global roles alone do not grant gameplay admission. | +| Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing; fresh issuance checks only the current four-field non-public grant row, not the lifecycle-qualified/expiring target grant and complete entitlement predicate. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Private/playtest targets require both membership and grant; global roles alone do not grant gameplay admission. | | Account Service | `Authenticate` | `internal_workload` | Exact Game Session mTLS identity, no pre-existing issued token, and trusted server-derived credential source context | | Account Service | `RefreshGameplayServiceToken` | `internal_workload` | Exact Game Session mTLS identity plus current `game-session-account-delegation` authority with audience `account-service` | | Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus validated typed player context; no circular end-user token prerequisite. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | From c945b1878310b730af045169813644e23b98f3a5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:50:58 +1200 Subject: [PATCH 05/28] Clarify conditional PLAY lifecycle outcomes and Account authority gates --- .../account-service/runtime-and-data.md | 2 + .../system-architecture-authentication.md | 3 +- .../player-access-and-session.md | 4 + .../text/GameplayStageCommandConstants.java | 8 +- .../command/text/PlayCommandHandler.java | 84 ++++++++- .../presentation-messages.properties | 4 +- .../presentation-messages_fr.properties | 4 +- .../command/text/PlayCommandHandlerTest.java | 175 +++++++++++++++--- .../text/SessionResumptionFlowTest.java | 4 +- .../text/TextCommandInterpreterTest.java | 1 + 10 files changed, 257 insertions(+), 32 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1d894ad30d..c434f4a8af 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -144,6 +144,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current Account REST runtime requires existing caller-bound membership for character discovery and connect-token issuance and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. The separate Game Session text `PLAY` path is currently blocked earlier by Account runtime membership/grant/entitlement gRPC methods returning `FAILED_PRECONDITION` before reads, producing `AUTH_UNAVAILABLE`; its downstream membership outcomes require successful mocked Account responses. For a publicly visible public-production target whose joining policy permits entry, the Account connect-token issuance branch may return `JOIN_REQUIRED` without creating or restoring membership; the latter existing-membership case is not lifecycle-aware while explicit `JOIN` is a separate local action. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. +- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish that proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. - It is backed by one `session:auth:token:` record so per-token logout and account-level revocation semantics remain consistent. - `POST /auth/logout` and `POST /auth/logout-all` must accept this profile so first-party gameplay UIs can explicitly revoke bootstrap capability on sign-out rather than waiting for expiry. @@ -170,6 +171,7 @@ Membership freshness evidence contract: - Account reads the membership state, `membershipVersion`, the complete applicable `authorityTuple` (including the Account-owned membership authority generation), `evaluatedAt`, and the applicable committed `outboxCheckpoints` set from one authoritative snapshot/transaction or equivalent Account-owned fence. It returns those values together, or returns Account-authenticated evidence over exactly those values; callers must not assemble them from separate membership, generation, projection, or event reads. - The target membership response minimum therefore includes `accountId`, `tenantId`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`. The checkpoint set uses `{outboxStreamKey, outboxSequence, sourceEventId, sourceEventDigest}` for every positive sequence and must contain the exact entry for `account:auth-authority:v1:membership//` that covers the returned membership and tuple snapshot. `membershipAuthorityGeneration` is the explicit membership member of that tuple; any separately carried value must authenticate the same value and is not an independent authority. +- A sequence-zero checkpoint is permitted only for an exact account/tenant membership stream that has never committed. Account must prove that condition under the same fenced snapshot as the no-row read and explicitly authenticate the tuple, membership generation, and version; a missing row cannot supply or imply those values. Sequence zero carries neither `sourceEventId` nor `sourceEventDigest` and cannot authorize admission. The first committed `JOIN` is sequence one, and a previously joined or left stream retains its positive sequence history even if no current membership row exists. - `evaluatedAt` is the UTC evaluation time of that complete authoritative snapshot and is not restamped when an older projection or cached row is read. A response is invalid when any required field or checkpoint is absent, when the checkpoint does not cover the tuple and membership version, or when the values cannot be proven to come from the same snapshot. Reachable contradictory, stale, regressed, or mismatched evidence is denied; an unavailable or timed-out Account evidence dependency remains retryable `AUTH_UNAVAILABLE`. A distinct authorization outcome may be defined only by the owning API contract for a different operation, not as an alternative code for this runtime membership dependency. Runtime caller contract: diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 9f4f9a37b9..ab7bab6a30 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -47,7 +47,7 @@ The following contract decisions are mandatory and resolve cross-document ambigu - **Authority outbox stream** – Account emits each revocation payload on exactly `account:auth-authority:v1:`, where `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound playtest grant scope produced by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). `outboxSequence` starts at `1` independently for each exact stream key; `tenantBillingSequence` remains the separate tenant billing sequence. Consumers keep watermarks per exact stream key: duplicates with matching evidence at or below the watermark are no-ops, the next sequence is contiguous, a higher sequence is a gap only within that same key, and an unrelated scope never creates a gap. Conflicting duplicate evidence or a same-key gap stops affected validation/admission until Account reconciliation proves the exact checkpoint. - **Playtest grant stream identity** – The grant stream's scope, `sourceScope`, and `outboxStreamKey` are lifecycle-bound and must be produced and parsed only by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Any grant revision, tombstone, lookup, or admission evidence that omits `playtestLifecycleId` is incomplete and fails closed; a realm slug alone cannot select a grant. - **Authority replay evidence** – Consumers retain only a finite, deployment-configured replay-evidence window per exact `outboxStreamKey`, with a maximum sequence count and retention TTL, keyed by `outboxSequence`; each retained entry includes `eventId`, the canonical event digest, `sourceScope`, the complete applicable `authorityTuple`/`issuanceFence`, and the relevant event payload evidence. When a duplicate at or below the watermark falls outside that window, the consumer must use an Account-owned authoritative lookup for the exact `(outboxStreamKey, outboxSequence)` and compare the supplied evidence for exact equality. Matching evidence is accepted as a no-op; unavailable lookup is retryable `AUTH_UNAVAILABLE` and keeps the affected scope fail closed; reachable missing or conflicting evidence is quarantined for reconciliation and fails closed. Advancing a watermark never makes an unverified older duplicate acceptable. -- **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. The matching checkpoint is `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: }`. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. +- **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. For a committed stream, the matching checkpoint is `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: , sourceEventId, sourceEventDigest}`. Account may instead return sequence `0` only when the exact account/tenant membership stream has never committed and the same fenced snapshot proves no membership row together with the authenticated tuple, generation, and version. A sequence-zero checkpoint omits event ID and digest, grants no admission, and is followed by the first committed `JOIN` event at sequence `1`. A formerly joined or left stream never resets to zero. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. - **Membership event continuity** – Membership changes use only `account:auth-authority:v1:membership//`. Each event names `outboxStreamKey`, `sourceScope` (`membership//`), `outboxSequence`, `eventId`, the complete applicable `authorityTuple`/`issuanceFence`, and the Account snapshot's `accountId`, `tenantId`, `membershipVersion`, membership payload, admission flag, and `callerBoundAuthorityInvalidated` result. `sourceScope` must decode to `outboxStreamKey`; each consumer stores a `watermark` and event identity/digest per exact stream and marks delivery `contiguous` only when the next sequence is `watermark + 1` (with first-stream initialization from the Account checkpoint). A duplicate at or below the watermark is valid only when all evidence matches; a same-sequence conflict quarantines the affected scope. A higher sequence is a gap only within that same stream; unrelated streams do not advance or gap this watermark. Conflicts, non-contiguous delivery, missing or mismatched tuple/checkpoint evidence, or an unresolved membership-version/generation pair stop affected admission and reconnect/validation until exact Account reconciliation proves coverage; unavailable reconciliation returns retryable `AUTH_UNAVAILABLE`, while reachable contradictory or revoked evidence is denied/revoked. - **Authority validation outcomes** – A registry, lease, gameplay binding, token-identity fence, Account authority source, or authority-projection freshness fence that cannot be reached or times out is a retryable `AUTH_UNAVAILABLE` / HTTP 503 condition; this includes runtime membership-authority reads. It does not revoke the client's authentication and no cached authority may authorize the failed operation. Reachable missing, malformed, expired, revoked, stale, regressed, or mismatched evidence is an authentication failure (`AUTH_SESSION_REVOKED` or the specific invalid-token outcome) and requires reauthentication. Registry presence or absence never overrides this classification; membership-authority failures use these same availability-versus-denial rules and do not introduce a second canonical error. - **Tenant authority-generation scope** – `session:auth:generation:tenant:` applies by default to tenant-scoped regular and gameplay-affecting operations. Only the closed route-class allowlist in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#explicit-route-class-generation-allowlist) may omit the target tenant generation. The `billing_safe_tenant` class intentionally omits that target-tenant generation only under this closed exception; it still requires issuer/account and caller-bound membership generations plus a live `tenantAdmin` check. `cross_tenant_support_safe` requires issuer/account generations, a live `support` role without elevation or an explicitly allowed `platformAdmin` role with `privileged_control` backed by independent TOTP, and global token scope; and `cross_tenant_billing_safe` requires issuer/account generations, a live `billingAdmin` or explicitly allowed `platformAdmin` role, global token scope, and `privileged_control`. None of these routes may use cached authorization, and no newly named route class inherits the allowlist. @@ -56,6 +56,7 @@ The following contract decisions are mandatory and resolve cross-document ambigu - **JWT claim contract** – Services must validate a strict JWT claim profile (required claims and audience per token profile), not only signature plus ad-hoc fields. Registry-backed profiles carry the complete `authorityTuple` and positive `issuanceFence` with the exact nested names above. A field marked `Absent` by its profile is omitted, not encoded as an empty string, null, map, or list; an empty map/list is valid only when that profile declares the field present and its value is empty. `control-ui` must include `scopedRoles` as `{}` when empty; omission is rejected. Its `tenantAuthorityGeneration` keys equal the non-empty scoped-role tenant keys whose allowed routes require target-tenant authority, while its independent `membershipAuthorityGeneration` and `membershipVersion` keys equal the caller-membership tenants needed by the token's allowed route classifications, including a `billing_safe_tenant` key that deliberately has no target-tenant authority entry. Explicitly unscoped profiles use empty maps/lists only where their profile declares those fields present, never absent or fabricated scope values. - **Authority tuple comparison** – Every applicable `issuerAuthGeneration`, `accountAuthorityGeneration`, exact tenant and membership map entry, private-realm `grantVersion`, `accountSecurityCutoff`, and `tenantBillingCutoff` is compared as part of one tuple. `membershipVersion` is a separate current/stored membership projection check and is never substituted for `membershipAuthorityGeneration`; a tuple, cutoff, fence, or membership mismatch fails closed. - **Internal gameplay delegation boundary** – Gameplay services authenticate the concrete mTLS workload identity, enforce an exact method-level caller allowlist, and validate a typed `PlayerExecutionContext` against request and domain scope. +- **First-party bare `LOGIN` delegation** – A first-party WebSocket `LOGIN` without credentials may obtain the private `game-session-account-delegation` JWT only through an Account-owned, one-use, idempotent exchange. Account verifies its committed gameplay-connect issuance and bootstrap subject, the verified Gateway-signed connect context, the exact Game Session mTLS caller, the player/tenant/target binding, current authority, and the issuance fence before issuing. Gateway context or a connect-token `jti` alone is not Account authentication. Game Session never mints this JWT or returns it to a gameplay client; an exact retry recovers the same bounded exchange result, while changed binding or fence evidence fails closed. - **No universal player attestation** – Routine gameplay delegation does not use signed per-action player attestations or a replay cache. Mutation replay is controlled by the owning command/effect/request idempotency contract. - **Route classification governance** – Protected routes must be classified in the shared route matrix document and enforced through middleware annotations/interceptors; behavior must not rely on per-service ad-hoc interpretation. - **Gameplay session ownership** – Game Session owns gameplay binding records, the atomic monotonic binding CAS, and bounded secondary indexes that map gameplay bindings by the target uniqueness key `{tenantId, playableStateNamespaceId, characterId}`, account/tenant scope, and tenant scope so takeover, reconnect, and revocation do not require scans. Server-derived `playableStateScope` and binding values/evidence retain `{sessionId, gameInstanceId, bindingGeneration}` as locally appropriate. Account owns the admission decision and exact-binding lease only; Account finalization commits lease/decision evidence and never creates, deletes, or mutates Game Session bindings or indexes. Orphan evidence from Account reconciliation becomes a durable cleanup request that Gateway and Game Session consume under their respective edge and gameplay fences. 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 6a812fd653..d665448fe5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,10 @@ Official-hosted creator-content acceptance remains an unimplemented target gap; Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). +The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. + +The approved first-party bare-`LOGIN` private-delegation exchange is not implemented. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. An Account-owned one-use/idempotent exchange must establish those producer facts and exact Game Session caller binding before Game Session can receive a private delegation JWT; a forwarded context or token `jti` alone cannot authorize the exchange. The approved never-joined sequence-zero membership checkpoint likewise requires Account to prove the exact stream never committed under the same fenced snapshot as the no-row read and authenticated tuple/generation/version; no current response or consumer provides that proof. Formerly joined or left streams retain positive sequence history. Both paths remain unavailable while the runtime RPCs deny. + Account's credential-granting gameplay gRPC methods enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Legacy profile GET/PUT now require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy batch reads require the exact Social Groups peer and remain scoped to tenant profiles. Direct account-ID export, external-link, and verification gRPC methods deny before reads or mutation because no authorized internal caller is configured. These guards do not make the broader target method/caller authority complete or restore the disabled runtime reads. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. The Unit 1B child removes `PLAY`'s synthetic account/name/hash fallback and requires a persisted account-roster actor after admission checks, with focused foreign-owner, malformed-row, absent/ambiguous roster, and no-mutation negatives. That Entity list is not yet namespace/policy-qualified, and Account's runtime reads still deny before data access; `CHARS` now returns unavailable before Entity access. These are safety corrections, not a working complete actor-entry path. Typed Account caller/target authority, stable namespace and policy snapshot, descriptor/template resolution, zero/one/many entry behavior, and fork-local copy proof remain ordered pre-v1 work and do not upgrade AA-2.1 status. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java index fd3ad7e5dc..b841113f62 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java @@ -23,7 +23,13 @@ public final class GameplayStageCommandConstants { "You are not allowed to enter that world."; public static final String JOIN_REQUIRED_CODE = "JOIN_REQUIRED"; public static final String JOIN_REQUIRED_MESSAGE = - "Membership is required before PLAY; joining this world is not available yet."; + "Membership is required before PLAY. Use JOIN or choose Join & Play."; + public static final String NON_PUBLIC_ENROLLMENT_REQUIRED_CODE = "NON_PUBLIC_ENROLLMENT_REQUIRED"; + public static final String NON_PUBLIC_ENROLLMENT_REQUIRED_MESSAGE = + "Existing game membership is required for this non-public realm."; + public static final String REALM_ACCESS_DENIED_CODE = "REALM_ACCESS_DENIED"; + public static final String REALM_ACCESS_DENIED_MESSAGE = + "This non-public realm is not available to your account."; public static final String TENANT_BILLING_BLOCKED_CODE = "TENANT_BILLING_BLOCKED"; public static final String TENANT_BILLING_BLOCKED_MESSAGE = "That world is temporarily unavailable for gameplay."; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 6e56ead86c..8ad33e958a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -714,7 +714,12 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (!response.getMembershipExists() || !response.getGameplayAdmissionAllowed()) { + if (!isValidMembershipLifecycleEvidence(response)) { + return Optional.of( + worldAccessDeniedFailure( + context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + } + if (!"ACTIVE".equals(response.getMembershipLifecycleState())) { if (isPublicProductionRealm(selectedRealm)) { if (!allowPublicJoin) { return Optional.of( @@ -741,6 +746,11 @@ private Optional validateMembershipResponse( Long.toString(requestedCharacterId), null)); } + return Optional.of( + nonPublicEnrollmentRequiredFailure( + context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + } + if (!response.getGameplayAdmissionAllowed()) { return Optional.of( worldAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); @@ -761,7 +771,7 @@ private Optional validateMembershipResponse( } if (grantError.isPresent() || !grantResponse.getGranted()) { return Optional.of( - worldAccessDeniedFailure( + realmAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } return Optional.empty(); @@ -769,6 +779,20 @@ private Optional validateMembershipResponse( return Optional.empty(); } + private boolean isValidMembershipLifecycleEvidence( + GetTenantMembershipForRuntimeResponse response) { + return switch (response.getMembershipLifecycleState()) { + case "MISSING" -> + !response.getMembershipExists() && !response.getGameplayAdmissionAllowed(); + case "INACTIVE" -> + response.getMembershipExists() + && response.getMembershipVersion() > 0L + && !response.getGameplayAdmissionAllowed(); + case "ACTIVE" -> response.getMembershipExists() && response.getMembershipVersion() > 0L; + default -> false; + }; + } + private PlayCommandHandlingResult worldAccessDeniedFailure( SessionContext context, String tenantTag, @@ -795,6 +819,58 @@ private PlayCommandHandlingResult worldAccessDeniedFailure( null); } + private PlayCommandHandlingResult nonPublicEnrollmentRequiredFailure( + SessionContext context, + String tenantTag, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + long requestedCharacterId) { + recordResumeDeniedIfApplicable( + context, + selectedWorld.slug(), + selectedRealm.slug(), + selectedRealm.pointerVersion(), + selectedRealm.gameInstanceId(), + requestedCharacterId, + tenantTag, + "non_public_enrollment_required"); + return failure( + GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE, + GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_MESSAGE, + "error.play.non-public-enrollment-required", + Map.of(), + tenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(requestedCharacterId), + null); + } + + private PlayCommandHandlingResult realmAccessDeniedFailure( + SessionContext context, + String tenantTag, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + long requestedCharacterId) { + recordResumeDeniedIfApplicable( + context, + selectedWorld.slug(), + selectedRealm.slug(), + selectedRealm.pointerVersion(), + selectedRealm.gameInstanceId(), + requestedCharacterId, + tenantTag, + "realm_access_denied"); + return failure( + GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE, + GameplayStageCommandConstants.REALM_ACCESS_DENIED_MESSAGE, + "error.play.realm-access-denied", + Map.of(), + tenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(requestedCharacterId), + null); + } + private Optional validateEntitlementsResponse( GetTenantEntitlementsForRuntimeResponse response, SessionContext context, @@ -956,9 +1032,7 @@ private boolean isSafeMembershipAuthorityResponse( } catch (DateTimeParseException | NumberFormatException ex) { return false; } - return response.getMembershipExists() - ? response.getMembershipVersion() > 0L - : response.getMembershipVersion() == 0L; + return true; } private void maybeRecordFreshEntryFallback( diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index b6a3dddfbe..539552bad3 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -20,7 +20,9 @@ error.play.character-selection-required=Selection required. Use {playUsage} or b error.play.connect-context-invalid=Connect context invalid. error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. -error.play.join-required=Membership is required before PLAY; joining this world is not available yet. +error.play.join-required=Membership is required before PLAY. Use JOIN or choose Join & Play. +error.play.non-public-enrollment-required=Existing game membership is required for this non-public realm. +error.play.realm-access-denied=This non-public realm is not available to your account. error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. error.play.entitlement-unavailable=Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. error.play.billing-blocked=That world is temporarily unavailable for gameplay. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index ddf61357e6..dc29b5e0ac 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -20,7 +20,9 @@ error.play.character-selection-required=Selection requise. Utilisez {playUsage} error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. -error.play.join-required=Une adhésion est requise avant PLAY ; rejoindre ce monde n’est pas encore disponible. +error.play.join-required=Une adhésion est requise avant PLAY. Utilisez JOIN ou choisissez « Join & Play ». +error.play.non-public-enrollment-required=Une adhésion existante est requise pour ce royaume non public. +error.play.realm-access-denied=Ce royaume non public n’est pas accessible à votre compte. error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. error.play.entitlement-unavailable=L’autorité d’abonnement est temporairement indisponible. Réessayez PLAY sous peu. error.play.billing-blocked=Ce monde est temporairement indisponible pour le jeu. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 49235e3182..6b56b01405 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -107,6 +107,7 @@ void setUp() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") @@ -1043,9 +1044,9 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( } @Test - void playDeniedByMembershipReturnsWorldAccessDenied() { + void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1054,21 +1055,21 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); PlayCommandHandlingResult result = - handler.handle( - "1", - new TextCommand( - TextCommandType.PLAY, - List.of("sandbox", "preview", "Emberline"), - "PLAY sandbox preview Emberline")); + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.world-access-denied"); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); } @Test @@ -1083,7 +1084,8 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .setAccountId("123") .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1097,7 +1099,9 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.non-public-enrollment-required"); Mockito.verify(accountClient, Mockito.never()) .getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1105,6 +1109,52 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + } + + @Test + void playNonPublicInactiveMembershipDoesNotUsePublicJoin() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setMembershipLifecycleState("INACTIVE") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(3L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.non-public-enrollment-required"); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.characterId() == 0L + && saved.gameInstanceId() == 0L + && saved.roomInstanceId() == null)); } @Test @@ -1147,7 +1197,22 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.realm-access-denied"); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.characterId() == 0L + && saved.gameInstanceId() == 0L + && saved.roomInstanceId() == null)); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq("123"), @@ -1198,8 +1263,9 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); - Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); + .isEqualTo(GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE); + Mockito.verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(context, "realm_access_denied"); } @Test @@ -1225,8 +1291,9 @@ void playInvisibleRealmWithNonAuthorityGrantClearsBinding() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); - Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); + .isEqualTo(GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE); + Mockito.verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(context, "realm_access_denied"); } @ParameterizedTest @@ -1298,8 +1365,9 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { .setAccountId("123") .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(0L) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(5L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); PlayCommandHandlingResult result = @@ -1315,6 +1383,63 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); } + @ParameterizedTest + @ValueSource(strings = {"", "ACTIVE", "UNKNOWN"}) + void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleState) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setMembershipLifecycleState(lifecycleState) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.world-access-denied"); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + } + + @ParameterizedTest + @ValueSource(strings = {"MISSING", "INACTIVE"}) + void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleState) { + boolean membershipExists = "INACTIVE".equals(lifecycleState); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(membershipExists) + .setMembershipLifecycleState(lifecycleState) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(membershipExists ? 3L : 5L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + } + @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { SessionContext context = @@ -1327,6 +1452,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("INACTIVE") .setGameplayAdmissionAllowed(false) .setMembershipVersion(4L) .setEvaluatedAt("2026-03-30T00:00:00Z") @@ -1356,7 +1482,8 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { .setAccountId("123") .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1395,7 +1522,8 @@ void playBillingDenialMasksMissingPublicMembership() { .setAccountId("123") .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1432,7 +1560,8 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { .setAccountId("123") .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1495,7 +1624,8 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti .setAccountId("123") .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("MISSING") + .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1533,6 +1663,7 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) .setEvaluatedAt("not-a-timestamp") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 2a5f7398a0..3475ff8cba 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -170,6 +170,7 @@ void setUp() { .setAccountId("77") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") @@ -462,6 +463,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { .setAccountId("77") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) .setEvaluatedAt("2026-03-30T00:01:00Z") @@ -471,7 +473,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { assertTrue(secondLogin.commandResult().accepted()); TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertFalse(deniedPlay.commandResult().accepted()); - assertEquals("JOIN_REQUIRED", deniedPlay.commandResult().errorCode()); + assertEquals("WORLD_ACCESS_DENIED", deniedPlay.commandResult().errorCode()); TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 8bdbfc2f8a..70f1fa60c2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -170,6 +170,7 @@ void setUp() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") From 7f4f1f419cf05eb9f50b9fb9dfc483c3cf400887 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 14:55:50 +1200 Subject: [PATCH 06/28] Retain Account JOIN transition receipts for bounded recovery --- .../account-service/runtime-and-data.md | 4 +- .../system-architecture-authz-route-matrix.md | 2 +- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 4 +- .../dto/MembershipTransitionReceipt.java | 14 + .../MembershipTransitionReceiptDigest.java | 114 ++++++ ...MembershipTransitionReceiptRepository.java | 367 ++++++++++++++++++ .../AccountJoinReconciliationService.java | 89 ++++- .../service/impl/AccountServiceImpl.java | 23 +- ...account_membership_transition_receipts.sql | 64 +++ .../AccountJoinPostgresIntegrationTest.java | 350 ++++++++++++++++- ...MembershipTransitionReceiptDigestTest.java | 33 ++ .../AccountJoinReconciliationServiceTest.java | 160 +++++++- .../service/impl/AccountServiceImplTest.java | 4 + 14 files changed, 1196 insertions(+), 37 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceipt.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V28__account_membership_transition_receipts.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c434f4a8af..5cc2249ef8 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,11 +16,11 @@ Account V25 enforces the live tenant-scoped profile identity `(tenantId, account Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Focused unit proof in `ExpiredCredentialCleanupJobTest` has executed locally; PostgreSQL repository integration cases in `CredentialCleanupRepositoryIntegrationTest` compile but were skipped because Docker was unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired scope cannot prove a terminal outcome: Account records a retryable unavailable attempt without entitlement evaluation or membership mutation, and only exact operation and membership/audit readback may later terminalize it. A malformed or missing bearer is rejected without inventing a terminal operation result. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. A bounded Account-owned worker now revisits due `PENDING` intents, locks and reads back exact operation, scope, membership and audit evidence, and records capped attempts with a reason and backoff when evidence is incomplete. It terminalizes only a positively proved prior transition; it cannot infer a failure from expiry or an absent row, and after its attempt cap the pending row remains visible and caller-retryable. Exact PostgreSQL concurrency and unknown-outcome proof remains open until executed. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired scope cannot prove a terminal outcome: Account records a retryable unavailable attempt without entitlement evaluation or membership mutation, and only exact operation and membership/audit readback may later terminalize it. A malformed or missing bearer is rejected without inventing a terminal operation result. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. A bounded Account-owned worker now revisits due `PENDING` intents, locks and reads back exact operation, scope, membership, provisional transition receipt, and audit evidence, and records capped attempts with a reason and backoff when evidence is incomplete. It terminalizes only a positively proved prior transition or an event-free already-active outcome with matching retained receipt history; it cannot infer a failure from expiry or an absent row, and after its attempt cap the pending row remains visible and caller-retryable. Exact PostgreSQL concurrency and unknown-outcome proof remains open until executed. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership with matching positive receipt history is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The proto and Account producer emit lifecycle state and generation, but Game Session does not validate them; `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes fail with `FAILED_PRECONDITION` before Account reads until a typed verified player/target contract and consumer are implemented. The separate Account REST connect-token issuance path consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admits only when the two admission fields are true; an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`, but the current consumer does not distinguish `INACTIVE` from another existing non-admitting lifecycle state. It does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes only exact positive operation/membership/audit proof and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The proto and Account producer emit lifecycle state and generation, but Game Session does not validate them; `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes fail with `FAILED_PRECONDITION` before Account reads until a typed verified player/target contract and consumer are implemented. The separate Account REST connect-token issuance path consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admits only when the two admission fields are true; an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`, but the current consumer does not distinguish `INACTIVE` from another existing non-admitting lifecycle state. It does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. Account still cannot treat their bare request-body `accountId`/`tenantId` as verified player or lifecycle context. These runtime reads and the similarly bare realm-grant read must reject before Account data access until the exact Game Session or World Management peer, typed caller/target context, and applicable private delegation are carried and verified. The Game Session consumer still sends the older request shape, so this containment is not a working admission path or proof of the target membership/entitlement snapshot. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 2c16878df1..329826546a 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -258,7 +258,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing; fresh issuance checks only the current four-field non-public grant row, not the lifecycle-qualified/expiring target grant and complete entitlement predicate. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Private/playtest targets require both membership and grant; global roles alone do not grant gameplay admission. | | Account Service | `Authenticate` | `internal_workload` | Exact Game Session mTLS identity, no pre-existing issued token, and trusted server-derived credential source context | | Account Service | `RefreshGameplayServiceToken` | `internal_workload` | Exact Game Session mTLS identity plus current `game-session-account-delegation` authority with audience `account-service` | -| Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus validated typed player context; no circular end-user token prerequisite. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | +| Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus current Account-issued `game-session-account-delegation` authority with audience `account-service` and validated typed player/target context. Credential-bearing `LOGIN` obtains that private token from Account authentication; bare first-party `LOGIN` requires the separate Account-owned one-use exchange over proved committed connect issuance and verified signed context. Gateway context or a connect-token `jti` alone does not authorize the read, and Game Session never passes an end-user token as a substitute. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); the RPCs remain denied until the producer and consumer proof is complete. | | Account Service | `GetTenantEntitlementsForRuntime` | `internal_workload` | Exactly one complete caller-policy alternative: Game Session mTLS plus current private delegation and typed player context for player admission, or World Management mTLS plus tenant/operation-bound instance-lifecycle context without a player delegation. Constraints within the selected alternative are conjunctive; no `control-ui` or Logging and Admin caller; not edge exposed. The read assesses eligibility only and never commits capacity. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `CommitTenantCapacityAdmission` | `internal_workload` | **Target; not currently routable.** Exactly one complete caller-policy alternative is required: Game Session presents its own exact Game Session caller workload mTLS identity to Account with typed `PlayerExecutionContext` and the live player-binding checks, or World Management presents its own exact World Management caller workload mTLS identity to Account with tenant/operation-bound instance-lifecycle context and the live lifecycle checks. Account remains the receiving authority; only those alternatives may call its exact receiving mTLS boundary. The request binds `tenantId`, stable `requestId`/`admissionId`, fresh `admissionAttemptId`, current `capacityRearmFence`, the complete Account evidence bundle including its applicable `authorityTuple`, `expected_billing_evidence`, and all `outboxCheckpoints[]`, plus a bounded `capacityDelta` whose protobuf field is `optional int64` encoded as a varint and whose canonical JSON/proto-JSON spelling is `capacityDelta` encoded as a base-10 decimal string. The machine contract explicitly distinguishes omitted (`absent`) from present zero (`present_zero`), rejects JSON `null` and boolean zero, and publishes both transport-specific golden vectors. The caller-supplied `capacity_rearm_fence` is the attempt-bound fence, while Account compares the live `capacity_admission_fence` at final commit alongside the applicable generation guards. It also carries versioned `mutationDigest` over the attempt identity, fence, and complete payload. The first attempt binds those fields without a rearm; an exact retry replays, while a changed field requires the Account-owned committed rearm CAS that advances the fence and binds the fresh attempt. Any change without that CAS is an idempotency conflict before reservation, usage, activation, or routing mutation. Account performs the final fenced reservation commit and returns the committed evidence or a canonical stale/quota/unavailable outcome; until this route is implemented, capacity-changing operations fail closed. | | Account Service | `GetTenantEntitlementsTenant` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks | diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8320c31b83..c90b5d97af 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -99,3 +99,8 @@ Entry format: - Context: a Game Session correction rejected unowned or ambiguous `PLAY` actors, while a shared Docker-backed WebSocket integration fixture still returned actor rows with protobuf-default playable scope. - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. + +- `2026-09-26`: Review status refused a shared private allocation record + - Context: during #2873 implementation, `dev-tools/pr-review status --pr 2873` returned `review allocation contains fields outside the private schema` before review intake. + - Observation: the controller could not report current review state; no review was requested or allocation edited. The cause and ownership of the private record remain unverified. + - Expected pattern: diagnose the record against the controller's current schema with its owning operator before CodeRabbit intake; do not bypass the controller or infer review eligibility from GitHub's visible state alone. 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 d665448fe5..7c70bed16b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,11 +10,13 @@ Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, G Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. +The current Unit 1B draft adds Account-owned provisional JOIN/reactivation transition receipts, separate from the canonical authority outbox. A `JOINED` recovery readback requires the matching operation, membership, receipt, and audit evidence; event-free `ALREADY_ACTIVE` requires matching positive prior receipt history. Legacy active/inactive rows without that receipt, and absent rows with retained history, fail closed rather than restart at sequence one. The receipt is not a complete authority tuple, fenced runtime snapshot, or sequence-zero absence proof. All 11 focused PostgreSQL integration cases skipped locally without Docker; their database behavior and lost-acknowledgement/concurrency remain unproved until executed. + Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. -The approved first-party bare-`LOGIN` private-delegation exchange is not implemented. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. An Account-owned one-use/idempotent exchange must establish those producer facts and exact Game Session caller binding before Game Session can receive a private delegation JWT; a forwarded context or token `jti` alone cannot authorize the exchange. The approved never-joined sequence-zero membership checkpoint likewise requires Account to prove the exact stream never committed under the same fenced snapshot as the no-row read and authenticated tuple/generation/version; no current response or consumer provides that proof. Formerly joined or left streams retain positive sequence history. Both paths remain unavailable while the runtime RPCs deny. +The approved first-party bare-`LOGIN` private-delegation exchange is not implemented. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. An Account-owned one-use/idempotent exchange must establish those producer facts and exact Game Session caller binding before Game Session can receive a private delegation JWT; a forwarded context or token `jti` alone cannot authorize the exchange. The approved never-joined sequence-zero membership checkpoint likewise requires Account to prove the exact canonical authority stream never committed under the same fenced snapshot as the no-row read and authenticated tuple/generation/version; the provisional transition receipt does not prove that condition, and no current response or consumer provides it. Formerly joined or left streams retain positive sequence history. Both paths remain unavailable while the runtime RPCs deny. Account's credential-granting gameplay gRPC methods enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Legacy profile GET/PUT now require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy batch reads require the exact Social Groups peer and remain scoped to tenant profiles. Direct account-ID export, external-link, and verification gRPC methods deny before reads or mutation because no authorized internal caller is configured. These guards do not make the broader target method/caller authority complete or restore the disabled runtime reads. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceipt.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceipt.java new file mode 100644 index 0000000000..146018cab5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceipt.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** Provisional per-membership transition receipt, not a canonical authority outbox checkpoint. */ +public record MembershipTransitionReceipt( + String receiptStreamKey, + long receiptSequence, + UUID receiptId, + String receiptDigest, + String evidenceStatus, + String transitionType, + String requestId, + long membershipId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java new file mode 100644 index 0000000000..b942e92a0c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; + +/** Deterministic SHA-256 digest for a provisional Account membership transition receipt only. */ +public final class MembershipTransitionReceiptDigest { + public static final String EVIDENCE_STATUS = "PROVISIONAL_TRANSITION_RECEIPT"; + + private static final String VERSIONED_RECEIPT_ID_PREFIX = + "account-membership-transition-receipt/v1:"; + + private MembershipTransitionReceiptDigest() {} + + public static String receiptStreamKey(long accountId, long tenantId) { + requirePositive(accountId, "accountId"); + requirePositive(tenantId, "tenantId"); + return "account:membership-transition-receipt:v1:membership/" + accountId + "/" + tenantId; + } + + public static UUID receiptIdForRequest(String requestId) { + String request = requiredField("requestId", requestId); + return UUID.nameUUIDFromBytes( + (VERSIONED_RECEIPT_ID_PREFIX + request).getBytes(StandardCharsets.UTF_8)); + } + + public static String transitionDigest( + String receiptStreamKey, + long receiptSequence, + UUID receiptId, + String transitionType, + String requestId, + long accountId, + long tenantId, + long membershipId, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance) { + requirePositive(receiptSequence, "receiptSequence"); + requirePositive(accountId, "accountId"); + requirePositive(tenantId, "tenantId"); + requirePositive(membershipId, "membershipId"); + requirePositive(membershipVersion, "membershipVersion"); + requirePositive(membershipAuthorityGeneration, "membershipAuthorityGeneration"); + String streamKey = requiredField("receiptStreamKey", receiptStreamKey); + String transition = requiredField("transitionType", transitionType); + String request = requiredField("requestId", requestId); + String lifecycleState = requiredField("membershipLifecycleState", membershipLifecycleState); + String provenance = requiredField("authorityProvenance", authorityProvenance); + if (receiptId == null) { + throw new IllegalArgumentException("receiptId is required"); + } + if (!receiptStreamKey(accountId, tenantId).equals(streamKey)) { + throw new IllegalArgumentException("receiptStreamKey does not match the membership scope"); + } + if (!("MEMBERSHIP_JOINED".equals(transition) || "MEMBERSHIP_REACTIVATED".equals(transition))) { + throw new IllegalArgumentException("transitionType is not a supported membership receipt"); + } + + String preimage = + "accountMembershipTransitionReceiptVersion=v1\n" + + field("evidenceStatus", EVIDENCE_STATUS) + + field("receiptStreamKey", streamKey) + + field("receiptSequence", receiptSequence) + + field("receiptId", receiptId) + + field("transitionType", transition) + + field("requestId", request) + + field("accountId", accountId) + + field("tenantId", tenantId) + + field("membershipId", membershipId) + + field("membershipLifecycleState", lifecycleState) + + field("gameplayAdmissionAllowed", gameplayAdmissionAllowed) + + field("membershipVersion", membershipVersion) + + field("membershipAuthorityGeneration", membershipAuthorityGeneration) + + field("authorityProvenance", provenance); + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static String field(String name, Object value) { + String wireValue = value.toString(); + requiredField(name, wireValue); + return name + "=" + wireValue + "\n"; + } + + private static String requiredField(String name, String value) { + if (value == null + || value.isBlank() + || value.indexOf('=') >= 0 + || value.indexOf('\n') >= 0 + || value.indexOf('\r') >= 0) { + throw new IllegalArgumentException(name + " has an invalid canonical wire value"); + } + return value; + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw new IllegalArgumentException(name + " must be positive"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java new file mode 100644 index 0000000000..ac9d09d207 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java @@ -0,0 +1,367 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Retains provisional Account JOIN/reactivation receipts without claiming complete authority proof. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountMembershipTransitionReceiptRepository { + private static final String MEMBERSHIP_JOINED = "MEMBERSHIP_JOINED"; + private static final String MEMBERSHIP_REACTIVATED = "MEMBERSHIP_REACTIVATED"; + + private final DSLContext dsl; + + public AccountMembershipTransitionReceiptRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Appends one provisional receipt inside the surrounding Account JOIN transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public MembershipTransitionReceipt appendTransition( + AccountTenantMembership membership, String transitionType, String requestId) { + if (membership == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getId() == null) { + throw new IllegalArgumentException("A persisted Account membership is required"); + } + long accountId = membership.getAccount().getId(); + long tenantId = membership.getTenantId(); + long membershipId = membership.getId(); + if (!MEMBERSHIP_JOINED.equals(transitionType) + && !MEMBERSHIP_REACTIVATED.equals(transitionType)) { + throw new IllegalArgumentException("Membership transition type is unsupported"); + } + if (!"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalArgumentException("JOIN receipt requires its committed active state"); + } + + String streamKey = MembershipTransitionReceiptDigest.receiptStreamKey(accountId, tenantId); + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest(requestId); + Long sequence = + (Long) + dsl.fetchValue( + "INSERT INTO account_membership_transition_receipt_stream_heads " + + "(account_id, tenant_id, receipt_stream_key, last_receipt_sequence, updated_at) " + + "VALUES (?, ?, ?, 1, CURRENT_TIMESTAMP) " + + "ON CONFLICT (account_id, tenant_id) DO UPDATE SET " + + "last_receipt_sequence = " + + "account_membership_transition_receipt_stream_heads.last_receipt_sequence + 1, " + + "updated_at = CURRENT_TIMESTAMP " + + "RETURNING last_receipt_sequence", + Long.class, + accountId, + tenantId, + streamKey); + if (sequence == null || sequence <= 0L) { + throw new IllegalStateException("Account membership receipt sequence was not allocated"); + } + String digest = + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + sequence, + receiptId, + transitionType, + requestId, + accountId, + tenantId, + membershipId, + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance()); + int inserted = + dsl.execute( + "INSERT INTO account_membership_transition_receipts " + + "(receipt_stream_key, receipt_sequence, account_id, tenant_id, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + streamKey, + sequence, + accountId, + tenantId, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + transitionType, + requestId, + membershipId, + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance(), + receiptId, + digest); + if (inserted != 1) { + throw new IllegalStateException("Account membership transition receipt was not inserted"); + } + return new MembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + digest, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + transitionType, + requestId, + membershipId); + } + + /** + * Reads and validates the latest provisional receipt. Empty does not prove a canonical + * sequence-zero stream; existing rows without a receipt fail closed. + */ + @Transactional(readOnly = true) + public Optional findLatestReceipt(long accountId, long tenantId) { + ReceiptSnapshot snapshot = readLatestReceiptSnapshot(accountId, tenantId); + if (snapshot == null) { + return Optional.empty(); + } + MembershipTransitionReceipt receipt = snapshot.receipt(); + if (receipt == null) { + return Optional.empty(); + } + Long currentMembershipId = snapshot.currentMembershipId(); + if (currentMembershipId != null + && (currentMembershipId.longValue() != receipt.membershipId() + || !"ACTIVE".equals(snapshot.currentLifecycleState()) + || !snapshot.currentAdmissionAllowed() + || snapshot.currentMembershipVersion() != snapshot.receiptMembershipVersion() + || snapshot.currentAuthorityGeneration() != snapshot.receiptAuthorityGeneration() + || !"EXPLICIT_JOIN".equals(snapshot.currentAuthorityProvenance()))) { + throw new IllegalStateException( + "Account membership row does not match its latest provisional receipt"); + } + return Optional.of(receipt); + } + + /** + * Fail-closes a new row when prior history exists or no versioned restoration path is defined. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public void assertNewMembershipTransitionCanStart(long accountId, long tenantId) { + ReceiptSnapshot snapshot = readLatestReceiptSnapshot(accountId, tenantId); + if (snapshot == null || snapshot.currentMembershipId() != null) { + throw new IllegalStateException("New Account membership transition scope is inconsistent"); + } + if (snapshot.receipt() != null) { + throw new IllegalStateException( + "Retained Account membership history has no supported restoration path"); + } + if (hasPriorMembershipHistory(accountId, tenantId)) { + throw new IllegalStateException( + "Prior Account membership history exists without a provisional transition receipt"); + } + } + + /** Requires positive retained history before reactivating an existing inactive membership. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public MembershipTransitionReceipt requireInactiveMembershipHistory( + AccountTenantMembership membership) { + if (membership == null + || membership.getId() == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getTenantId() <= 0L + || !"INACTIVE".equals(membership.getLifecycleState())) { + throw new IllegalArgumentException("A persisted inactive Account membership is required"); + } + long accountId = membership.getAccount().getId(); + long tenantId = membership.getTenantId(); + ReceiptSnapshot snapshot = readLatestReceiptSnapshot(accountId, tenantId); + if (snapshot == null + || snapshot.currentMembershipId() == null + || !snapshot.currentMembershipId().equals(membership.getId()) + || !"INACTIVE".equals(snapshot.currentLifecycleState()) + || snapshot.currentAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(snapshot.currentAuthorityProvenance()) + || snapshot.receipt() == null + || snapshot.receipt().membershipId() != membership.getId() + || snapshot.currentMembershipVersion() < snapshot.receiptMembershipVersion() + || snapshot.currentAuthorityGeneration() < snapshot.receiptAuthorityGeneration()) { + throw new IllegalStateException( + "Inactive Account membership lacks matching positive transition receipt history"); + } + return snapshot.receipt(); + } + + private ReceiptSnapshot readLatestReceiptSnapshot(long accountId, long tenantId) { + if (accountId <= 0L || tenantId <= 0L) { + throw new IllegalArgumentException("Account and tenant IDs must be positive"); + } + Record row = + dsl.fetchOne( + "SELECT h.receipt_stream_key, h.last_receipt_sequence, " + + "m.id AS current_membership_id, " + + "m.lifecycle_state AS current_lifecycle_state, " + + "m.gameplay_admission_allowed AS current_admission_allowed, " + + "m.membership_version AS current_membership_version, " + + "m.membership_authority_generation AS current_authority_generation, " + + "m.authority_provenance AS current_authority_provenance, " + + "r.receipt_sequence AS row_receipt_sequence, r.account_id AS receipt_account_id, " + + "r.tenant_id AS receipt_tenant_id, r.evidence_status, r.transition_type, " + + "r.request_id, r.membership_id AS receipt_membership_id, " + + "r.membership_lifecycle_state AS receipt_lifecycle_state, " + + "r.gameplay_admission_allowed AS receipt_admission_allowed, " + + "r.membership_version AS receipt_membership_version, " + + "r.membership_authority_generation AS receipt_authority_generation, " + + "r.authority_provenance AS receipt_authority_provenance, " + + "r.receipt_id, r.receipt_digest " + + "FROM (SELECT 1) scope " + + "LEFT JOIN account_membership_transition_receipt_stream_heads h " + + "ON h.account_id = ? AND h.tenant_id = ? " + + "LEFT JOIN account_tenant_membership m " + + "ON m.account_id = ? AND m.tenant_id = ? " + + "LEFT JOIN account_membership_transition_receipts r " + + "ON r.receipt_stream_key = h.receipt_stream_key " + + "AND r.receipt_sequence = h.last_receipt_sequence ", + accountId, + tenantId, + accountId, + tenantId); + if (row == null) { + return null; + } + Long sequence = row.get("last_receipt_sequence", Long.class); + Long currentMembershipId = row.get("current_membership_id", Long.class); + if (sequence == null) { + if (currentMembershipId != null) { + throw new IllegalStateException( + "Account membership exists without a provisional transition receipt"); + } + return new ReceiptSnapshot(null, null, null, false, 0L, 0L, null, 0L, 0L); + } + Long rowSequence = row.get("row_receipt_sequence", Long.class); + UUID receiptId = row.get("receipt_id", UUID.class); + String receiptDigest = row.get("receipt_digest", String.class); + if (sequence <= 0L + || !sequence.equals(rowSequence) + || receiptId == null + || receiptDigest == null) { + throw new IllegalStateException( + "Account membership receipt head lacks its exact retained receipt"); + } + + String streamKey = row.get("receipt_stream_key", String.class); + Long receiptAccountId = row.get("receipt_account_id", Long.class); + Long receiptTenantId = row.get("receipt_tenant_id", Long.class); + String evidenceStatus = row.get("evidence_status", String.class); + String transitionType = row.get("transition_type", String.class); + String requestId = row.get("request_id", String.class); + Long membershipId = row.get("receipt_membership_id", Long.class); + String lifecycleState = row.get("receipt_lifecycle_state", String.class); + Boolean admissionAllowed = row.get("receipt_admission_allowed", Boolean.class); + Long membershipVersion = row.get("receipt_membership_version", Long.class); + Long authorityGeneration = row.get("receipt_authority_generation", Long.class); + String authorityProvenance = row.get("receipt_authority_provenance", String.class); + if (!MembershipTransitionReceiptDigest.receiptStreamKey(accountId, tenantId).equals(streamKey) + || !Long.valueOf(accountId).equals(receiptAccountId) + || !Long.valueOf(tenantId).equals(receiptTenantId) + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(evidenceStatus) + || membershipId == null + || lifecycleState == null + || admissionAllowed == null + || membershipVersion == null + || authorityGeneration == null + || authorityProvenance == null + || requestId == null + || !receiptId.equals(MembershipTransitionReceiptDigest.receiptIdForRequest(requestId))) { + throw new IllegalStateException("Account membership receipt scope is inconsistent"); + } + String expectedDigest = + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + sequence, + receiptId, + transitionType, + requestId, + accountId, + tenantId, + membershipId, + lifecycleState, + admissionAllowed, + membershipVersion, + authorityGeneration, + authorityProvenance); + if (!expectedDigest.equals(receiptDigest)) { + throw new IllegalStateException("Account membership receipt digest is inconsistent"); + } + return new ReceiptSnapshot( + new MembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + receiptDigest, + evidenceStatus, + transitionType, + requestId, + membershipId), + currentMembershipId, + row.get("current_lifecycle_state", String.class), + Boolean.TRUE.equals(row.get("current_admission_allowed", Boolean.class)), + row.get("current_membership_version", Long.class) == null + ? 0L + : row.get("current_membership_version", Long.class), + row.get("current_authority_generation", Long.class) == null + ? 0L + : row.get("current_authority_generation", Long.class), + row.get("current_authority_provenance", String.class), + membershipVersion, + authorityGeneration); + } + + private boolean hasPriorMembershipHistory(long accountId, long tenantId) { + // A minimized JOIN audit no longer identifies its account, so it conservatively blocks this + // tenant's new stream when no retained receipt proves the membership history. + Boolean hasHistory = + (Boolean) + dsl.fetchValue( + "SELECT EXISTS (" + + "SELECT 1 FROM account_legacy_membership_sources " + + "WHERE account_id = ? AND tenant_id = ? " + + "UNION ALL SELECT 1 FROM account_join_operations " + + "WHERE account_id = ? AND tenant_id = ? " + + "AND status = 'COMMITTED' AND outcome IN ('JOINED', 'ALREADY_ACTIVE') " + + "UNION ALL SELECT 1 FROM account_audit_outbox " + + "WHERE scope = 'tenant' AND tenant_id = ? " + + "AND producer_service = 'account-service' " + + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' " + + "AND (payload IS NULL OR payload::jsonb ->> 'accountId' = CAST(? AS TEXT))" + + ")", + accountId, + tenantId, + accountId, + tenantId, + tenantId, + accountId); + return Boolean.TRUE.equals(hasHistory); + } + + private record ReceiptSnapshot( + MembershipTransitionReceipt receipt, + Long currentMembershipId, + String currentLifecycleState, + boolean currentAdmissionAllowed, + long currentMembershipVersion, + long currentAuthorityGeneration, + String currentAuthorityProvenance, + long receiptMembershipVersion, + long receiptAuthorityGeneration) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java index 19d572f060..858dd247cf 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java @@ -14,10 +14,13 @@ import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; import org.slf4j.Logger; @@ -50,6 +53,7 @@ public class AccountJoinReconciliationService { private final AccountJoinOperationRepository joinOperationRepository; private final AccountConnectScopeRepository connectScopeRepository; private final AccountTenantMembershipRepository membershipRepository; + private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; private final AccountAuditOutboxRepository auditOutboxRepository; private final TransactionTemplate joinTransactionTemplate; private final int batchSize; @@ -64,6 +68,7 @@ public AccountJoinReconciliationService( AccountJoinOperationRepository joinOperationRepository, AccountConnectScopeRepository connectScopeRepository, AccountTenantMembershipRepository membershipRepository, + AccountMembershipTransitionReceiptRepository transitionReceiptRepository, AccountAuditOutboxRepository auditOutboxRepository, MeterRegistry meterRegistry, PlatformTransactionManager transactionManager, @@ -85,6 +90,7 @@ public AccountJoinReconciliationService( this.joinOperationRepository = joinOperationRepository; this.connectScopeRepository = connectScopeRepository; this.membershipRepository = membershipRepository; + this.transitionReceiptRepository = transitionReceiptRepository; this.auditOutboxRepository = auditOutboxRepository; this.batchSize = batchSize; this.maxAttempts = maxAttempts; @@ -168,6 +174,8 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no JoinMembershipProof membership = null; AccountAuditEnvelope envelope = null; + MembershipTransitionReceipt transitionReceipt = null; + String outcome = null; if (unresolvedReason == null) { membership = membershipRepository @@ -181,15 +189,41 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no } if (unresolvedReason == null) { - envelope = - auditOutboxRepository - .findJoinEnvelopeForUpdate( - joinAuditEventId(operation.requestId()), operation.tenantId()) - .orElse(null); - if (envelope == null) { - unresolvedReason = "JOIN_AUDIT_ENVELOPE_ABSENT"; - } else if (!auditEnvelopeMatches(operation, membership, envelope)) { - unresolvedReason = "JOIN_AUDIT_ENVELOPE_UNCLEAR"; + try { + transitionReceipt = + transitionReceiptRepository + .findLatestReceipt(operation.accountId(), operation.tenantId()) + .orElse(null); + } catch (RuntimeException ex) { + unresolvedReason = "MEMBERSHIP_TRANSITION_RECEIPT_UNAVAILABLE"; + } + if (unresolvedReason == null && transitionReceipt == null) { + unresolvedReason = "MEMBERSHIP_TRANSITION_RECEIPT_ABSENT"; + } else if (unresolvedReason == null) { + envelope = + auditOutboxRepository + .findJoinEnvelopeForUpdate( + joinAuditEventId(operation.requestId()), operation.tenantId()) + .orElse(null); + if (Objects.equals(operation.requestId(), transitionReceipt.requestId())) { + if (!transitionReceiptMatches(operation, membership, transitionReceipt)) { + unresolvedReason = "MEMBERSHIP_TRANSITION_RECEIPT_MISMATCH"; + } else if (envelope == null) { + unresolvedReason = "JOIN_AUDIT_ENVELOPE_ABSENT"; + } else if (!auditEnvelopeMatches(operation, membership, envelope)) { + unresolvedReason = "JOIN_AUDIT_ENVELOPE_UNCLEAR"; + } else { + outcome = "JOINED"; + } + } else if (!existingMembershipHistoryMatches(operation, membership, transitionReceipt)) { + unresolvedReason = "MEMBERSHIP_TRANSITION_RECEIPT_MISMATCH"; + } else if (envelope != null) { + // A request-specific audit without its matching transition receipt is contradictory. + unresolvedReason = "JOIN_AUDIT_ENVELOPE_UNCLEAR"; + } else { + // Existing active membership/history proves ALREADY_ACTIVE; this path writes no events. + outcome = "ALREADY_ACTIVE"; + } } } @@ -200,7 +234,7 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no joinOperationRepository.finish( operation.requestId(), "COMMITTED", - "JOINED", + outcome, membership.membershipId(), membership.membershipVersion(), membership.membershipAuthorityGeneration()); @@ -324,6 +358,41 @@ private static boolean auditEnvelopeMatches( && Objects.equals(payload.requestId(), operation.requestId()); } + private static boolean transitionReceiptMatches( + JoinOperation operation, + JoinMembershipProof membership, + MembershipTransitionReceipt receipt) { + return MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(receipt.evidenceStatus()) + && MembershipTransitionReceiptDigest.receiptStreamKey( + operation.accountId(), operation.tenantId()) + .equals(receipt.receiptStreamKey()) + && receipt.receiptSequence() > 0L + && MembershipTransitionReceiptDigest.receiptIdForRequest(operation.requestId()) + .equals(receipt.receiptId()) + && Objects.equals(receipt.requestId(), operation.requestId()) + && receipt.membershipId() == membership.membershipId() + && ("MEMBERSHIP_JOINED".equals(receipt.transitionType()) + || "MEMBERSHIP_REACTIVATED".equals(receipt.transitionType())); + } + + private static boolean existingMembershipHistoryMatches( + JoinOperation operation, + JoinMembershipProof membership, + MembershipTransitionReceipt receipt) { + return !Objects.equals(operation.requestId(), receipt.requestId()) + && MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(receipt.evidenceStatus()) + && MembershipTransitionReceiptDigest.receiptStreamKey( + operation.accountId(), operation.tenantId()) + .equals(receipt.receiptStreamKey()) + && receipt.receiptSequence() > 0L + && receipt.requestId() != null + && MembershipTransitionReceiptDigest.receiptIdForRequest(receipt.requestId()) + .equals(receipt.receiptId()) + && receipt.membershipId() == membership.membershipId() + && ("MEMBERSHIP_JOINED".equals(receipt.transitionType()) + || "MEMBERSHIP_REACTIVATED".equals(receipt.transitionType())); + } + private static JoinAuditPayload parseJoinAuditPayload(String json) { try { JsonNode root = AUDIT_JSON.readTree(json); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 61f3d8021b..902c970331 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -68,6 +68,7 @@ import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -122,6 +123,7 @@ public class AccountServiceImpl implements AccountService { private final AccountAuditOutboxRepository accountAuditOutboxRepository; private final AccountConnectScopeRepository accountConnectScopeRepository; private final AccountJoinOperationRepository accountJoinOperationRepository; + private final AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -152,6 +154,7 @@ public AccountServiceImpl( AccountAuditOutboxRepository accountAuditOutboxRepository, AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, + AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, AccountTenantMembershipRepository accountTenantMembershipRepository, @@ -177,6 +180,7 @@ public AccountServiceImpl( this.accountAuditOutboxRepository = accountAuditOutboxRepository; this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; + this.membershipTransitionReceiptRepository = membershipTransitionReceiptRepository; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; this.accountTenantMembershipRepository = accountTenantMembershipRepository; @@ -683,7 +687,10 @@ private JoinPublicProductionResult executeJoinAttempt( .findByAccountIdAndTenantId(accountId, scope.tenantId()) .orElse(null); boolean transitioned = false; + String membershipTransitionType = null; if (membership == null) { + membershipTransitionReceiptRepository.assertNewMembershipTransitionCanStart( + accountId, scope.tenantId()); membership = new AccountTenantMembership(); membership.setAccount(requireAccount(accountId)); membership.setTenantId(scope.tenantId()); @@ -694,7 +701,9 @@ private JoinPublicProductionResult executeJoinAttempt( membership.setAuthorityProvenance("EXPLICIT_JOIN"); accountTenantMembershipRepository.save(membership); transitioned = true; + membershipTransitionType = "MEMBERSHIP_JOINED"; } else if ("INACTIVE".equals(membership.getLifecycleState())) { + membershipTransitionReceiptRepository.requireInactiveMembershipHistory(membership); accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); membership.setLifecycleState("ACTIVE"); membership.setGameplayAdmissionAllowed(true); @@ -704,11 +713,21 @@ private JoinPublicProductionResult executeJoinAttempt( membership.setAuthorityProvenance("EXPLICIT_JOIN"); accountTenantMembershipRepository.save(membership); transitioned = true; - } else if (!"ACTIVE".equals(membership.getLifecycleState()) - || !membership.isGameplayAdmissionAllowed()) { + membershipTransitionType = "MEMBERSHIP_REACTIVATED"; + } else if ("ACTIVE".equals(membership.getLifecycleState()) + && membership.isGameplayAdmissionAllowed()) { + membershipTransitionReceiptRepository + .findLatestReceipt(accountId, scope.tenantId()) + .orElseThrow( + () -> + new IllegalStateException( + "Active Account membership lacks a provisional transition receipt")); + } else { return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); } if (transitioned) { + membershipTransitionReceiptRepository.appendTransition( + membership, membershipTransitionType, requestId); String payload = AUDIT_JSON.writeValueAsString( new JoinAuditPayload( diff --git a/services/account-service/src/main/resources/db/migration/V28__account_membership_transition_receipts.sql b/services/account-service/src/main/resources/db/migration/V28__account_membership_transition_receipts.sql new file mode 100644 index 0000000000..a9f29d47d9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V28__account_membership_transition_receipts.sql @@ -0,0 +1,64 @@ +-- Provisional transition receipts retain exact Account JOIN/reactivation history without +-- claiming the full authorityTuple or issuanceFence required by the canonical authority outbox. +-- Their distinct stream key cannot consume canonical account:auth-authority:v1 sequence values. +CREATE TABLE account_membership_transition_receipt_stream_heads ( + account_id BIGINT NOT NULL CHECK (account_id > 0), + tenant_id BIGINT NOT NULL CHECK (tenant_id > 0), + receipt_stream_key VARCHAR(256) NOT NULL, + last_receipt_sequence BIGINT NOT NULL CHECK (last_receipt_sequence > 0), + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_membership_transition_receipt_stream_heads_pk + PRIMARY KEY (account_id, tenant_id), + CONSTRAINT account_membership_transition_receipt_stream_heads_key_unique + UNIQUE (receipt_stream_key), + CONSTRAINT account_membership_transition_receipt_stream_heads_key_check + CHECK (receipt_stream_key = + 'account:membership-transition-receipt:v1:membership/' + || account_id::TEXT || '/' || tenant_id::TEXT) +); + +CREATE TABLE account_membership_transition_receipts ( + receipt_stream_key VARCHAR(256) NOT NULL, + receipt_sequence BIGINT NOT NULL CHECK (receipt_sequence > 0), + account_id BIGINT NOT NULL CHECK (account_id > 0), + tenant_id BIGINT NOT NULL CHECK (tenant_id > 0), + evidence_status VARCHAR(48) NOT NULL, + transition_type VARCHAR(32) NOT NULL, + request_id VARCHAR(128) NOT NULL, + membership_id BIGINT NOT NULL CHECK (membership_id > 0), + membership_lifecycle_state VARCHAR(32) NOT NULL, + gameplay_admission_allowed BOOLEAN NOT NULL, + membership_version BIGINT NOT NULL CHECK (membership_version > 0), + membership_authority_generation BIGINT NOT NULL CHECK (membership_authority_generation > 0), + authority_provenance VARCHAR(32) NOT NULL, + receipt_id UUID NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_membership_transition_receipts_pk + PRIMARY KEY (receipt_stream_key, receipt_sequence), + CONSTRAINT account_membership_transition_receipts_id_unique + UNIQUE (receipt_id), + CONSTRAINT account_membership_transition_receipts_request_unique + UNIQUE (request_id), + CONSTRAINT account_membership_transition_receipts_stream_fk + FOREIGN KEY (account_id, tenant_id) + REFERENCES account_membership_transition_receipt_stream_heads (account_id, tenant_id) + ON DELETE RESTRICT, + CONSTRAINT account_membership_transition_receipts_key_check + CHECK (receipt_stream_key = + 'account:membership-transition-receipt:v1:membership/' + || account_id::TEXT || '/' || tenant_id::TEXT), + CONSTRAINT account_membership_transition_receipts_status_check + CHECK (evidence_status = 'PROVISIONAL_TRANSITION_RECEIPT'), + CONSTRAINT account_membership_transition_receipts_transition_check + CHECK (transition_type IN ('MEMBERSHIP_JOINED', 'MEMBERSHIP_REACTIVATED')), + CONSTRAINT account_membership_transition_receipts_state_check + CHECK (membership_lifecycle_state = 'ACTIVE' + AND gameplay_admission_allowed = TRUE + AND authority_provenance = 'EXPLICIT_JOIN'), + CONSTRAINT account_membership_transition_receipts_digest_check + CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE INDEX idx_account_membership_transition_receipts_latest + ON account_membership_transition_receipts (account_id, tenant_id, receipt_sequence DESC); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index d86af7f70a..c5be5579ba 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -20,7 +20,10 @@ import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; @@ -79,6 +82,9 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; + @Autowired + private AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; + @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private LoggingAdminClient loggingAdminClient; @@ -180,6 +186,7 @@ void rolledBackTerminalAttemptStaysPendingAndSameRequestCommitsOnceOnRetry() { }); assertThat(countMemberships(fixture)).isZero(); assertThat(countJoinOutbox(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); JoinPublicProductionResult recovered = join(fixture); @@ -247,12 +254,227 @@ void failedJoinReplaysStoredOutcomeAndRejectsChangedPolicyDigest() { .isEqualTo("FAILED:PUBLIC_PRODUCTION_ADMISSION_DENIED"); assertThat(countMemberships(fixture)).isZero(); assertThat(countJoinOutbox(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + } + + @Test + void exactJoinRetryDoesNotAppendAnotherMembershipTransitionReceipt() { + JoinFixture fixture = fixture("active"); + + JoinPublicProductionResult joined = join(fixture); + JoinPublicProductionResult replayed = join(fixture); + + assertThat(joined.success()).isTrue(); + assertThat(joined.outcomeCode()).isEqualTo("JOINED"); + assertThat(replayed.replayed()).isTrue(); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); + } + + @Test + void newRequestForRetainedActiveMembershipIsEventFreeAndRequiresPositiveHistory() { + JoinFixture initialJoin = fixture("active"); + assertThat(join(initialJoin).outcomeCode()).isEqualTo("JOINED"); + JoinFixture alreadyActive = fixtureForMembership(initialJoin); + + JoinPublicProductionResult result = join(alreadyActive); + + assertThat(result.success()).isTrue(); + assertThat(result.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(countMembershipTransitionReceipts(alreadyActive)).isEqualTo(1L); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + assertThat(countTenantJoinOutboxEvents(initialJoin)).isEqualTo(1L); + assertThat(countTenantJoinOutboxEvents(alreadyActive)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_join_operations " + + "WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'ALREADY_ACTIVE'", + alreadyActive.requestId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void membershipTransitionReceiptSequenceIsIndependentForEachAccountTenantStream() { + JoinFixture first = fixture("active"); + JoinFixture second = fixture("active", first.accountId()); + + assertThat(join(first).success()).isTrue(); + assertThat(join(second).success()).isTrue(); + + assertMembershipTransitionReceipt(first, "MEMBERSHIP_JOINED", 1L); + assertMembershipTransitionReceipt(second, "MEMBERSHIP_JOINED", 1L); + assertThat(receiptStreamKey(first)).isNotEqualTo(receiptStreamKey(second)); + } + + @Test + void reactivationAppendsTheNextPositiveMembershipTransitionReceiptSequence() { + JoinFixture initialJoin = fixture("active"); + assertThat(join(initialJoin).success()).isTrue(); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + + "gameplay_admission_allowed = FALSE WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); + JoinFixture reactivation = fixtureForMembership(initialJoin); + + JoinPublicProductionResult result = join(reactivation); + + assertThat(result.success()).isTrue(); + assertThat(result.outcomeCode()).isEqualTo("JOINED"); + assertMembershipTransitionReceipt(reactivation, "MEMBERSHIP_REACTIVATED", 2L); + assertThat(countMembershipTransitionReceipts(reactivation)).isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT membership_version, membership_authority_generation " + + "FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + reactivation.accountId(), + reactivation.tenantId()) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("membership_version", Long.class)).isEqualTo(2L); + assertThat(row.get("membership_authority_generation", Long.class)).isEqualTo(2L); + }); + } + + @Test + void committedMembershipTransitionReceiptHistorySurvivesAbsenceOfCurrentMembershipRow() { + JoinFixture fixture = fixture("active"); + assertThat(join(fixture).success()).isTrue(); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); + + dsl.execute("DELETE FROM account_join_operations WHERE request_id = ?", fixture.requestId()); + + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()); + + assertThat(countMemberships(fixture)).isZero(); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); + } + + @Test + void absentMembershipWithPriorAuditHistoryCannotRestartAtSequenceOne() { + JoinFixture initialJoin = fixture("active"); + assertThat(join(initialJoin).success()).isTrue(); + dsl.execute( + "DELETE FROM account_membership_transition_receipts WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); + dsl.execute( + "DELETE FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); + dsl.execute( + "DELETE FROM account_join_operations WHERE request_id = ?", initialJoin.requestId()); + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); + JoinFixture retry = fixtureForMembership(initialJoin); + + AuthenticationException blocked = + assertThrows(AuthenticationException.class, () -> join(retry)); + + assertThat(blocked.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(countMemberships(retry)).isZero(); + assertThat(countMembershipTransitionReceipts(retry)).isZero(); + assertThat(countTenantJoinOutboxEvents(retry)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT status FROM account_join_operations WHERE request_id = ?", + retry.requestId()) + .fetchOne(0, String.class)) + .isEqualTo("PENDING"); + } + + @Test + void absentMembershipWithRetainedReceiptFailsClosedWithoutResettingSequence() { + JoinFixture initialJoin = fixture("active"); + assertThat(join(initialJoin).success()).isTrue(); + dsl.execute( + "DELETE FROM account_join_operations WHERE request_id = ?", initialJoin.requestId()); + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); + JoinFixture retry = fixtureForMembership(initialJoin); + + AuthenticationException blocked = + assertThrows(AuthenticationException.class, () -> join(retry)); + + assertThat(blocked.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(countMemberships(retry)).isZero(); + assertThat(countMembershipTransitionReceipts(retry)).isEqualTo(1L); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + assertThat(countTenantJoinOutboxEvents(retry)).isEqualTo(1L); + } + + @Test + void retainedActiveOrInactiveMembershipWithoutTransitionReceiptFailsClosed() { + JoinFixture active = fixture("active"); + JoinFixture inactive = fixture("active"); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'EXPLICIT_JOIN')", + active.accountId(), + active.tenantId()); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'INACTIVE', 1, 1, 'EXPLICIT_JOIN')", + inactive.accountId(), + inactive.tenantId()); + + IllegalStateException activeFailure = + assertThrows( + IllegalStateException.class, + () -> + membershipTransitionReceiptRepository.findLatestReceipt( + active.accountId(), active.tenantId())); + IllegalStateException inactiveFailure = + assertThrows( + IllegalStateException.class, + () -> + membershipTransitionReceiptRepository.findLatestReceipt( + inactive.accountId(), inactive.tenantId())); + + assertThat(activeFailure) + .hasMessageContaining("Account membership exists without a provisional transition receipt"); + assertThat(inactiveFailure) + .hasMessageContaining("Account membership exists without a provisional transition receipt"); + assertThat(countMembershipTransitionReceipts(active)).isZero(); + assertThat(countMembershipTransitionReceipts(inactive)).isZero(); + + AuthenticationException activeJoinFailure = + assertThrows(AuthenticationException.class, () -> join(active)); + AuthenticationException inactiveJoinFailure = + assertThrows(AuthenticationException.class, () -> join(inactive)); + + assertThat(activeJoinFailure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(inactiveJoinFailure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(countMembershipTransitionReceipts(active)).isZero(); + assertThat(countMembershipTransitionReceipts(inactive)).isZero(); + assertThat( + dsl.resultQuery( + "SELECT lifecycle_state FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?", + inactive.accountId(), + inactive.tenantId()) + .fetchOne(0, String.class)) + .isEqualTo("INACTIVE"); } private JoinFixture fixture(String subscriptionStatus) { String suffix = UUID.randomUUID().toString(); - String requestId = "join-proof-" + suffix; - long tenantId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; long accountId = Objects.requireNonNull( dsl.resultQuery( @@ -261,12 +483,33 @@ private JoinFixture fixture(String subscriptionStatus) { "join-proof-" + suffix + "@example.com", "test-hash") .fetchOne(0, Long.class)); - dsl.execute( - "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) VALUES (?, ?, ?, ?, 1)", - accountId, - tenantId, - "join-proof", - subscriptionStatus); + return fixture(subscriptionStatus, accountId, null, suffix); + } + + private JoinFixture fixture(String subscriptionStatus, long accountId) { + return fixture(subscriptionStatus, accountId, null, UUID.randomUUID().toString()); + } + + private JoinFixture fixtureForMembership(JoinFixture existing) { + return fixture( + "active", existing.accountId(), existing.tenantId(), UUID.randomUUID().toString()); + } + + private JoinFixture fixture( + String subscriptionStatus, long accountId, Long existingTenantId, String suffix) { + String requestId = "join-proof-" + suffix; + long tenantId = + existingTenantId == null + ? UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE + : existingTenantId; + if (existingTenantId == null) { + dsl.execute( + "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) VALUES (?, ?, ?, ?, 1)", + accountId, + tenantId, + "join-proof", + subscriptionStatus); + } GameplayRealm realm = GameplayRealm.newBuilder() @@ -352,6 +595,95 @@ private long countJoinOutbox(JoinFixture fixture) { .fetchOne(0, Long.class)); } + private long countTenantJoinOutboxEvents(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE scope = 'tenant' " + + "AND tenant_id = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private long countMembershipTransitionReceipts(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private String receiptStreamKey(JoinFixture fixture) { + return MembershipTransitionReceiptDigest.receiptStreamKey( + fixture.accountId(), fixture.tenantId()); + } + + private void assertMembershipTransitionReceipt( + JoinFixture fixture, String transitionType, long expectedSequence) { + var row = + dsl.resultQuery( + "SELECT receipt_stream_key, receipt_sequence, evidence_status, transition_type, " + + "request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, " + + "receipt_digest FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? AND receipt_sequence = ?", + fixture.accountId(), + fixture.tenantId(), + expectedSequence) + .fetchOne(); + assertThat(row).isNotNull(); + String streamKey = row.get("receipt_stream_key", String.class); + long sequence = row.get("receipt_sequence", Long.class); + UUID receiptId = row.get("receipt_id", UUID.class); + String receiptDigest = row.get("receipt_digest", String.class); + long membershipId = row.get("membership_id", Long.class); + String lifecycleState = row.get("membership_lifecycle_state", String.class); + boolean admissionAllowed = row.get("gameplay_admission_allowed", Boolean.class); + long membershipVersion = row.get("membership_version", Long.class); + long authorityGeneration = row.get("membership_authority_generation", Long.class); + String authorityProvenance = row.get("authority_provenance", String.class); + String requestId = row.get("request_id", String.class); + + assertThat(streamKey).isEqualTo(receiptStreamKey(fixture)); + assertThat(sequence).isEqualTo(expectedSequence); + String evidenceStatus = row.get("evidence_status", String.class); + assertThat(evidenceStatus).isEqualTo(MembershipTransitionReceiptDigest.EVIDENCE_STATUS); + assertThat(row.get("transition_type", String.class)).isEqualTo(transitionType); + assertThat(receiptId) + .isEqualTo(MembershipTransitionReceiptDigest.receiptIdForRequest(requestId)); + assertThat(receiptDigest) + .isEqualTo( + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + sequence, + receiptId, + transitionType, + requestId, + fixture.accountId(), + fixture.tenantId(), + membershipId, + lifecycleState, + admissionAllowed, + membershipVersion, + authorityGeneration, + authorityProvenance)); + assertThat( + membershipTransitionReceiptRepository.findLatestReceipt( + fixture.accountId(), fixture.tenantId())) + .contains( + new MembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + receiptDigest, + evidenceStatus, + transitionType, + requestId, + membershipId)); + } + private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long membershipId) { assertThat(countMemberships(fixture)).isEqualTo(1L); assertThat( @@ -363,6 +695,8 @@ private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long member .fetchOne(0, Long.class)) .isEqualTo(1L); assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); assertThat( dsl.resultQuery( "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND payload LIKE ?", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java new file mode 100644 index 0000000000..e37dd11419 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class MembershipTransitionReceiptDigestTest { + @Test + void joinsUseTheNamespacedProvisionalReceiptIdentityAndDigestVector() { + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest("join-request-1"); + + assertThat(MembershipTransitionReceiptDigest.receiptStreamKey(42L, 7L)) + .isEqualTo("account:membership-transition-receipt:v1:membership/42/7"); + assertThat(receiptId).isEqualTo(UUID.fromString("171e5793-c53b-3308-934c-bdd7b7c0e13a")); + assertThat( + MembershipTransitionReceiptDigest.transitionDigest( + "account:membership-transition-receipt:v1:membership/42/7", + 1L, + receiptId, + "MEMBERSHIP_JOINED", + "join-request-1", + 42L, + 7L, + 18L, + "ACTIVE", + true, + 3L, + 4L, + "EXPLICIT_JOIN")) + .isEqualTo("sha256:2a07588ddf2444d1b4304cf5bd746365640fc30a2474dc3d0dbe0787d7cc494c"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java index 39f2ba7942..910654622a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java @@ -21,12 +21,15 @@ import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.ConnectScopeEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; import org.junit.jupiter.api.Test; @@ -59,8 +62,7 @@ void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()))); @@ -79,9 +81,92 @@ void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { MEMBERSHIP_AUTHORITY_GENERATION); verify(fixture.joinOperations, never()) .recordReconciliationAttempt(anyString(), anyInt(), anyInt(), any(), anyString(), any()); + verify(fixture.transitionReceipts).findLatestReceipt(ACCOUNT_ID, TENANT_ID); + verify(fixture.auditOutbox).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); assertThat(reconciliationCounter(fixture, "committed")).isEqualTo(1); } + @Test + void priorMembershipHistoryCommitsEventFreeAlreadyActiveOutcome() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending, 3); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + stubReceiptFor(fixture, "prior-join-request", MEMBERSHIP_ID); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.empty()); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .finish( + REQUEST_ID, + "COMMITTED", + "ALREADY_ACTIVE", + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION); + verify(fixture.transitionReceipts).findLatestReceipt(ACCOUNT_ID, TENANT_ID); + verify(fixture.auditOutbox).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); + verify(fixture.auditOutbox, never()) + .append(any(), anyString(), any(), anyString(), anyString()); + } + + @Test + void mismatchedPriorMembershipReceiptStaysPending() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending, 3); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + stubReceiptFor(fixture, "prior-join-request", MEMBERSHIP_ID + 1L); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "MEMBERSHIP_TRANSITION_RECEIPT_MISMATCH", NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "MEMBERSHIP_TRANSITION_RECEIPT_MISMATCH", NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + + @Test + void missingTransitionReceiptDoesNotInferJoinedFromMembershipAndAuditAlone() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending, 3); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + when(fixture.transitionReceipts.findLatestReceipt(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "MEMBERSHIP_TRANSITION_RECEIPT_ABSENT", NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "MEMBERSHIP_TRANSITION_RECEIPT_ABSENT", NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions(fixture.auditOutbox); + } + @Test void missingMembershipAfterScopeExpiryStaysPendingAndRecordsBackoffReason() { Fixture fixture = fixture(3); @@ -115,8 +200,7 @@ void absentJoinAuditStaysPendingAndLogsAttemptLimitMetric() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn(Optional.empty()); when(fixture.joinOperations.recordReconciliationAttempt( @@ -141,8 +225,7 @@ void wrongPayloadDigestStaysPending() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, sha256("wrong")))); when(fixture.joinOperations.recordReconciliationAttempt( @@ -166,8 +249,7 @@ void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); String mismatchedPayload = joinAuditEnvelope("other-world", TENANT_ID, "unused").payload(); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn( @@ -206,7 +288,7 @@ void wrongRetainedTargetStaysPending() { REQUEST_ID, 0, 3, NOW, "JOIN_SCOPE_EVIDENCE_MISMATCH", NOW.plusMillis(5_000)); verify(fixture.joinOperations, never()) .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); - verifyNoInteractions(fixture.memberships, fixture.auditOutbox); + verifyNoInteractions(fixture.memberships, fixture.transitionReceipts, fixture.auditOutbox); } @Test @@ -218,8 +300,7 @@ void repeatedRunDoesNotFinishSameJoinTwice() { when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); - when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) - .thenReturn(Optional.of(activeJoinMembership())); + stubActiveMembership(fixture); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()))); @@ -257,13 +338,19 @@ void concurrentCallerTerminalizationIsSkippedAfterAccountAndOperationLocks() { .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); verify(fixture.joinOperations, never()) .recordReconciliationAttempt(anyString(), anyInt(), anyInt(), any(), anyString(), any()); - verifyNoInteractions(fixture.connectScopes, fixture.memberships, fixture.auditOutbox); + verifyNoInteractions( + fixture.connectScopes, + fixture.memberships, + fixture.transitionReceipts, + fixture.auditOutbox); } private static Fixture fixture(int maxAttempts) { AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); AccountConnectScopeRepository connectScopes = mock(AccountConnectScopeRepository.class); AccountTenantMembershipRepository memberships = mock(AccountTenantMembershipRepository.class); + AccountMembershipTransitionReceiptRepository transitionReceipts = + mock(AccountMembershipTransitionReceiptRepository.class); AccountAuditOutboxRepository auditOutbox = mock(AccountAuditOutboxRepository.class); PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); when(transactionManager.getTransaction(any(TransactionDefinition.class))) @@ -274,6 +361,7 @@ private static Fixture fixture(int maxAttempts) { joinOperations, connectScopes, memberships, + transitionReceipts, auditOutbox, meterRegistry, transactionManager, @@ -281,7 +369,52 @@ private static Fixture fixture(int maxAttempts) { maxAttempts, 5_000); return new Fixture( - service, joinOperations, connectScopes, memberships, auditOutbox, meterRegistry); + service, + joinOperations, + connectScopes, + memberships, + transitionReceipts, + auditOutbox, + meterRegistry); + } + + private static void stubActiveMembership(Fixture fixture) { + when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(activeJoinMembership())); + stubReceiptFor(fixture, REQUEST_ID, MEMBERSHIP_ID); + } + + private static void stubReceiptFor(Fixture fixture, String requestId, long membershipId) { + String receiptStreamKey = + MembershipTransitionReceiptDigest.receiptStreamKey(ACCOUNT_ID, TENANT_ID); + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest(requestId); + String receiptDigest = + MembershipTransitionReceiptDigest.transitionDigest( + receiptStreamKey, + 1L, + receiptId, + "MEMBERSHIP_JOINED", + requestId, + ACCOUNT_ID, + TENANT_ID, + membershipId, + "ACTIVE", + true, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION, + "EXPLICIT_JOIN"); + when(fixture.transitionReceipts.findLatestReceipt(ACCOUNT_ID, TENANT_ID)) + .thenReturn( + Optional.of( + new MembershipTransitionReceipt( + receiptStreamKey, + 1L, + receiptId, + receiptDigest, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_JOINED", + requestId, + membershipId))); } private static void stubDue(Fixture fixture, JoinOperation operation, int maxAttempts) { @@ -495,6 +628,7 @@ private record Fixture( AccountJoinOperationRepository joinOperations, AccountConnectScopeRepository connectScopes, AccountTenantMembershipRepository memberships, + AccountMembershipTransitionReceiptRepository transitionReceipts, AccountAuditOutboxRepository auditOutbox, SimpleMeterRegistry meterRegistry) {} } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index ae00e6a901..b4dd6a252b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -49,6 +49,7 @@ import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -87,6 +88,7 @@ class AccountServiceImplTest { @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @Mock private AccountJoinOperationRepository accountJoinOperationRepository; + @Mock private AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @Mock private AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -197,6 +199,7 @@ void setup() { accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, + membershipTransitionReceiptRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -1575,6 +1578,7 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, + membershipTransitionReceiptRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, From 9971b33118215fc48a9711ca5a0f39cc328eec90 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 15:20:54 +1200 Subject: [PATCH 07/28] Repair Account receipt SQL and CI fixtures --- design/project-management/ai-observations.md | 4 ++-- .../AccountMembershipTransitionReceiptRepository.java | 7 +++---- .../AccountJoinPostgresIntegrationTest.java | 7 ++++++- .../command/text/FriendsCommandHandler.java | 11 ++--------- .../gamesession/command/text/PlayCommandHandler.java | 5 ++--- .../command/text/FriendsCommandHandlerTest.java | 10 ++++------ .../command/text/WhoCommandHandlerTest.java | 8 +++----- .../impl/GameplayPresenceRoleClassifierTest.java | 5 ++++- .../impl/RedisGameplayPresenceServiceTest.java | 7 +------ .../websocket/WebSocketOutputProjectorTest.java | 3 +-- 10 files changed, 28 insertions(+), 39 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index c633bc0884..c9061bfbb6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -102,8 +102,8 @@ Entry format: - `2026-09-26`: Review status refused a shared private allocation record - Context: during #2873 implementation, `dev-tools/pr-review status --pr 2873` returned `review allocation contains fields outside the private schema` before review intake. - - Observation: the controller could not report current review state; no review was requested or allocation edited. The cause and ownership of the private record remain unverified. - - Expected pattern: diagnose the record against the controller's current schema with its owning operator before CodeRabbit intake; do not bypass the controller or infer review eligibility from GitHub's visible state alone. + - Observation: the shared `2818` review allocation contains historical `stop_*` and retained-ambiguity fields that this worktree's `ReviewAllocation.from_dict` does not recognize. The controller could not report current review state; no review was requested or allocation edited. This is a cross-worktree private-state/schema mismatch, not evidence that #2873 has a review allocation. + - Expected pattern: reconcile the shared record against the controller version that wrote it with the owning operator before CodeRabbit intake; do not bypass the controller, delete private evidence, or infer review eligibility from GitHub's visible state alone. - `2026-09-26`: One-shot certificate issuance and readback require separate proof - Context: the Entity baseline migrator needs a short-lived dedicated client identity without giving its certificate writer general Secret-read or deletion privileges. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java index ac9d09d207..ef4bfaf8ef 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java @@ -55,8 +55,7 @@ public MembershipTransitionReceipt appendTransition( String streamKey = MembershipTransitionReceiptDigest.receiptStreamKey(accountId, tenantId); UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest(requestId); Long sequence = - (Long) - dsl.fetchValue( + dsl.resultQuery( "INSERT INTO account_membership_transition_receipt_stream_heads " + "(account_id, tenant_id, receipt_stream_key, last_receipt_sequence, updated_at) " + "VALUES (?, ?, ?, 1, CURRENT_TIMESTAMP) " @@ -65,10 +64,10 @@ public MembershipTransitionReceipt appendTransition( + "account_membership_transition_receipt_stream_heads.last_receipt_sequence + 1, " + "updated_at = CURRENT_TIMESTAMP " + "RETURNING last_receipt_sequence", - Long.class, accountId, tenantId, - streamKey); + streamKey) + .fetchOne(0, Long.class); if (sequence == null || sequence <= 0L) { throw new IllegalStateException("Account membership receipt sequence was not allocated"); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index c5be5579ba..b3c09f1bd5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -8,7 +8,9 @@ import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; @@ -90,6 +92,7 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private LoggingAdminClient loggingAdminClient; @MockitoBean private JavaMailSender mailSender; @MockitoSpyBean private AccountJoinOperationRepository joinOperationRepository; + private final Map fixtureRealms = new LinkedHashMap<>(); @Test void terminalCommitWithLostAcknowledgementReadsBackExactStoredJoinResult() { @@ -539,7 +542,9 @@ private JoinFixture fixture( .setPublicProductionRealm(true) .setStateScope("SHARED") .build(); - when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + fixtureRealms.put(tenantId, realm); + when(gameSessionClient.listGameplayRealms(WORLD_SLUG)) + .thenReturn(List.copyOf(fixtureRealms.values())); when(gameSessionClient.getAdmissionPointer(tenantId, WORLD_SLUG, REALM_SLUG)) .thenReturn(pointer); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index a4cbb18be3..14257ef208 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java @@ -432,11 +432,7 @@ private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry en FriendPresenceEntry presence = entry.getPresence(); long friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); if (!isPlayerDisclosablePolicy(presence.getVisibilityPolicy())) { - return redactedEntry( - ordinal, - entry, - friendAccountId, - "Friend #" + friendAccountId); + return redactedEntry(ordinal, entry, friendAccountId, "Friend #" + friendAccountId); } String characterName = presence.getCharacterName().isBlank() ? null : presence.getCharacterName().trim(); @@ -462,10 +458,7 @@ private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry en } private FriendPresenceViewOutput.Entry redactedEntry( - int ordinal, - FriendRosterEntry entry, - long friendAccountId, - String displayName) { + int ordinal, FriendRosterEntry entry, long friendAccountId, String displayName) { return new FriendPresenceViewOutput.Entry( ordinal, parseOptionalLong(entry.getFriendLinkId()), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 8ad33e958a..b4e70732ea 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -780,10 +780,9 @@ private Optional validateMembershipResponse( } private boolean isValidMembershipLifecycleEvidence( - GetTenantMembershipForRuntimeResponse response) { + GetTenantMembershipForRuntimeResponse response) { return switch (response.getMembershipLifecycleState()) { - case "MISSING" -> - !response.getMembershipExists() && !response.getGameplayAdmissionAllowed(); + case "MISSING" -> !response.getMembershipExists() && !response.getGameplayAdmissionAllowed(); case "INACTIVE" -> response.getMembershipExists() && response.getMembershipVersion() > 0L diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index edc61b6e2c..f231dbe113 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -371,7 +371,8 @@ void friendsRedactsLegacyHiddenStaffEntryButPreservesRelationshipRow() { .setWorldDisplayName("Demo World") .setRealmSlug("production") .setRealmDisplayName("Live Realm") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setPointerVersion(17L) .setActivityState( FriendPresenceActivityState @@ -1113,8 +1114,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { FriendPresencePolicyViewOutput view = (FriendPresencePolicyViewOutput) result.outputs().getFirst().payload(); assertThat(view.currentPolicy()).isEqualTo("FRIENDS_ONLY"); - assertThat(view.options()) - .noneMatch(option -> option.policy().equals("HIDDEN_STAFF")); + assertThat(view.options()).noneMatch(option -> option.policy().equals("HIDDEN_STAFF")); assertThat(view.options()) .anySatisfy( option -> { @@ -1316,9 +1316,7 @@ void friendsDoesNotAcceptLegacyHiddenStaffFilter() { TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, - java.util.List.of("HIDDEN_STAFF"), - "FRIENDS HIDDEN_STAFF"), + TextCommandType.FRIENDS, java.util.List.of("HIDDEN_STAFF"), "FRIENDS HIDDEN_STAFF"), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isFalse(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index b098f3f8ed..f41613d0c4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -57,10 +57,7 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { jwtUtil.generateToken( "1", java.util.Map.of( - "accountId", - "1", - "scopedRoles", - java.util.Map.of("22", java.util.List.of("god")))); + "accountId", "1", "scopedRoles", java.util.Map.of("22", java.util.List.of("god")))); gameplayPresenceService.registerConnected( new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt)); @@ -104,7 +101,8 @@ void whoShowsGlobalOnlyRolesAsPlayers() { java.util.List.of("platformAdmin", "support", "billingAdmin", "god", "moderator"))); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "staff@example.com", 101L, "Aster", 7L, "R-1", globalOnlyJwt)); + new SessionContext( + 1L, 22L, 1L, "staff@example.com", 101L, "Aster", 7L, "R-1", globalOnlyJwt)); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java index 3fb2e9d849..8c03ef384a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java @@ -158,7 +158,10 @@ void classifyRoleReturnsGodForTenantScopedGodRole() { JWT_UTIL.generateToken( "202", java.util.Map.of( - "accountId", "202", "scopedRoles", java.util.Map.of("22", java.util.List.of("god")))); + "accountId", + "202", + "scopedRoles", + java.util.Map.of("22", java.util.List.of("god")))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index 5e4d79242f..bee45bc8a1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -85,12 +85,7 @@ void registerConnectedClassifiesInvalidJwtAsPlayer() { void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { String godJwt = jwtUtil.generateToken( - "1", - Map.of( - "accountId", - "1", - "scopedRoles", - Map.of("22", List.of("god")))); + "1", Map.of("accountId", "1", "scopedRoles", Map.of("22", List.of("god")))); SessionContext godContext = new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); service.registerConnected(godContext); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index 33d4122202..cea7a9d73c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -688,8 +688,7 @@ void firstPartyWebProjectsFriendRosterSummaryViewPayloads() throws Exception { PlayerOutput.view( new FriendRosterSummaryViewOutput(4, 1, 3, 2, 1, 2, 1, 2, 1, 1)))), List.of( - PlayerOutput.view( - new FriendRosterSummaryViewOutput(4, 1, 3, 2, 1, 2, 1, 2, 1, 1))), + PlayerOutput.view(new FriendRosterSummaryViewOutput(4, 1, 3, 2, 1, 2, 1, 2, 1, 1))), "en-NZ", presentation); From 55ed1387c54e1a1b2386da5255e94eca5bc26afa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 15:32:35 +1200 Subject: [PATCH 08/28] Align gameplay Account stub with membership lifecycle --- .../test/AccountRuntimeStubServerTest.java | 27 ++++++++++++------- .../test/AccountRuntimeStubServer.java | 6 +++++ ...ionAccountCrossServiceIntegrationTest.java | 4 +-- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index abc3e59a76..b6485d69f6 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -14,7 +14,7 @@ class AccountRuntimeStubServerTest { @Test - void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() + void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmission() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { ManagedChannel channel = @@ -33,17 +33,26 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .getAccountId()) .isEqualTo("7"); - server.setMembershipExists(false); + var request = + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setRequestId("request-1") + .build(); + assertThat(stub.getTenantMembershipForRuntime(request).getMembershipLifecycleState()) + .isEqualTo("ACTIVE"); + + server.denyGameplayAdmission(); + var inactive = stub.getTenantMembershipForRuntime(request); + assertThat(inactive.getMembershipExists()).isTrue(); + assertThat(inactive.getGameplayAdmissionAllowed()).isFalse(); + assertThat(inactive.getMembershipLifecycleState()).isEqualTo("INACTIVE"); - var membership = - stub.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("7") - .setTenantId("1") - .setRequestId("request-1") - .build()); + server.setMembershipExists(false); + var membership = stub.getTenantMembershipForRuntime(request); assertThat(membership.getMembershipExists()).isFalse(); assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); + assertThat(membership.getMembershipLifecycleState()).isEqualTo("MISSING"); } finally { channel.shutdownNow(); } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 5fdff55e61..0bc0f4bf81 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -12,6 +12,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -54,6 +55,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final List authenticateRequests = new CopyOnWriteArrayList<>(); private final AtomicBoolean membershipExists = new AtomicBoolean(true); private final AtomicBoolean gameplayAdmissionAllowed = new AtomicBoolean(true); + private final AtomicReference membershipLifecycleState = new AtomicReference<>("ACTIVE"); private final AtomicBoolean gameplayAvailable = new AtomicBoolean(true); private final AtomicBoolean allowPublicJoin = new AtomicBoolean(true); private final AtomicBoolean realmAccessGranted = new AtomicBoolean(true); @@ -104,6 +106,7 @@ public void setMembershipExists(boolean exists) { gameplayAdmissionAllowed.set(false); } membershipExists.set(exists); + membershipLifecycleState.set(exists ? "ACTIVE" : "MISSING"); } public void allowGameplayAdmission() { @@ -114,6 +117,7 @@ public void allowGameplayAdmission() { public void denyGameplayAdmission() { setMembershipExists(true); setGameplayAdmissionAllowed(false); + membershipLifecycleState.set("INACTIVE"); } public void setGameplayAvailable(boolean available) { @@ -132,6 +136,7 @@ public void resetRuntimeState() { authenticateRequests.clear(); membershipExists.set(true); gameplayAdmissionAllowed.set(true); + membershipLifecycleState.set("ACTIVE"); gameplayAvailable.set(true); allowPublicJoin.set(true); realmAccessGranted.set(true); @@ -169,6 +174,7 @@ public void getTenantMembershipForRuntime( .setAccountId(request.getAccountId()) .setTenantId(request.getTenantId()) .setMembershipExists(exists) + .setMembershipLifecycleState(membershipLifecycleState.get()) .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) .setMembershipVersion(exists ? 1L : 0L) .setEvaluatedAt(EVALUATED_AT) diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 1f0fc160bb..d8f8f19e09 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -169,7 +169,7 @@ void telnetReconnectAfterRevocationFailsPlayAdmission() throws Exception { ensureTestServicesStarted(); try (GameplayTelnetDriver firstClient = openAdmittedTelnetClient()) {} - accountStub().setGameplayAdmissionAllowed(false); + accountStub().denyGameplayAdmission(); try (GameplayTelnetScenarios.LoginThenPlayScenario scenario = GameplayTelnetScenarios.loginThenAttemptPlay( @@ -489,7 +489,7 @@ void telnetReconnectAfterRevocationFailsClosed() throws Exception { .anyMatch(response -> response.contains(LookTestFixtures.DESTINATION_ROOM_ID)); } - accountStub().setGameplayAdmissionAllowed(false); + accountStub().denyGameplayAdmission(); try (GameplayTelnetScenarios.LoginThenPlayScenario scenario = GameplayTelnetScenarios.loginThenAttemptPlay( From 7153f825df44545e223647f4f0749d2f7de9cc76 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 16:02:51 +1200 Subject: [PATCH 09/28] Expect current JOIN_REQUIRED wording in TCP proof --- ...tGatewayGameSessionAccountCrossServiceIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index d8f8f19e09..fa002a18c4 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -179,13 +179,13 @@ void telnetReconnectAfterRevocationFailsPlayAdmission() throws Exception { assertThat(client.readLineContaining("ERROR JOIN_REQUIRED")) .contains("ERROR JOIN_REQUIRED") .contains( - "Membership is required before PLAY; joining this world is not available yet."))) { + "Membership is required before PLAY. Use JOIN or choose Join & Play."))) { assertThat(scenario.responses()) .anyMatch(response -> response.contains("ERROR JOIN_REQUIRED")) .anyMatch( response -> response.contains( - "Membership is required before PLAY; joining this world is not available yet.")); + "Membership is required before PLAY. Use JOIN or choose Join & Play.")); } } From 86b380d0cc7ae33b9e4809e6f88d302da68068a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 16:59:20 +1200 Subject: [PATCH 10/28] Establish provenance-backed account and game tenant UUID sources --- .../account-service/runtime-and-data.md | 2 + .../game-design-service/api-contracts.md | 8 + .../system-architecture-multi-tenancy.md | 9 + design/project-management/ai-observations.md | 5 + ...ame-authoring-publishing-and-activation.md | 2 + ...hared-runtime-contracts-and-persistence.md | 2 + .../v1/tenant_identity_service.proto | 23 ++ .../accountservice/entity/Account.java | 4 + .../entity/AccountIdentityProvenance.java | 18 + .../repository/AccountRepository.java | 105 ++++- .../V29__account_identity_uuid_bridge.sql | 80 ++++ .../AccountRepositoryIntegrationTest.java | 362 ++++++++++++++++++ .../firemud/gamedesign/entity/Game.java | 2 + .../firemud/gamedesign/mapper/GameMapper.java | 2 + .../gamedesign/repository/GameRepository.java | 116 +++++- .../repository/GameTenantIdentity.java | 15 + .../impl/TenantIdentityGrpcService.java | 93 +++++ .../V30__canonical_game_tenant_identity.sql | 61 +++ ...nantIdentityRepositoryIntegrationTest.java | 274 +++++++++++++ .../impl/TenantIdentityGrpcServiceTest.java | 148 +++++++ 20 files changed, 1305 insertions(+), 26 deletions(-) create mode 100644 protos/game-design/v1/tenant_identity_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java create mode 100644 services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V30__canonical_game_tenant_identity.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 5cc2249ef8..2914090417 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -14,6 +14,8 @@ Account V22/V23 rewrite retained email values to canonical form and validate a c Account V25 enforces the live tenant-scoped profile identity `(tenantId, accountId)`. Before adding the unique constraint, the migration fails closed with the named `profiles_tenant_account_identity_collision` preflight constraint when retained duplicates exist; it does not select, merge, delete, or rewrite those rows. Focused PostgreSQL proof covers legal profiles for one global account in different tenants, same-tenant duplicate rejection, and retained-duplicate migration failure without row loss, but those cases compile and are skipped when Docker is unavailable. This current-schema correction does not resolve the separate global-registration, explicit-membership, retained tenant-default, or mixed-binary obligations. +Account V29 keeps the numeric `accounts.id` primary key and adds an immutable canonical `account_uuid` per Account. Retained rows receive `ACCOUNT_V29_MIGRATION` provenance and a source numeric row equal to their unchanged primary key; an Account insert trigger binds new rows to their numeric key, while `AccountRepository` assigns UUIDs with `ACCOUNT_REPOSITORY_INSERT` provenance and verifies exact persisted identity readback. Database uniqueness constraints prevent duplicate UUID/source mappings. This is an Account persistence bridge only: REST/gRPC DTOs, JWT identities, and external callers remain numeric, and this migration does not create or infer tenant UUID mappings. The focused repository/migration integration class compiled successfully, but all 13 cases were skipped because Docker was unavailable; V29 PostgreSQL migration and immutability behavior therefore remains unexecuted runtime proof. + Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Focused unit proof in `ExpiredCredentialCleanupJobTest` has executed locally; PostgreSQL repository integration cases in `CredentialCleanupRepositoryIntegrationTest` compile but were skipped because Docker was unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired scope cannot prove a terminal outcome: Account records a retryable unavailable attempt without entitlement evaluation or membership mutation, and only exact operation and membership/audit readback may later terminalize it. A malformed or missing bearer is rejected without inventing a terminal operation result. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. A bounded Account-owned worker now revisits due `PENDING` intents, locks and reads back exact operation, scope, membership, provisional transition receipt, and audit evidence, and records capped attempts with a reason and backoff when evidence is incomplete. It terminalizes only a positively proved prior transition or an event-free already-active outcome with matching retained receipt history; it cannot infer a failure from expiry or an absent row, and after its attempt cap the pending row remains visible and caller-retryable. Exact PostgreSQL concurrency and unknown-outcome proof remains open until executed. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership with matching positive receipt history is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index a2d28ba116..44f305ff94 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -6,6 +6,14 @@ The protobuf service definitions under [../../../../protos/game-design/v1](../.. For REST endpoints, the authoritative request/response schema source is [openapi.yaml](../../../../services/game-design-service/src/main/resources/openapi.yaml). Design-doc examples should be updated to match when those schemas evolve. +## Tenant Identity Source and Selector + +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 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. A distinct, provenance-backed owner assertion of that cross-owner association and Account exact mapping/readback are still required before Account may use the UUID to admit any retained membership. + +**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 owner-local UUID source/read is being introduced as a bounded prerequisite; it does not make the Account runtime membership snapshot RPC safe to enable. Live retained-row migration, mounted-certificate acceptance, and Account/Game Session consumer proof must be reported separately from schema and unit tests. + ## Official Hosted Creator Mutation Gate For official hosted deployments, every creator-intent content-bearing mutation enters the Game Design boundary only after the Account-owned currentness/evidence authority in [Account Service API Contracts](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party) has been evaluated for the tenant's Creator Party, identified operator, and hosted-terms scope under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). This applies before the first persisted Draft and before later authoring/revision, asset, template, plugin, and publication writes. The acting account's current tenant authorization is a separate conjunct; Gateway/UI checks are advisory. diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 6651f2d97b..591c1189d6 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -26,6 +26,7 @@ FireMUD separates **global identity** from **per-game state** so that one person - **Hosted creator party (`creatorPartyId`)** – An Account-owned party reference for official hosted creator content and terms acceptance. It is not a login identity, JWT role, billing wallet, tenant, or platform determination of copyright ownership; community self-hosting does not use this official-hosted party model. - **Tenant (`tenantId`)** – A hosted game world or project. Each tenant represents one game created on the platform and may have one or more running game instances. Game Design owns tenant content and `tenantId`-scoped workflows, while Account owns the tenant's current Creator Party association, party-transfer authority, referenced party, and acceptance authority for official hosting. A party change follows the explicit Account-owned transfer boundary in ADR 0180 and is not inferred from membership, display name, or billing owner. - **Tenant slug (`tenantSlug`)** – A stable, human-friendly identifier owned by the Game Design Service. It selects the tenant in the player-facing lobby flow (`WORLDS` / `REALMS` / `CHARS` / `PLAY`) and is resolved server-side to `tenantId`; an authored-world selection additionally uses the tenant-scoped `worldSlug` under that resolved tenant. Slugs are selectors, not authority: services and persistence models continue to use `tenantId` as the authoritative tenant identifier, and any direct slug is re-resolved and reauthorized against current catalog/pointer authority at use time. See [ADR 0168: Snapshot-Bound Lobby Selectors and Stable Realm Identity](./decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md) for the current selector and slug-stability authority; [ADR 0005](./decisions/adr-0005-tenant-identifiers-in-gameplay-protocol.md) records the superseded historical decision. + - **World slug (`worldSlug`)** – A stable tenant-scoped selector for one authored world inside the tenant/game. It is resolved only together with `tenantId` and is paired with `realmSlug` by the realm catalog and admission-pointer contract. It is not an alias for `tenantSlug`, does not identify a tenant across the platform, and must not be inferred from display metadata, `realmSlug`, or `gameInstanceId`. - **Realm identity (`realmId`)** – Every durable realm has an opaque UUID `realmId`; its stable `realmSlug` is unique within the tenant and resolves to that identity. Selectors remain direct stable `tenantSlug`/`worldSlug` values, while `realmId` is the durable identity used by the catalog and admission pointer after selector resolution. - **Game instance (`gameInstanceId`)** – A specific running instance of a tenant’s world, keyed as described in [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md#version-activation--rollback). Runtime APIs and disposable instance-data keys include `gameInstanceId` explicitly; durable playable state that survives replacement additionally carries the stable `playableStateNamespaceId` and active-instance authorization. @@ -40,6 +41,14 @@ FireMUD separates **global identity** from **per-game state** so that one person - **Target auth token session** – A short-lived issued-token registry record (`session:auth:token:`) backing a revocable JWT for meta/control or admission APIs, as described in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md). Current Account credential-login sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key instead. - **Control-plane browser session** – A front-end admin/creator UI session that holds short-lived JWTs in memory; target server-side revocation relies on auth token sessions, while current Account authentication retains the legacy session keys above. These are distinct from gameplay sessions and are described in the Frontend Architecture and Authentication designs. +### Canonical Identity and Retained-Key Bridge + +Game Design issues and persists the canonical opaque UUID `tenantId` and owns its stable `tenantSlug` selector. Issuance is a durable owner transaction, not a conversion of a numeric key, an interpretation of UUID bits, or a slug-derived value. An exact owner read must return the same persisted UUID and the source/selector provenance; absence, ambiguity, or changed source binding is not a tenant identity. A retained Game Design game row can be assigned a UUID with provenance naming that exact row and its former Game Design tenant key. That assignment by itself does not prove that a numerically similar Account tenant key denotes the same tenant. + +Account issues and persists a separate canonical UUID `accountId` for each global account while retaining private numeric row keys. Its retained account mapping is one-to-one and records the exact Account row and assignment provenance. For retained membership, JOIN, receipt, and audit rows, Account preserves the original numeric evidence and adds a separate one-to-one bridge to the Game Design-issued tenant UUID only after an authenticated Game Design owner assertion establishes the exact legacy Account tenant-key association and its provenance. Neither a matching decimal string, a game row ID, a default tenant value, nor a guessed slug is that assertion. The owner assertion and Account bridge must be durably readable back and must reject duplicate UUID claims, one legacy key mapped to multiple UUIDs, one UUID mapped to multiple legacy keys, and evidence changes on retry. Unmapped or ambiguous retained rows remain non-admitting and may not be resolved by selecting an arbitrary candidate. + +At an Account-to-Game Session membership read, both logical IDs must resolve through these owner mappings and be bound to the verified caller, selected target, authority generation, stream checkpoint, and returned membership state in one fenced snapshot. Mapping presence alone neither activates retained membership nor proves a never-committed sequence-zero stream. The runtime membership RPC remains denied until the owner read and consumer exact-binding proof are complete. + ### Authority Generations Across Tenant States Account Service owns the issuer, account, tenant, and caller-bound membership authority generations and their projections. The exact global-role branches, route-class exceptions, target-tenant generation predicates, and assurance requirements are canonical in the [Authorization Route Matrix](./system-architecture-authz-route-matrix.md#classification-rules). Multi-tenancy's local consequence is that no role or route may use cached authorization, infer tenant access from a global role, or let a new route class inherit an exception implicitly. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index c9061bfbb6..28c5b8177b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -109,3 +109,8 @@ Entry format: - Context: the Entity baseline migrator needs a short-lived dedicated client identity without giving its certificate writer general Secret-read or deletion privileges. - Observation: a leaf verifying against the CA bundled in the same Secret is only self-consistent; it does not show that the namespace trusts that CA, and static issuance tests do not show the live Entity server accepts the identity. - Expected pattern: keep issuance opt-in and narrowly admitted, verify the projected leaf and chain against the namespace's independent trust projection under a separately authorized reader, then report live served-mTLS acceptance and later identity retirement as distinct proof. + +- `2026-09-26`: PostgreSQL identity migrations need separate jOOQ and runtime proof + - Context: Account and Game Design added UUID identity-source migrations while preserving numeric retained rows. The configured community jOOQ DDL parser rejected `GENERATED ALWAYS AS` and some grouped `ALTER COLUMN`/PostgreSQL function syntax, even though those are database constructs. + - Observation: replacing Account's generated source column with a trigger-bound immutable column and isolating Game Design's PostgreSQL-only DDL behind the existing jOOQ-ignore markers let schema generation proceed. Local Testcontainers cases compiled but skipped without Docker, so parser success is not PostgreSQL migration execution. + - Expected pattern: run jOOQ generation, Flyway numbering, and focused Java tests locally; keep a separate exact-head PostgreSQL migration/readback gate on a runner with Docker, and report any skipped integration case as unproved rather than green runtime evidence. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 797da0ac56..41b9b811cc 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. +The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30 assigns each retained `game` row a unique UUID with immutable row/former-key provenance, new game rows receive distinct issued UUIDs, and an Account-workload-only read returns the exact persisted source tuple. Five focused gRPC unit cases executed locally; the PostgreSQL retained-row migration case compiled but skipped without Docker. This is not the stable `tenantSlug` catalog/selector, a verified mapping from Account's numeric tenant keys, or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain unmapped and non-admitting until that separate owner assertion, bridge readback, and consumer proof exist. + Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 2a636ae76a..928ee6d0ad 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for shared runtime, service contr The implementation record below summarizes the shared runtime, service-contract, orchestration, persistence, and workflow boundaries represented by this tracker. It distinguishes live implementation from bounded follow-up work; it does not claim that every future service, runtime consumer, or workflow family has already adopted these conventions. +Account V29 now persists one immutable canonical UUID per Account while preserving the numeric local primary key, with explicit migration/insertion provenance and source-row evidence. The Account repository returns and resolves that UUID using exact source-row readback, while external Account carriers and consumers remain numeric; this does not establish a tenant UUID mapping. `:account-service:spotlessJavaCheck` and the focused `AccountLoginAuthModesTest` executed successfully; the focused `AccountRepositoryIntegrationTest` compiled but all 13 cases, including the V29 retained-row, JOIN-operation, and membership-receipt no-loss proof, were skipped because Docker was unavailable. PostgreSQL runtime behavior is therefore not yet verified. The broader `SF-1.2` capability remains partial and its cross-service UUID convergence is still unproved. + ### Script-transition cross-service handoff Implementation and proof remain partial: Game Session has durable per-instance pin state, while rollout history and final effect fencing remain incomplete; Automation has tenant readiness and core runtime state, while owner-observation projections and complete cross-boundary propagation/fencing remain incomplete. Current proof does not cover every durable work, handoff, timer, replay, and final-effect boundary, stage-aware dead-letter recovery, or complete no-degraded instance-bound admission. Canonical ownership remains in [scripting contracts](../../architecture/system-architecture-scripting-contracts.md), [scheduler and timers](../../architecture/system-architecture-scripting-scheduler-and-timers.md), [rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md), and [owner-read-first control-plane notifications](../../architecture/decisions/adr-0120-owner-read-first-control-plane-notifications.md); detailed status remains in the [Game Session](./game-session-runtime-and-tick-coordination.md#capability-status) and [Automation](./automation-and-scheduler-runtime.md#capability-status) trackers. diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto new file mode 100644 index 0000000000..09394f5d2d --- /dev/null +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; + +package gamedesign.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Owner-local legacy source read. This does not attest an Account numeric tenant key. +service TenantIdentityService { + rpc ResolveLegacyGameTenantIdentity(ResolveLegacyGameTenantIdentityRequest) + returns (ResolveLegacyGameTenantIdentityResponse); +} + +message ResolveLegacyGameTenantIdentityRequest { + string legacy_game_tenant_id = 1; +} + +message ResolveLegacyGameTenantIdentityResponse { + string canonical_tenant_id = 1; + string source_legacy_game_tenant_id = 2; + int64 source_game_row_id = 3; + string provenance_kind = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java index 2fb0e62afe..09ed06a6b5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java @@ -1,10 +1,14 @@ package net.firedevops.firemud.accountservice.entity; +import java.util.UUID; import lombok.Data; @Data public class Account { private Long id; + private UUID accountUuid; + private AccountIdentityProvenance accountUuidProvenance; + private Long accountUuidSourceNumericId; private String username; private String email; private String passwordHash; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java new file mode 100644 index 0000000000..f3f17c8704 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.accountservice.entity; + +public enum AccountIdentityProvenance { + ACCOUNT_V29_MIGRATION, + ACCOUNT_REPOSITORY_INSERT, + ACCOUNT_DATABASE_INSERT; + + public static AccountIdentityProvenance fromStorageValue(String value) { + if (value == null) { + throw new IllegalStateException("Account UUID provenance must not be null"); + } + try { + return AccountIdentityProvenance.valueOf(value); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Unknown Account UUID provenance: " + value, exception); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index dbc73e32ab..b1002a2489 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -3,8 +3,11 @@ import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.jooq.tables.records.AccountsRecord; import net.firedevops.firemud.common.EmailCanonicalization; import org.jooq.DSLContext; @@ -26,6 +29,14 @@ public Optional findById(Long id) { dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).fetchOne(this::toEntity)); } + public Optional findByAccountUuid(UUID accountUuid) { + Objects.requireNonNull(accountUuid, "accountUuid must not be null"); + return Optional.ofNullable( + dsl.selectFrom(ACCOUNTS) + .where(ACCOUNTS.ACCOUNT_UUID.eq(accountUuid)) + .fetchOne(this::toEntity)); + } + public Optional findByUsername(String username) { return Optional.ofNullable( dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.USERNAME.eq(username)).fetchOne(this::toEntity)); @@ -41,8 +52,13 @@ public Optional findByEmail(String email) { public Account save(Account entity) { entity.setEmail(EmailCanonicalization.normalize(entity.getEmail())); if (entity.getId() == null) { - Long id = + UUID expectedUuid = UUID.randomUUID(); + AccountsRecord inserted = dsl.insertInto(ACCOUNTS) + .set(ACCOUNTS.ACCOUNT_UUID, expectedUuid) + .set( + ACCOUNTS.ACCOUNT_UUID_PROVENANCE, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name()) .set(ACCOUNTS.USERNAME, entity.getUsername()) .set(ACCOUNTS.EMAIL, entity.getEmail()) .set(ACCOUNTS.PASSWORD_HASH, entity.getPasswordHash()) @@ -50,12 +66,20 @@ public Account save(Account entity) { .set(ACCOUNTS.EMAIL_VERIFIED, entity.isEmailVerified()) .set(ACCOUNTS.LOGIN_AUTH_MODES, normalizedLoginAuthModes(entity)) .set(ACCOUNTS.LIFECYCLE_STATE, entity.getLifecycleState().storageValue()) - .returningResult(ACCOUNTS.ID) - .fetchOne(ACCOUNTS.ID); - entity.setId(id); + .returning() + .fetchOne(); + if (inserted == null) { + throw new IllegalStateException("Account insert did not return its persisted identity"); + } + requireExactIdentityReadback( + inserted, expectedUuid, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + copyIdentityToEntity(entity, inserted); return entity; } - int updated = + UUID expectedUuid = entity.getAccountUuid(); + AccountIdentityProvenance expectedProvenance = entity.getAccountUuidProvenance(); + Long expectedSourceNumericId = entity.getAccountUuidSourceNumericId(); + var update = dsl.update(ACCOUNTS) .set(ACCOUNTS.USERNAME, entity.getUsername()) .set(ACCOUNTS.EMAIL, entity.getEmail()) @@ -63,11 +87,27 @@ public Account save(Account entity) { .set(ACCOUNTS.ROLE, entity.getRole()) .set(ACCOUNTS.EMAIL_VERIFIED, entity.isEmailVerified()) .set(ACCOUNTS.LOGIN_AUTH_MODES, normalizedLoginAuthModes(entity)) - .where(ACCOUNTS.ID.eq(entity.getId())) - .execute(); - if (updated != 1) { + .where(ACCOUNTS.ID.eq(entity.getId())); + if (expectedUuid != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID.eq(expectedUuid)); + } + if (expectedProvenance != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID_PROVENANCE.eq(expectedProvenance.name())); + } + if (expectedSourceNumericId != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID_SOURCE_NUMERIC_ID.eq(expectedSourceNumericId)); + } + AccountsRecord updated = update.returning().fetchOne(); + if (updated == null) { throw JooqAccountRepositorySupport.staleWrite("accounts", entity.getId()); } + requireExactIdentityReadback( + updated, + expectedUuid == null ? updated.getAccountUuid() : expectedUuid, + expectedProvenance == null + ? AccountIdentityProvenance.fromStorageValue(updated.getAccountUuidProvenance()) + : expectedProvenance); + copyIdentityToEntity(entity, updated); return entity; } @@ -78,15 +118,46 @@ public void delete(Account entity) { } private Account toEntity(AccountsRecord record) { - return JooqAccountRepositorySupport.partialAccount( - record.getId(), - record.getUsername(), - record.getEmail(), - record.getPasswordHash(), - record.getRole(), - record.getEmailVerified(), - record.getLoginAuthModes(), - record.getLifecycleState()); + Account account = + JooqAccountRepositorySupport.partialAccount( + record.getId(), + record.getUsername(), + record.getEmail(), + record.getPasswordHash(), + record.getRole(), + record.getEmailVerified(), + record.getLoginAuthModes(), + record.getLifecycleState()); + if (account != null) { + account.setAccountUuid(record.getAccountUuid()); + account.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue(record.getAccountUuidProvenance())); + account.setAccountUuidSourceNumericId(record.getAccountUuidSourceNumericId()); + requireExactIdentityReadback( + record, record.getAccountUuid(), account.getAccountUuidProvenance()); + } + return account; + } + + private void requireExactIdentityReadback( + AccountsRecord record, UUID expectedUuid, AccountIdentityProvenance expectedProvenance) { + if (record.getId() == null + || expectedUuid == null + || expectedProvenance == null + || !Objects.equals(record.getAccountUuid(), expectedUuid) + || !Objects.equals(record.getAccountUuidProvenance(), expectedProvenance.name()) + || !Objects.equals(record.getAccountUuidSourceNumericId(), record.getId())) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + } + + private void copyIdentityToEntity(Account entity, AccountsRecord record) { + entity.setId(record.getId()); + entity.setAccountUuid(record.getAccountUuid()); + entity.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue(record.getAccountUuidProvenance())); + entity.setAccountUuidSourceNumericId(record.getAccountUuidSourceNumericId()); } private String normalizedLoginAuthModes(Account entity) { diff --git a/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql b/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql new file mode 100644 index 0000000000..bc7962b8cd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql @@ -0,0 +1,80 @@ +-- Keep the numeric primary key as an Account-local storage detail while adding +-- the canonical, durable UUID identity required at cross-service boundaries. +-- Each retained UUID is assigned to its exact source row in place; the numeric +-- source is copied from that row's unchanged primary key. +ALTER TABLE accounts + ADD COLUMN account_uuid UUID, + ADD COLUMN account_uuid_provenance VARCHAR(40), + ADD COLUMN account_uuid_source_numeric_id BIGINT; + +UPDATE accounts +SET account_uuid = gen_random_uuid(), + account_uuid_provenance = 'ACCOUNT_V29_MIGRATION', + account_uuid_source_numeric_id = id; + +-- jOOQ's open-source DDL parser cannot model the PostgreSQL UUID generator default. +-- [jooq ignore start] +ALTER TABLE accounts ALTER COLUMN account_uuid SET DEFAULT gen_random_uuid(); +ALTER TABLE accounts + ALTER COLUMN account_uuid_provenance SET DEFAULT 'ACCOUNT_DATABASE_INSERT'; +-- [jooq ignore stop] + +ALTER TABLE accounts ALTER COLUMN account_uuid SET NOT NULL; +ALTER TABLE accounts ALTER COLUMN account_uuid_provenance SET NOT NULL; +ALTER TABLE accounts ALTER COLUMN account_uuid_source_numeric_id SET NOT NULL; +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_unique UNIQUE (account_uuid); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_source_numeric_id_unique + UNIQUE (account_uuid_source_numeric_id); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_source_numeric_id_check + CHECK (account_uuid_source_numeric_id = id); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_provenance_check + CHECK (account_uuid_provenance IN ( + 'ACCOUNT_V29_MIGRATION', + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + )); + +-- The UUID and its source record are immutable identity evidence. The numeric +-- primary key remains unchanged and cannot be reassigned after UUID backfill. +-- [jooq ignore start] +CREATE FUNCTION account_identity_source_row_on_insert() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + NEW.account_uuid_source_numeric_id := NEW.id; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_identity_source_row_on_insert + BEFORE INSERT ON accounts + FOR EACH ROW + EXECUTE FUNCTION account_identity_source_row_on_insert(); + +CREATE FUNCTION account_identity_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.account_uuid_provenance IS DISTINCT FROM OLD.account_uuid_provenance + OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM OLD.account_uuid_source_numeric_id THEN + RAISE EXCEPTION 'Account identity cannot be reassigned' + USING ERRCODE = '23514', CONSTRAINT = 'accounts_identity_immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_identity_immutable + BEFORE UPDATE OF id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + ON accounts + FOR EACH ROW + EXECUTE FUNCTION account_identity_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 1b6005e154..7f46d64d42 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import org.flywaydb.core.Flyway; @@ -49,6 +50,7 @@ class AccountRepositoryIntegrationTest { "account_profile_identity_migration_proof"; private static final String GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA = "account_global_registration_migration_proof"; + private static final String ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA = "account_uuid_migration_proof"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -405,6 +407,55 @@ void saveCanonicalizesEmail() { assertThat(repository.findByEmail(" PLAYER@EXAMPLE.COM ")).isPresent(); } + @Test + void repositoryPersistsAndReadsBackUniqueAccountUuidAndProvenance() { + Account saved = + repository.save( + account("uuid-account", "uuid-account@example.com", AccountLifecycleState.ACTIVE)); + UUID accountUuid = saved.getAccountUuid(); + + assertThat(accountUuid).isNotNull(); + assertThat(saved.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(saved.getAccountUuidSourceNumericId()).isEqualTo(saved.getId()); + + Account foundByNumericId = repository.findById(saved.getId()).orElseThrow(); + Account foundByUuid = repository.findByAccountUuid(accountUuid).orElseThrow(); + assertThat(foundByNumericId.getAccountUuid()).isEqualTo(accountUuid); + assertThat(foundByUuid.getId()).isEqualTo(saved.getId()); + assertThat(foundByUuid.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(foundByUuid.getAccountUuidSourceNumericId()).isEqualTo(saved.getId()); + + saved.setUsername("uuid-account-updated"); + Account updated = repository.save(saved); + assertThat(updated.getAccountUuid()).isEqualTo(accountUuid); + assertThat(updated.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(updated.getAccountUuidSourceNumericId()).isEqualTo(updated.getId()); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO accounts " + + "(username, email, password_hash, account_uuid, account_uuid_provenance) " + + "VALUES (?, ?, ?, ?, ?)", + "duplicate-uuid-account", + "duplicate-uuid-account@example.com", + "hash", + accountUuid, + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("accounts_account_uuid_unique"); + + saved.setAccountUuid(UUID.randomUUID()); + assertThatThrownBy(() -> repository.save(saved)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("Failed to update accounts id="); + assertThat(repository.findById(saved.getId()).orElseThrow().getAccountUuid()) + .isEqualTo(accountUuid); + } + @ParameterizedTest @NullSource @ValueSource(strings = {"", " "}) @@ -698,6 +749,313 @@ void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { .isEqualTo(0L); } + @Test + void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { + String schema = ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA; + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("28") + .load() + .migrate(); + + long firstAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('uuid-retained-one', 'uuid-retained-one@example.com', 'hash-one', 41) " + + "RETURNING id")) + .longValue(); + long secondAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('uuid-retained-two', 'uuid-retained-two@example.com', 'hash-two', 42) " + + "RETURNING id")) + .longValue(); + dsl.execute( + "INSERT INTO " + + schema + + ".profiles (account_id, tenant_id, display_name, bio) VALUES (?, ?, ?, ?)", + firstAccountId, + 41L, + "Retained profile", + "retained bio"); + dsl.execute( + "INSERT INTO " + + schema + + ".account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED')", + firstAccountId, + 41L); + dsl.execute( + "UPDATE " + + schema + + ".account_tenant_membership SET gameplay_admission_allowed = TRUE, " + + "lifecycle_state = 'ACTIVE', membership_version = 2, " + + "membership_authority_generation = 3, authority_provenance = 'EXPLICIT_JOIN' " + + "WHERE account_id = ? AND tenant_id = 42", + secondAccountId); + long secondMembershipId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "SELECT id FROM " + + schema + + ".account_tenant_membership WHERE account_id = ? AND tenant_id = 42", + secondAccountId)) + .longValue(); + + UUID joinRealmId = UUID.fromString("61d40f5d-2d59-4cc5-8774-54f7445d144b"); + String pendingJoinRequestId = "retained-v28-pending-join"; + String scopeDigest = AccountJoinDigest.tokenHash("retained-connect-scope"); + String intentDigest = AccountJoinDigest.tokenHash(pendingJoinRequestId + ":intent"); + dsl.execute( + "INSERT INTO " + + schema + + ".account_join_operations " + + "(request_id, account_id, tenant_id, verified_caller_binding, scope_token_hash, " + + "connect_scope_digest, world_slug, realm_slug, realm_id, playable_state_namespace_id, " + + "playable_state_scope, game_instance_id, catalog_revision, pointer_version, " + + "intent_digest_version, intent_digest, caller_bound_authority_invalidated, status) " + + "VALUES (?, ?, 42, 'retained-caller', ?, ?, 'retained-world', 'retained-realm', ?, " + + "'retained-namespace', 'REALM', 7, 11, 13, 1, ?, FALSE, 'PENDING')", + pendingJoinRequestId, + secondAccountId, + AccountJoinDigest.tokenHash("retained-scope-token"), + scopeDigest, + joinRealmId, + intentDigest); + + String receiptStreamKey = + "account:membership-transition-receipt:v1:membership/" + secondAccountId + "/42"; + String receiptRequestId = "retained-v28-membership-transition"; + UUID receiptId = UUID.fromString("92b9c1a4-2840-4c48-9622-782b9aa83a07"); + String receiptPayload = "retained membership transition receipt"; + String receiptDigest = AccountAuditDigest.ofPayload(receiptPayload); + dsl.execute( + "INSERT INTO " + + schema + + ".account_membership_transition_receipt_stream_heads " + + "(account_id, tenant_id, receipt_stream_key, last_receipt_sequence) " + + "VALUES (?, 42, ?, 1)", + secondAccountId, + receiptStreamKey); + dsl.execute( + "INSERT INTO " + + schema + + ".account_membership_transition_receipts " + + "(receipt_stream_key, receipt_sequence, account_id, tenant_id, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, membership_authority_generation, " + + "authority_provenance, receipt_id, receipt_digest) " + + "VALUES (?, 1, ?, 42, 'PROVISIONAL_TRANSITION_RECEIPT', 'MEMBERSHIP_JOINED', ?, ?, " + + "'ACTIVE', TRUE, 2, 3, 'EXPLICIT_JOIN', ?, ?)", + receiptStreamKey, + secondAccountId, + receiptRequestId, + secondMembershipId, + receiptId, + receiptDigest); + + UUID auditEventId = UUID.fromString("1596dcce-a52c-4c39-86bf-138a06069012"); + String payload = "{\"accountId\":" + firstAccountId + ",\"event\":\"retained\"}"; + String payloadDigest = AccountAuditDigest.ofPayload(payload); + dsl.execute( + "INSERT INTO " + + schema + + ".account_audit_outbox " + + "(audit_event_id, scope, producer_service, event_type, occurred_at, schema_version, " + + "payload_digest_version, payload_digest, payload) " + + "VALUES (?, 'platform', 'account-service', 'ACCOUNT_REGISTERED', " + + "TIMESTAMP '2026-09-01 12:00:00', 1, 1, ?, ?)", + auditEventId, + payloadDigest, + payload); + + String firstAccountBefore = + jsonRow( + "SELECT to_jsonb(a)::text FROM " + schema + ".accounts a WHERE id = ?", firstAccountId); + String secondAccountBefore = + jsonRow( + "SELECT to_jsonb(a)::text FROM " + schema + ".accounts a WHERE id = ?", + secondAccountId); + String profileBefore = + jsonRow( + "SELECT to_jsonb(p)::text FROM " + schema + ".profiles p WHERE account_id = ?", + firstAccountId); + String membershipBefore = + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + firstAccountId); + String explicitMembershipBefore = + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + secondAccountId); + String pendingJoinBefore = + jsonRow( + "SELECT to_jsonb(j)::text FROM " + + schema + + ".account_join_operations j WHERE request_id = ?", + pendingJoinRequestId); + String receiptStreamHeadBefore = + jsonRow( + "SELECT to_jsonb(h)::text FROM " + + schema + + ".account_membership_transition_receipt_stream_heads h " + + "WHERE account_id = ? AND tenant_id = 42", + secondAccountId); + String membershipTransitionReceiptBefore = + jsonRow( + "SELECT to_jsonb(r)::text FROM " + + schema + + ".account_membership_transition_receipts r WHERE receipt_id = ?", + receiptId); + String outboxBefore = + jsonRow( + "SELECT to_jsonb(o)::text FROM " + + schema + + ".account_audit_outbox o WHERE audit_event_id = ?", + auditEventId); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); + + String accountProjection = + "(to_jsonb(a) - 'account_uuid' - 'account_uuid_provenance' " + + "- 'account_uuid_source_numeric_id')::text"; + assertThat( + jsonRow( + "SELECT " + accountProjection + " FROM " + schema + ".accounts a WHERE id = ?", + firstAccountId)) + .isEqualTo(firstAccountBefore); + assertThat( + jsonRow( + "SELECT " + accountProjection + " FROM " + schema + ".accounts a WHERE id = ?", + secondAccountId)) + .isEqualTo(secondAccountBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(p)::text FROM " + schema + ".profiles p WHERE account_id = ?", + firstAccountId)) + .isEqualTo(profileBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + firstAccountId)) + .isEqualTo(membershipBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + secondAccountId)) + .isEqualTo(explicitMembershipBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(j)::text FROM " + + schema + + ".account_join_operations j WHERE request_id = ?", + pendingJoinRequestId)) + .isEqualTo(pendingJoinBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(h)::text FROM " + + schema + + ".account_membership_transition_receipt_stream_heads h " + + "WHERE account_id = ? AND tenant_id = 42", + secondAccountId)) + .isEqualTo(receiptStreamHeadBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(r)::text FROM " + + schema + + ".account_membership_transition_receipts r WHERE receipt_id = ?", + receiptId)) + .isEqualTo(membershipTransitionReceiptBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(o)::text FROM " + + schema + + ".account_audit_outbox o WHERE audit_event_id = ?", + auditEventId)) + .isEqualTo(outboxBefore); + + UUID firstUuid = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", firstAccountId) + .fetchOne(0, UUID.class)); + UUID secondUuid = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", + secondAccountId) + .fetchOne(0, UUID.class)); + assertThat(firstUuid).isNotEqualTo(secondUuid); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_provenance FROM " + schema + ".accounts WHERE id = ?", + firstAccountId) + .fetchOne(0, String.class)) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION.name()); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_source_numeric_id FROM " + + schema + + ".accounts WHERE id = ?", + firstAccountId) + .fetchOne(0, Long.class)) + .isEqualTo(firstAccountId); + assertThat( + dsl.resultQuery("SELECT COUNT(DISTINCT account_uuid) FROM " + schema + ".accounts") + .fetchOne(0, Long.class)) + .isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + + schema + + ".account_audit_outbox WHERE payload_digest = ?", + payloadDigest) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + schema + ".accounts SET account_uuid = ? WHERE id = ?", + UUID.randomUUID(), + firstAccountId)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("accounts_identity_immutable"); + assertThat( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", firstAccountId) + .fetchOne(0, UUID.class)) + .isEqualTo(firstUuid); + } + private Account account(String username, String email, AccountLifecycleState lifecycleState) { Account account = new Account(); account.setUsername(username); @@ -708,4 +1066,8 @@ private Account account(String username, String email, AccountLifecycleState lif account.setLifecycleState(lifecycleState); return account; } + + private String jsonRow(String query, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(query, bindings)).get(0, String.class); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java index 83572c7198..204de77695 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java @@ -1,11 +1,13 @@ package net.firedevops.firemud.gamedesign.entity; +import java.util.UUID; import lombok.Data; @Data public class Game { private Long id; private String tenantId; + private UUID canonicalTenantId; private String name; private String description; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java index f9a4d6c07c..2d3c2c6c40 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java @@ -3,10 +3,12 @@ import net.firedevops.firemud.gamedesign.dto.GameDto; import net.firedevops.firemud.gamedesign.entity.Game; import org.mapstruct.Mapper; +import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface GameMapper { GameDto toDto(Game entity); + @Mapping(target = "canonicalTenantId", ignore = true) Game toEntity(GameDto dto); } 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 57bce6b96d..94e35866c9 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 @@ -2,7 +2,10 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Game; +import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -18,6 +21,14 @@ public class GameRepository { private static final Table GAME_TABLE = DSL.table(DSL.name("game")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_IDENTITY_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field TENANT_IDENTITY_SOURCE_GAME_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); private static final Field NAME = DSL.field(DSL.name("name"), String.class); private static final Field DESCRIPTION = DSL.field(DSL.name("description"), String.class); @@ -33,22 +44,67 @@ public List findAll() { public Game save(Game game) { if (game.getId() == null) { + if (game.getCanonicalTenantId() != null) { + throw new IllegalArgumentException("Canonical tenant identity is issued by Game Design"); + } + UUID canonicalTenantId = UUID.randomUUID(); Record record = dsl.insertInto(GAME_TABLE) .set(TENANT_ID, game.getTenantId()) + .set(CANONICAL_TENANT_ID, canonicalTenantId) .set(NAME, game.getName()) .set(DESCRIPTION, game.getDescription()) - .returning(ID, TENANT_ID, NAME, DESCRIPTION) + .returning( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID, + NAME, + DESCRIPTION) .fetchOne(); - return toEntity(record); + if (record == null) { + throw new IllegalStateException("Game insert did not return its persisted row"); + } + Game saved = toEntity(record); + GameTenantIdentity persistedIdentity = toTenantIdentity(record); + if (saved == null + || !canonicalTenantId.equals(saved.getCanonicalTenantId()) + || persistedIdentity.provenanceKind() != GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW + || !saved.getId().equals(persistedIdentity.sourceGameId()) + || !saved.getTenantId().equals(persistedIdentity.sourceLegacyTenantId())) { + throw new IllegalStateException("Persisted game tenant identity did not match issuance"); + } + return saved; } - dsl.update(GAME_TABLE) - .set(TENANT_ID, game.getTenantId()) - .set(NAME, game.getName()) - .set(DESCRIPTION, game.getDescription()) - .where(ID.eq(game.getId())) - .execute(); - return findByTenantId(game.getTenantId()); + Condition identityCondition = ID.eq(game.getId()); + if (game.getTenantId() != null) { + identityCondition = identityCondition.and(TENANT_ID.eq(game.getTenantId())); + } + if (game.getCanonicalTenantId() != null) { + identityCondition = + identityCondition.and(CANONICAL_TENANT_ID.eq(game.getCanonicalTenantId())); + } + Record record = + dsl.update(GAME_TABLE) + .set(NAME, game.getName()) + .set(DESCRIPTION, game.getDescription()) + .where(identityCondition) + .returning( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID, + NAME, + DESCRIPTION) + .fetchOne(); + if (record == null) { + throw new IllegalStateException("Game update identity does not match a persisted game row"); + } + return toEntity(record); } public Game findByTenantId(String tenantId) { @@ -58,6 +114,17 @@ public Game findByTenantId(String tenantId) { .fetchOne(this::toEntity); } + public Optional findTenantIdentityByLegacyTenantId(String legacyTenantId) { + return dsl.select( + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID) + .from(GAME_TABLE) + .where(TENANT_ID.eq(legacyTenantId)) + .fetchOptional(record -> toTenantIdentity(record, legacyTenantId)); + } + public Game findByTenantIdForUpdate(String tenantId) { return dsl.selectFrom(GAME_TABLE) .where(TENANT_ID.eq(tenantId)) @@ -72,8 +139,39 @@ private Game toEntity(Record record) { Game game = new Game(); game.setId(record.get(ID)); game.setTenantId(record.get(TENANT_ID)); + game.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); game.setName(record.get(NAME)); game.setDescription(record.get(DESCRIPTION)); return game; } + + private GameTenantIdentity toTenantIdentity(Record record) { + return toTenantIdentity(record, null); + } + + private GameTenantIdentity toTenantIdentity(Record record, String expectedLegacyTenantId) { + 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 sourceLegacyTenantId = record.get(TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID); + if (canonicalTenantId == null + || provenanceKindValue == null + || sourceGameId == null + || sourceGameId <= 0 + || sourceLegacyTenantId == null + || sourceLegacyTenantId.isBlank() + || (expectedLegacyTenantId != null + && !expectedLegacyTenantId.equals(sourceLegacyTenantId))) { + throw new IllegalStateException("Persisted game tenant identity provenance is incomplete"); + } + GameTenantIdentity.ProvenanceKind provenanceKind; + try { + provenanceKind = GameTenantIdentity.ProvenanceKind.valueOf(provenanceKindValue); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Persisted game tenant identity provenance kind is unknown", exception); + } + return new GameTenantIdentity( + canonicalTenantId, provenanceKind, sourceGameId, sourceLegacyTenantId); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java new file mode 100644 index 0000000000..5c8faea07e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.repository; + +import java.util.UUID; + +/** Game Design's provenance-bearing canonical tenant identity sourced from its game row. */ +public record GameTenantIdentity( + UUID canonicalTenantId, + ProvenanceKind provenanceKind, + Long sourceGameId, + String sourceLegacyTenantId) { + public enum ProvenanceKind { + RETAINED_GAME_V30, + NEW_GAME_ROW + } +} 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 new file mode 100644 index 0000000000..bc403abb4b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.grpc.server.service.GrpcService; + +/** Authenticated read of Game Design's own retained tenant identity provenance. */ +@GrpcService +public class TenantIdentityGrpcService + extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { + private final GameRepository gameRepository; + private final String workloadNamespace; + + public TenantIdentityGrpcService( + GameRepository gameRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.gameRepository = gameRepository; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveLegacyGameTenantIdentity( + ResolveLegacyGameTenantIdentityRequest request, + StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || workloadNamespace == null + || workloadNamespace.isBlank() + || !peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service")) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Account workload identity is required") + .asRuntimeException()); + return; + } + + String sourceKey = request.getLegacyGameTenantId(); + if (sourceKey.isBlank() || sourceKey.length() > 36) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Exact legacy Game Design tenant key is required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = gameRepository.findTenantIdentityByLegacyTenantId(sourceKey); + } catch (IllegalStateException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design tenant identity provenance is invalid") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No Game Design tenant identity for exact source key") + .asRuntimeException()); + return; + } + GameTenantIdentity identity = resolved.orElseThrow(); + if (identity.canonicalTenantId() == null + || identity.sourceGameId() == null + || identity.sourceGameId() <= 0 + || identity.provenanceKind() == null + || !sourceKey.equals(identity.sourceLegacyTenantId())) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design tenant identity provenance is incomplete") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveLegacyGameTenantIdentityResponse.newBuilder() + .setCanonicalTenantId(identity.canonicalTenantId().toString()) + .setSourceLegacyGameTenantId(identity.sourceLegacyTenantId()) + .setSourceGameRowId(identity.sourceGameId()) + .setProvenanceKind(identity.provenanceKind().name()) + .build()); + responseObserver.onCompleted(); + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V30__canonical_game_tenant_identity.sql b/services/game-design-service/src/main/resources/db/migration/V30__canonical_game_tenant_identity.sql new file mode 100644 index 0000000000..4230a0793f --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V30__canonical_game_tenant_identity.sql @@ -0,0 +1,61 @@ +ALTER TABLE game + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN tenant_identity_provenance_kind VARCHAR(32), + ADD COLUMN tenant_identity_source_game_id BIGINT, + ADD COLUMN tenant_identity_source_legacy_tenant_id VARCHAR(36); + +UPDATE game +SET canonical_tenant_id = gen_random_uuid(), + tenant_identity_provenance_kind = 'RETAINED_GAME_V30', + tenant_identity_source_game_id = id, + tenant_identity_source_legacy_tenant_id = tenant_id; + +ALTER TABLE game ALTER COLUMN canonical_tenant_id SET NOT NULL; +ALTER TABLE game ALTER COLUMN tenant_identity_provenance_kind SET NOT NULL; +ALTER TABLE game ALTER COLUMN tenant_identity_source_game_id SET NOT NULL; +ALTER TABLE game ALTER COLUMN tenant_identity_source_legacy_tenant_id SET NOT NULL; +ALTER TABLE game ADD CONSTRAINT uq_game_canonical_tenant_id UNIQUE (canonical_tenant_id); +ALTER TABLE game ADD CONSTRAINT chk_game_tenant_identity_provenance_kind + CHECK (tenant_identity_provenance_kind IN ('RETAINED_GAME_V30', 'NEW_GAME_ROW')); +ALTER TABLE game ADD CONSTRAINT chk_game_tenant_identity_source_game + CHECK (tenant_identity_source_game_id = id); +ALTER TABLE game ADD CONSTRAINT chk_game_tenant_identity_source_legacy_tenant + CHECK (tenant_identity_source_legacy_tenant_id = tenant_id); + +-- [jooq ignore start] +ALTER TABLE game + ALTER COLUMN canonical_tenant_id SET DEFAULT gen_random_uuid(); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION enforce_game_tenant_identity() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + NEW.tenant_identity_provenance_kind := 'NEW_GAME_ROW'; + NEW.tenant_identity_source_game_id := NEW.id; + NEW.tenant_identity_source_legacy_tenant_id := NEW.tenant_id; + RETURN NEW; + END IF; + + IF NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN + RAISE EXCEPTION 'game legacy tenant_id is immutable after canonical tenant identity issuance' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.tenant_identity_provenance_kind IS DISTINCT FROM OLD.tenant_identity_provenance_kind + OR NEW.tenant_identity_source_game_id IS DISTINCT FROM OLD.tenant_identity_source_game_id + OR NEW.tenant_identity_source_legacy_tenant_id IS DISTINCT FROM OLD.tenant_identity_source_legacy_tenant_id THEN + RAISE EXCEPTION 'game canonical tenant identity and provenance are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_tenant_identity_immutable + BEFORE INSERT OR UPDATE ON game + FOR EACH ROW + EXECUTE FUNCTION enforce_game_tenant_identity(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java new file mode 100644 index 0000000000..a25ec0b35b --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java @@ -0,0 +1,274 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameTenantIdentityRepositoryIntegrationTest { + private static final String SERVICE_SCHEMA = "game_design_service"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final 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 NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field 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_LEGACY_TENANT_ID = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migratesRetainedGamesAndIssuesImmutableProvenanceForNewGames() throws Exception { + DriverManagerDataSource dataSource = dataSource(); + migrate(dataSource, MigrationVersion.fromVersion("29")); + + long retainedAlphaId; + long retainedBetaId; + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection); + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + retainedAlphaId = insertLegacyGame(dsl, "legacy-tenant-alpha", "Alpha", "alpha-data"); + retainedBetaId = insertLegacyGame(dsl, "legacy-tenant-beta", "Beta", "beta-data"); + } + + migrate(dataSource, null); + + UUID retainedAlphaCanonicalId; + UUID retainedBetaCanonicalId; + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection); + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + var retainedRows = + dsl.select( + ID, + TENANT_ID, + NAME, + DESCRIPTION, + CANONICAL_TENANT_ID, + PROVENANCE_KIND, + SOURCE_GAME_ID, + SOURCE_LEGACY_TENANT_ID) + .from(GAME) + .orderBy(ID.asc()) + .fetch(); + + assertThat(retainedRows).hasSize(2); + assertThat(retainedRows) + .extracting(row -> row.get(TENANT_ID)) + .containsExactly("legacy-tenant-alpha", "legacy-tenant-beta"); + assertThat(retainedRows).extracting(row -> row.get(NAME)).containsExactly("Alpha", "Beta"); + assertThat(retainedRows) + .extracting(row -> row.get(DESCRIPTION)) + .containsExactly("alpha-data", "beta-data"); + assertThat(retainedRows) + .extracting(row -> row.get(PROVENANCE_KIND)) + .containsOnly("RETAINED_GAME_V30"); + assertThat(retainedRows) + .extracting(row -> row.get(SOURCE_GAME_ID)) + .containsExactly(retainedAlphaId, retainedBetaId); + assertThat(retainedRows) + .extracting(row -> row.get(SOURCE_LEGACY_TENANT_ID)) + .containsExactly("legacy-tenant-alpha", "legacy-tenant-beta"); + + retainedAlphaCanonicalId = retainedRows.get(0).get(CANONICAL_TENANT_ID); + retainedBetaCanonicalId = retainedRows.get(1).get(CANONICAL_TENANT_ID); + assertThat(retainedAlphaCanonicalId).isNotNull().isNotEqualTo(retainedBetaCanonicalId); + + migrate(dataSource, null); + assertThat( + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(ID.eq(retainedAlphaId)) + .fetchOne(CANONICAL_TENANT_ID)) + .isEqualTo(retainedAlphaCanonicalId); + assertThat( + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(ID.eq(retainedBetaId)) + .fetchOne(CANONICAL_TENANT_ID)) + .isEqualTo(retainedBetaCanonicalId); + + GameRepository repository = new GameRepository(dsl); + assertThat(repository.findTenantIdentityByLegacyTenantId("legacy-tenant-alpha")) + .contains( + new GameTenantIdentity( + retainedAlphaCanonicalId, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + retainedAlphaId, + "legacy-tenant-alpha")); + Game newGame = new Game(); + newGame.setTenantId("legacy-tenant-new"); + newGame.setName("New"); + newGame.setDescription("new-data"); + Game saved = repository.save(newGame); + + assertThat(saved.getCanonicalTenantId()) + .isNotNull() + .isNotEqualTo(retainedAlphaCanonicalId) + .isNotEqualTo(retainedBetaCanonicalId); + assertThat(repository.findByTenantId("legacy-tenant-new").getCanonicalTenantId()) + .isEqualTo(saved.getCanonicalTenantId()); + assertThat(repository.findTenantIdentityByLegacyTenantId("legacy-tenant-new")) + .contains( + new GameTenantIdentity( + saved.getCanonicalTenantId(), + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + saved.getId(), + "legacy-tenant-new")); + assertThat(repository.findTenantIdentityByLegacyTenantId("unknown-legacy-tenant")).isEmpty(); + + Game existingGame = repository.findByTenantId("legacy-tenant-new"); + existingGame.setDescription("updated-data"); + Game updatedGame = repository.save(existingGame); + assertThat(updatedGame.getCanonicalTenantId()).isEqualTo(saved.getCanonicalTenantId()); + assertThat(repository.findTenantIdentityByLegacyTenantId("legacy-tenant-new")) + .contains( + new GameTenantIdentity( + saved.getCanonicalTenantId(), + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + saved.getId(), + "legacy-tenant-new")); + + Game mismatchedUpdate = new Game(); + mismatchedUpdate.setId(saved.getId()); + mismatchedUpdate.setTenantId("different-legacy-tenant"); + mismatchedUpdate.setName("Must not apply"); + mismatchedUpdate.setDescription("must-not-apply"); + assertThatThrownBy(() -> repository.save(mismatchedUpdate)) + .isInstanceOf(IllegalStateException.class); + assertThat(repository.findByTenantId("legacy-tenant-new").getName()).isEqualTo("New"); + assertThat(repository.findByTenantId("legacy-tenant-new").getDescription()) + .isEqualTo("updated-data"); + + Game mismatchedCanonicalUpdate = new Game(); + mismatchedCanonicalUpdate.setId(saved.getId()); + mismatchedCanonicalUpdate.setTenantId(saved.getTenantId()); + mismatchedCanonicalUpdate.setCanonicalTenantId(UUID.randomUUID()); + mismatchedCanonicalUpdate.setName("Must not apply"); + mismatchedCanonicalUpdate.setDescription("must-not-apply"); + assertThatThrownBy(() -> repository.save(mismatchedCanonicalUpdate)) + .isInstanceOf(IllegalStateException.class); + assertThat(repository.findByTenantId("legacy-tenant-new").getDescription()) + .isEqualTo("updated-data"); + + assertThatThrownBy( + () -> + dsl.update(GAME) + .set(CANONICAL_TENANT_ID, UUID.randomUUID()) + .where(ID.eq(retainedAlphaId)) + .execute()) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.update(GAME) + .set(SOURCE_GAME_ID, SOURCE_GAME_ID.plus(1L)) + .where(ID.eq(retainedAlphaId)) + .execute()) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.update(GAME) + .set(TENANT_ID, "legacy-tenant-renamed") + .where(ID.eq(retainedAlphaId)) + .execute()) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.insertInto(GAME) + .set(TENANT_ID, "legacy-tenant-duplicate-canonical") + .set(CANONICAL_TENANT_ID, retainedAlphaCanonicalId) + .set(NAME, "Duplicate") + .execute()) + .isInstanceOf(DataAccessException.class); + + dsl.insertInto(GAME) + .set(TENANT_ID, "legacy-tenant-database-issued") + .set(NAME, "Database issued") + .execute(); + GameTenantIdentity databaseIssuedIdentity = + repository + .findTenantIdentityByLegacyTenantId("legacy-tenant-database-issued") + .orElseThrow(); + assertThat(databaseIssuedIdentity.canonicalTenantId()) + .isNotNull() + .isNotEqualTo(retainedAlphaCanonicalId) + .isNotEqualTo(retainedBetaCanonicalId) + .isNotEqualTo(saved.getCanonicalTenantId()); + assertThat(databaseIssuedIdentity.provenanceKind()) + .isEqualTo(GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW); + assertThat(databaseIssuedIdentity.sourceLegacyTenantId()) + .isEqualTo("legacy-tenant-database-issued"); + assertThat(dsl.fetchCount(GAME)).isEqualTo(4); + } + } + + private DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, MigrationVersion target) { + FluentConfiguration configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(SERVICE_SCHEMA) + .defaultSchema(SERVICE_SCHEMA) + .table(FLYWAY_TABLE) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private void setSearchPath(Connection connection) throws Exception { + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO game_design_service"); + } + } + + private long insertLegacyGame( + DSLContext dsl, String legacyTenantId, String name, String description) { + return Objects.requireNonNull( + dsl.insertInto(GAME) + .set(TENANT_ID, legacyTenantId) + .set(NAME, name) + .set(DESCRIPTION, description) + .returning(ID) + .fetchOne(ID)) + .longValue(); + } +} 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 new file mode 100644 index 0000000000..f6e65b4f47 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; +import org.junit.jupiter.api.Test; + +class TenantIdentityGrpcServiceTest { + private static final String ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_PEER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); + + private final GameRepository repository = mock(GameRepository.class); + private final TenantIdentityGrpcService service = + new TenantIdentityGrpcService(repository, "test"); + + @Test + void exactAccountPeerReadsOwnerSourceAndProvenance() { + when(repository.findTenantIdentityByLegacyTenantId("legacy-game-7")) + .thenReturn( + Optional.of( + new GameTenantIdentity( + CANONICAL_TENANT_ID, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + 7L, + "legacy-game-7"))); + TestObserver observer = call("legacy-game-7", ACCOUNT_PEER); + + assertNull(observer.errorCode); + assertTrue(observer.completed); + assertNotNull(observer.value); + assertEquals(CANONICAL_TENANT_ID.toString(), observer.value.getCanonicalTenantId()); + assertEquals("legacy-game-7", observer.value.getSourceLegacyGameTenantId()); + assertEquals(7L, observer.value.getSourceGameRowId()); + assertEquals("RETAINED_GAME_V30", observer.value.getProvenanceKind()); + verify(repository).findTenantIdentityByLegacyTenantId("legacy-game-7"); + } + + @Test + void wrongOrMissingPeerNeverReadsOwnerRows() { + assertEquals(Status.Code.PERMISSION_DENIED, status(call("legacy-game-7", WRONG_PEER))); + assertEquals(Status.Code.PERMISSION_DENIED, status(call("legacy-game-7", null))); + verifyNoInteractions(repository); + } + + @Test + void blankOrOverlongSourceKeyNeverReadsOwnerRows() { + assertEquals(Status.Code.INVALID_ARGUMENT, status(call("", ACCOUNT_PEER))); + assertEquals(Status.Code.INVALID_ARGUMENT, status(call("x".repeat(37), ACCOUNT_PEER))); + verifyNoInteractions(repository); + } + + @Test + void unknownOrMismatchedSourceFailsClosed() { + when(repository.findTenantIdentityByLegacyTenantId("unknown")).thenReturn(Optional.empty()); + when(repository.findTenantIdentityByLegacyTenantId("legacy-game-7")) + .thenReturn( + Optional.of( + new GameTenantIdentity( + CANONICAL_TENANT_ID, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V30, + 7L, + "different-source"))); + + TestObserver absent = call("unknown", ACCOUNT_PEER); + TestObserver mismatched = call("legacy-game-7", ACCOUNT_PEER); + assertEquals(Status.Code.NOT_FOUND, status(absent)); + assertEquals(Status.Code.FAILED_PRECONDITION, status(mismatched)); + assertNull(absent.value); + assertNull(mismatched.value); + assertFalse(absent.completed); + assertFalse(mismatched.completed); + } + + @Test + void invalidStoredProvenanceFailsClosed() { + when(repository.findTenantIdentityByLegacyTenantId("legacy-game-7")) + .thenThrow(new IllegalStateException("corrupt source binding")); + + TestObserver observer = call("legacy-game-7", ACCOUNT_PEER); + + assertEquals(Status.Code.FAILED_PRECONDITION, status(observer)); + assertNull(observer.value); + } + + private TestObserver call(String sourceKey, String peerUri) { + TestObserver observer = new TestObserver(); + Context context = Context.current(); + if (peerUri != null) { + context = + context.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + } + context.run( + () -> + service.resolveLegacyGameTenantIdentity( + ResolveLegacyGameTenantIdentityRequest.newBuilder() + .setLegacyGameTenantId(sourceKey) + .build(), + observer)); + return observer; + } + + private static Status.Code status(TestObserver observer) { + assertNotNull(observer.errorCode); + return observer.errorCode; + } + + private static final class TestObserver + implements StreamObserver { + private ResolveLegacyGameTenantIdentityResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ResolveLegacyGameTenantIdentityResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 7c60505872b459efaecff95135f253434d0d235f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 17:11:31 +1200 Subject: [PATCH 11/28] Fix Account and Game Design migration proof fixtures --- .../repository/AccountRepositoryIntegrationTest.java | 10 +++++----- .../GameTenantIdentityRepositoryIntegrationTest.java | 2 ++ 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 7f46d64d42..db26a7bd3b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -799,12 +799,12 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { firstAccountId, 41L); dsl.execute( - "UPDATE " + "INSERT INTO " + schema - + ".account_tenant_membership SET gameplay_admission_allowed = TRUE, " - + "lifecycle_state = 'ACTIVE', membership_version = 2, " - + "membership_authority_generation = 3, authority_provenance = 'EXPLICIT_JOIN' " - + "WHERE account_id = ? AND tenant_id = 42", + + ".account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, 42, TRUE, 'ACTIVE', 2, 3, 'EXPLICIT_JOIN')", secondAccountId); long secondMembershipId = Objects.requireNonNull( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java index a25ec0b35b..bc76dcda40 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java @@ -5,6 +5,7 @@ import java.sql.Connection; import java.sql.Statement; +import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Game; @@ -247,6 +248,7 @@ private void migrate(DriverManagerDataSource dataSource, MigrationVersion target .schemas(SERVICE_SCHEMA) .defaultSchema(SERVICE_SCHEMA) .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", SERVICE_SCHEMA)) .locations("classpath:db/migration"); if (target != null) { configuration.target(target); From 1938e2d74bf2fe1cb21041a2859c6276d0eb03ad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 17:17:45 +1200 Subject: [PATCH 12/28] Assert Account UUID immutability by canonical rejection --- .../repository/AccountRepositoryIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index db26a7bd3b..90ad31b3e9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -1048,7 +1048,7 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { UUID.randomUUID(), firstAccountId)) .isInstanceOf(DataAccessException.class) - .hasStackTraceContaining("accounts_identity_immutable"); + .hasStackTraceContaining("Account identity cannot be reassigned"); assertThat( dsl.resultQuery( "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", firstAccountId) From 45c45900e9ee2cdeae07f61da1c1bde5289a970e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 18:12:58 +1200 Subject: [PATCH 13/28] Add audited legacy tenant association bridge --- .../account-service/operations.md | 6 + .../game-design-service/api-contracts.md | 2 +- .../game-design-service/operations.md | 6 + .../system-architecture-multi-tenancy.md | 2 + ...ame-authoring-publishing-and-activation.md | 2 +- .../player-access-and-session.md | 2 + .../v1/tenant_identity_service.proto | 25 ++ .../GameDesignTenantIdentityClient.java | 64 +++++ ...egacyTenantAssociationImportJobRunner.java | 100 ++++++++ ...ovedLegacyTenantAssociationRepository.java | 196 +++++++++++++++ .../LegacyTenantSourceEvidence.java | 134 ++++++++++ .../LegacyTenantAssociationImportService.java | 35 +++ ...0__approved_legacy_tenant_associations.sql | 39 +++ ...enantAssociationImportIntegrationTest.java | 132 ++++++++++ ...LegacyTenantAssociationRepositoryTest.java | 56 +++++ .../TenantAssociationManifest.java | 36 +++ .../TenantAssociationManifestJobRunner.java | 104 ++++++++ .../TenantAssociationManifestVerifier.java | 142 +++++++++++ .../TenantAssociationMigrationService.java | 231 ++++++++++++++++++ .../impl/TenantIdentityGrpcService.java | 108 +++++++- ...ved_legacy_account_tenant_associations.sql | 48 ++++ ...ntAssociationMigrationIntegrationTest.java | 203 +++++++++++++++ ...TenantAssociationManifestVerifierTest.java | 131 ++++++++++ .../impl/TenantIdentityGrpcServiceTest.java | 114 ++++++++- 24 files changed, 1910 insertions(+), 8 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/LegacyTenantSourceEvidence.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java create mode 100644 services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifier.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantAssociationMigrationService.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V31__approved_legacy_account_tenant_associations.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/TenantAssociationMigrationIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifierTest.java diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 585438a383..8876853317 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -9,6 +9,12 @@ This document collects the Account Service operational behavior, readiness model - `readiness` is truthful local readiness for the currently implemented authentication/account slice and must fail when the service cannot safely satisfy new authentication traffic with its required local persistence/session infrastructure. - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. +### Legacy tenant association import + +**Current implementation status:** V30 and the opt-in `LegacyTenantAssociationImportJobRunner` provide an Account-owned read of retained V26 tenant, membership, and profile source rows, a versioned SHA-256 evidence digest, and guarded import from Game Design's exact Account-peer-only owner read. The Account import compares that digest, deployment namespace, source key, UUID, operation and approval evidence before immutable one-to-one storage and exact readback. It does not auto-map rows or enable membership admission. Focused malformed-owner-response unit proof executed; PostgreSQL import/readback proof compiled but skipped without Docker, and no live manifest or cross-service migration has run. + +An operator first runs `evidence` for an exact positive retained numeric key in a listener-free Account job using the Account workload certificate. Missing or conflicting V26 source rows fail closed. The digest goes into the [Game Design approved manifest](../game-design-service/operations.md#legacy-tenant-association-migration), not into an inferred key match. After Game Design applies and reads back the signed operation, the operator runs Account `import` for the same key. That mode calls Game Design with the exact Account mTLS identity, validates its owner response and the current V26 digest, and commits the immutable local mapping. An exact retry is event-free; changed owner or Account evidence is a conflict. Job deployment and executed PostgreSQL, cross-service, and membership consumer proof remain open; an import cannot be treated as a JOIN, a sequence-zero stream checkpoint, or a working runtime membership RPC. + ## Saga Participation The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. A delivery job sends the unchanged envelope to Logging & Admin and marks it complete only after matching receipt evidence; failed or ambiguous delivery leaves the event pending for retry with the same identity. Logging & Admin locally implements receipt persistence, deduplication, exact payload digest checking, and receipt readback. This status does not claim PostgreSQL runtime proof or direct text-client end-to-end proof. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025. These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 44f305ff94..987efda189 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -10,7 +10,7 @@ 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 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. A distinct, provenance-backed owner assertion of that cross-owner association and Account exact mapping/readback are still required before Account may use the UUID to admit any retained membership. +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 Account-peer-only, 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 owner-local UUID source/read is being introduced as a bounded prerequisite; it does not make the Account runtime membership snapshot RPC safe to enable. Live retained-row migration, mounted-certificate acceptance, and Account/Game Session consumer proof must be reported separately from schema and unit tests. diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 7f22d35dce..de2f770aec 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -28,6 +28,12 @@ The target publication boundary treats object-store export as a durable candidat ## Local Development Notes +### Legacy tenant association migration + +**Current implementation status:** V31 and the opt-in `TenantAssociationManifestJobRunner` can verify a trusted Ed25519 owner signature over a versioned, byte-length-framed manifest, compare every former Game Design key and canonical UUID with its persisted V30 source row, and store/read back the immutable operation and one-to-one associations. The job requires an exact deployment namespace and a dedicated `game-design-tenant-migrator` service account, with listeners and Temporal disabled. It is not a public mutation route and ordinary startup does not import any association. Local focused verifier/gRPC tests executed, but the PostgreSQL test skipped without Docker; no real manifest, job deployment, retained-row set, or live readback has been proved. + +For an approved operation, first obtain Account's exact retained-source evidence digest from its [Account owner migration mode](../account-service/operations.md#legacy-tenant-association-import). The Game Design owner then reviews the explicit numeric Account key, former Game Design key, V30 game row, canonical UUID, namespace, stable operation identity, and Account evidence digest; records the approval reference; and signs the canonical manifest preimage using an owner-controlled key already trusted by the migration job. A preflight verifies the signed bytes and exact namespace without writing. Only an operator-invoked `apply` with that same signed manifest and trusted public-key set writes V31; an exact retry must return the same readback and a conflicting pair fails. Account then imports from the authenticated owner read and checks its retained evidence before the membership consumer can be considered. This order does not enable the disabled runtime membership RPC. The job image, trusted-key Secret, signed-manifest Secret, certificate/namespace wiring, and an executed migration readback still require deployment proof; do not describe this code-only path as an applied data migration. + ### Historical Entity digest baseline migration **Current implementation status:** The one-shot Game Design maintenance Job and guarded owner-local v1→v2 baseline transition are implemented, but no retained row set or live certificate/consumer/readback outcome has been verified by this document. The Job is disabled in ordinary Helm releases and must be invoked only from a trusted operator context, using a reviewed immutable Game Design image digest. It is not a public API, a general admin role, or a PR-controlled executor. Its dedicated `game-design-baseline-migrator` Kubernetes service account has no Kubernetes API verbs, and its separate client certificate may read only Entity Management's bound `GetDraftDesignDigest` RPC. No Game Design, Account, or Game Session mutation API is delegated to that identity. The Job only writes Game Design's own baseline and audit tables through its guarded service operation; it never accesses Entity's database. diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 591c1189d6..8c19d74537 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -47,6 +47,8 @@ Game Design issues and persists the canonical opaque UUID `tenantId` and owns it Account issues and persists a separate canonical UUID `accountId` for each global account while retaining private numeric row keys. Its retained account mapping is one-to-one and records the exact Account row and assignment provenance. For retained membership, JOIN, receipt, and audit rows, Account preserves the original numeric evidence and adds a separate one-to-one bridge to the Game Design-issued tenant UUID only after an authenticated Game Design owner assertion establishes the exact legacy Account tenant-key association and its provenance. Neither a matching decimal string, a game row ID, a default tenant value, nor a guessed slug is that assertion. The owner assertion and Account bridge must be durably readable back and must reject duplicate UUID claims, one legacy key mapped to multiple UUIDs, one UUID mapped to multiple legacy keys, and evidence changes on retry. Unmapped or ambiguous retained rows remain non-admitting and may not be resolved by selecting an arbitrary candidate. +For retained rows without another authoritative association source, that owner assertion is an explicit, one-time, audited migration manifest. Game Design's tenant owner signs a versioned, length-framed manifest binding the exact deployment namespace, stable operation identity, owner approval/reference, former Game Design tenant key, Game Design source row, issued UUID, Account numeric tenant key, and Account's retained-source evidence digest. Game Design verifies the trusted signer and exact former-key-to-UUID source before storing an immutable, one-to-one assertion; Account obtains it only from the authenticated Game Design workload read, recomputes its own retained-row evidence, then stores and reads back its immutable local mapping. Exact retries must return the same evidence, while missing, conflicting, duplicate, changed, or ambiguous pairs fail closed. Manifest approval establishes identity association only: it does not activate a legacy membership, create an authority stream, grant admission, or relax the disabled runtime membership RPC. + At an Account-to-Game Session membership read, both logical IDs must resolve through these owner mappings and be bound to the verified caller, selected target, authority generation, stream checkpoint, and returned membership state in one fenced snapshot. Mapping presence alone neither activates retained membership nor proves a never-committed sequence-zero stream. The runtime membership RPC remains denied until the owner read and consumer exact-binding proof are complete. ### Authority Generations Across Tenant States diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 41b9b811cc..b9e6553892 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. -The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30 assigns each retained `game` row a unique UUID with immutable row/former-key provenance, new game rows receive distinct issued UUIDs, and an Account-workload-only read returns the exact persisted source tuple. Five focused gRPC unit cases executed locally; the PostgreSQL retained-row migration case compiled but skipped without Docker. This is not the stable `tenantSlug` catalog/selector, a verified mapping from Account's numeric tenant keys, or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain unmapped and non-admitting until that separate owner assertion, bridge readback, and consumer proof exist. +The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30 assigns each retained `game` row a unique UUID with immutable row/former-key provenance, new game rows receive distinct issued UUIDs, and an Account-workload-only read returns the exact persisted source tuple. The in-progress V31 addition defines a separate signed, owner-approved manifest operation for exact Account numeric-key associations. It verifies the former Game Design key, source row, and issued UUID, stores immutable one-to-one evidence, and exposes the exact approved tuple only to the Account workload. Focused manifest and gRPC unit tests execute locally; the new PostgreSQL manifest case compiles but skips without Docker. No actual manifest has been applied or read back in a deployed environment, and the Account bridge/consumer proof remains incomplete. This is not the stable `tenantSlug` catalog/selector or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain non-admitting until the owner assertion, bridge readback, and consumer proof exist. Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7c70bed16b..8a303d965d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,6 +14,8 @@ The current Unit 1B draft adds Account-owned provisional JOIN/reactivation trans Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). +The in-progress #2873 tenant bridge now has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact-Account-peer 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 jobs are opt-in and the runtime membership RPC remains denied. Local focused manifest, gRPC, and Account negative tests executed; both new PostgreSQL import/readback cases compiled but skipped without Docker. No real signed manifest, live data association, composed owner/consumer snapshot, or runtime admission proof has been completed. Missing/conflicting rows remain denied; this is not a completed membership authority stream or Unit 1B closure. + The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. The approved first-party bare-`LOGIN` private-delegation exchange is not implemented. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. An Account-owned one-use/idempotent exchange must establish those producer facts and exact Game Session caller binding before Game Session can receive a private delegation JWT; a forwarded context or token `jti` alone cannot authorize the exchange. The approved never-joined sequence-zero membership checkpoint likewise requires Account to prove the exact canonical authority stream never committed under the same fenced snapshot as the no-row read and authenticated tuple/generation/version; the provisional transition receipt does not prove that condition, and no current response or consumer provides it. Formerly joined or left streams retain positive sequence history. Both paths remain unavailable while the runtime RPCs deny. diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 09394f5d2d..ece5fc66e7 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -9,6 +9,9 @@ option java_multiple_files = true; service TenantIdentityService { rpc ResolveLegacyGameTenantIdentity(ResolveLegacyGameTenantIdentityRequest) returns (ResolveLegacyGameTenantIdentityResponse); + // Owner-approved cross-service legacy association; Account is the sole caller. + rpc ResolveLegacyAccountTenantAssociation(ResolveLegacyAccountTenantAssociationRequest) + returns (ResolveLegacyAccountTenantAssociationResponse); } message ResolveLegacyGameTenantIdentityRequest { @@ -21,3 +24,25 @@ message ResolveLegacyGameTenantIdentityResponse { int64 source_game_row_id = 3; string provenance_kind = 4; } + +message ResolveLegacyAccountTenantAssociationRequest { + int64 legacy_account_tenant_id = 1; +} + +message ResolveLegacyAccountTenantAssociationResponse { + int64 legacy_account_tenant_id = 1; + string source_legacy_game_tenant_id = 2; + string canonical_tenant_id = 3; + int64 source_game_row_id = 4; + string account_evidence_digest = 5; + string operation_id = 6; + string manifest_digest = 7; + string target_namespace = 8; + string signer_key_id = 9; + string approved_by = 10; + string approval_reference = 11; + string signed_at = 12; + int32 operation_entry_count = 13; + string manifest_signature = 14; + int32 manifest_schema_version = 15; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java new file mode 100644 index 0000000000..439f0d6788 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.accountservice.client; + +import jakarta.annotation.PostConstruct; +import java.io.IOException; +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.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.springframework.stereotype.Component; + +/** Account-only authenticated read of a Game Design owner-approved legacy association. */ +@Component +public class GameDesignTenantIdentityClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + public GameDesignTenantIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + super( + endpoints, tlsProps, channelFactory, stubCustomizer, GameDesignTenantIdentityClient.class); + } + + @PostConstruct + 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( + io.grpc.ManagedChannel channel) { + return applyStubCustomizer( + TenantIdentityServiceGrpc.newBlockingStub(channel).withCompression("gzip")); + } + + public ResolveLegacyAccountTenantAssociationResponse resolveApprovedAssociation(long tenantId) { + if (tenantId <= 0) { + throw new IllegalArgumentException("positive legacy Account tenant key is required"); + } + return stub() + .withDeadlineAfter(5, TimeUnit.SECONDS) + .resolveLegacyAccountTenantAssociation( + ResolveLegacyAccountTenantAssociationRequest.newBuilder() + .setLegacyAccountTenantId(tenantId) + .build()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java new file mode 100644 index 0000000000..d8f2489f4e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.accountservice.maintenance; + +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import net.firedevops.firemud.accountservice.service.impl.LegacyTenantAssociationImportService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** Opt-in Account owner import; ordinary service startup performs no legacy mapping. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.account-tenant-migration", + name = "enabled", + havingValue = "true") +public class LegacyTenantAssociationImportJobRunner implements ApplicationRunner { + private static final Logger LOG = + LoggerFactory.getLogger(LegacyTenantAssociationImportJobRunner.class); + + private final Environment environment; + private final LegacyTenantAssociationImportService importService; + + public LegacyTenantAssociationImportJobRunner( + Environment environment, LegacyTenantAssociationImportService importService) { + this.environment = environment; + this.importService = importService; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + if (!"true".equals(System.getenv("FIREMUD_ACCOUNT_TENANT_MIGRATION_ENABLED")) + || !"none".equalsIgnoreCase(required("spring.main.web-application-type")) + || environment.getProperty("spring.grpc.server.enabled", Boolean.class, true)) { + throw new IllegalStateException("Account tenant migration must not start listeners"); + } + String podNamespace = required("firemud.account-tenant-migration.pod-namespace"); + String targetNamespace = required("firemud.account-tenant-migration.target-namespace"); + if (!podNamespace.equals(targetNamespace) + || !"account-service" + .equals(required("firemud.account-tenant-migration.pod-service-account"))) { + throw new IllegalStateException("Account tenant migration Job has the wrong workload scope"); + } + GrpcPeerIdentity identity = verifiedWorkloadIdentity(); + if (!identity.isService("account-service") || !identity.isInNamespace(podNamespace)) { + throw new IllegalStateException( + "Account tenant migration certificate has the wrong identity"); + } + long legacyTenantId = + Long.parseLong(required("firemud.account-tenant-migration.legacy-tenant-id")); + if (legacyTenantId <= 0) { + throw new IllegalArgumentException("legacy Account tenant key must be positive"); + } + String mode = required("firemud.account-tenant-migration.mode"); + if ("evidence".equals(mode)) { + LOG.info( + "Account tenant evidence legacyTenantId={} digest={} namespace={}", + legacyTenantId, + importService.retainedEvidenceDigest(legacyTenantId), + targetNamespace); + } else if ("import".equals(mode)) { + var imported = importService.importApproved(legacyTenantId); + LOG.info( + "Account tenant association imported legacyTenantId={} canonicalTenantId={} " + + "operationId={} manifestDigest={} namespace={}", + legacyTenantId, + imported.canonicalTenantId(), + imported.operationId(), + imported.manifestDigest(), + targetNamespace); + } else { + throw new IllegalArgumentException("unsupported Account tenant migration Job mode"); + } + } + + private GrpcPeerIdentity verifiedWorkloadIdentity() throws Exception { + Path certificatePath = Path.of(required("FIREMUD_GRPC_CERT_CHAIN_PATH")); + X509Certificate leaf; + try (InputStream input = Files.newInputStream(certificatePath)) { + leaf = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + return GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow(() -> new IllegalStateException("Account certificate lacks a valid URI SAN")); + } + + private String required(String property) { + String value = environment.getProperty(property); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(property + " is required"); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java new file mode 100644 index 0000000000..98240cbae1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java @@ -0,0 +1,196 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Base64; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +/** Account-owned exact retained-row verification and immutable association readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring transaction collaborator.") +public class ApprovedLegacyTenantAssociationRepository { + private final DSLContext dsl; + private final LegacyTenantSourceEvidence sourceEvidence; + private final String workloadNamespace; + + public ApprovedLegacyTenantAssociationRepository( + DSLContext dsl, + LegacyTenantSourceEvidence sourceEvidence, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.dsl = dsl; + this.sourceEvidence = sourceEvidence; + this.workloadNamespace = workloadNamespace; + } + + @Transactional(isolation = Isolation.SERIALIZABLE) + public ApprovedAssociation importApproved( + long requestedLegacyTenantId, ResolveLegacyAccountTenantAssociationResponse ownerResponse) { + ApprovedAssociation expected = requireExactResponse(requestedLegacyTenantId, ownerResponse); + String actualEvidenceDigest = sourceEvidence.digest(requestedLegacyTenantId); + if (!actualEvidenceDigest.equals(expected.accountEvidenceDigest())) { + throw new IllegalStateException( + "approved Account source evidence differs from retained rows"); + } + Optional existing = findByLegacyTenantId(requestedLegacyTenantId); + if (existing.isPresent()) { + if (!existing.orElseThrow().equals(expected)) { + throw new IllegalStateException( + "approved Account tenant association conflicts with readback"); + } + return existing.orElseThrow(); + } + + dsl.execute( + "INSERT INTO account_approved_legacy_tenant_associations " + + "(legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, manifest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (legacy_tenant_id) DO NOTHING", + expected.legacyTenantId(), + expected.canonicalTenantId(), + expected.sourceLegacyGameTenantId(), + expected.sourceGameRowId(), + expected.accountEvidenceDigest(), + expected.operationId(), + expected.manifestDigest(), + expected.manifestSignature(), + expected.targetNamespace(), + expected.signerKeyId(), + expected.approvedBy(), + expected.approvalReference(), + expected.signedAt(), + expected.operationEntryCount(), + expected.manifestSchemaVersion()); + ApprovedAssociation committed = + findByLegacyTenantId(requestedLegacyTenantId) + .orElseThrow( + () -> new IllegalStateException("approved association readback is absent")); + if (!committed.equals(expected)) { + throw new IllegalStateException("approved association readback differs"); + } + return committed; + } + + @Transactional(readOnly = true) + public Optional findByLegacyTenantId(long legacyTenantId) { + if (legacyTenantId <= 0) { + return Optional.empty(); + } + Record row = + dsl.fetchOne( + "SELECT legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, " + + "manifest_schema_version " + + "FROM account_approved_legacy_tenant_associations WHERE legacy_tenant_id = ?", + legacyTenantId); + return Optional.ofNullable(row) + .map( + result -> + new ApprovedAssociation( + result.get(0, Long.class), + result.get(1, UUID.class), + result.get(2, String.class), + result.get(3, Long.class), + result.get(4, String.class), + result.get(5, UUID.class), + result.get(6, String.class), + result.get(7, String.class), + result.get(8, String.class), + result.get(9, String.class), + result.get(10, String.class), + result.get(11, String.class), + result.get(12, String.class), + result.get(13, Integer.class), + result.get(14, Integer.class))); + } + + private ApprovedAssociation requireExactResponse( + long requestedLegacyTenantId, ResolveLegacyAccountTenantAssociationResponse response) { + Objects.requireNonNull(response, "Game Design owner response is required"); + if (requestedLegacyTenantId <= 0 + || response.getLegacyAccountTenantId() != requestedLegacyTenantId + || workloadNamespace == null + || workloadNamespace.isBlank() + || !workloadNamespace.equals(response.getTargetNamespace()) + || response.getSourceLegacyGameTenantId().isBlank() + || response.getSourceLegacyGameTenantId().length() > 36 + || response.getSourceGameRowId() <= 0 + || !digest(response.getAccountEvidenceDigest()) + || !digest(response.getManifestDigest()) + || response.getSignerKeyId().isBlank() + || response.getApprovedBy().isBlank() + || response.getApprovalReference().isBlank() + || response.getOperationEntryCount() <= 0 + || response.getManifestSchemaVersion() != 1) { + throw new IllegalArgumentException( + "Game Design owner association is incomplete or mismatched"); + } + try { + UUID canonicalTenantId = UUID.fromString(response.getCanonicalTenantId()); + UUID operationId = UUID.fromString(response.getOperationId()); + Instant.parse(response.getSignedAt()); + byte[] signature = Base64.getDecoder().decode(response.getManifestSignature()); + if (signature.length != 64 + || !Base64.getEncoder() + .encodeToString(signature) + .equals(response.getManifestSignature())) { + throw new IllegalArgumentException("owner manifest signature has the wrong length"); + } + return new ApprovedAssociation( + requestedLegacyTenantId, + canonicalTenantId, + response.getSourceLegacyGameTenantId(), + response.getSourceGameRowId(), + response.getAccountEvidenceDigest(), + operationId, + response.getManifestDigest(), + response.getManifestSignature(), + response.getTargetNamespace(), + response.getSignerKeyId(), + response.getApprovedBy(), + response.getApprovalReference(), + response.getSignedAt(), + response.getOperationEntryCount(), + response.getManifestSchemaVersion()); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException( + "Game Design owner association has invalid identity evidence", ex); + } + } + + private static boolean digest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + public record ApprovedAssociation( + long legacyTenantId, + UUID canonicalTenantId, + String sourceLegacyGameTenantId, + long sourceGameRowId, + String accountEvidenceDigest, + UUID operationId, + String manifestDigest, + String manifestSignature, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + int operationEntryCount, + int manifestSchemaVersion) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/LegacyTenantSourceEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/LegacyTenantSourceEvidence.java new file mode 100644 index 0000000000..710903a2b0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/LegacyTenantSourceEvidence.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.List; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** Exact V26 retained Account source-row evidence for an operator-approved tenant association. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring transaction collaborator.") +public class LegacyTenantSourceEvidence { + private static final String DOMAIN = "firemud/account-legacy-tenant-source/v1"; + + private final DSLContext dsl; + + public LegacyTenantSourceEvidence(DSLContext dsl) { + this.dsl = dsl; + } + + public String digest(long legacyTenantId) { + if (legacyTenantId <= 0) { + throw new IllegalArgumentException("positive retained Account tenant key is required"); + } + List accounts = + dsl.fetch( + "SELECT account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition, captured_at " + + "FROM account_legacy_tenant_sources WHERE legacy_tenant_id = ? " + + "ORDER BY account_id", + legacyTenantId); + if (accounts.isEmpty()) { + throw new IllegalStateException("retained Account numeric tenant source is absent"); + } + List memberships = + dsl.fetch( + "SELECT membership_id, account_id, tenant_id, " + + "original_gameplay_admission_allowed, matches_account_legacy_tenant, " + + "disposition, captured_at FROM account_legacy_membership_sources " + + "WHERE tenant_id = ? ORDER BY membership_id", + legacyTenantId); + List profiles = + dsl.fetch( + "SELECT profile_id, account_id, tenant_id, matches_account_legacy_tenant, " + + "disposition, captured_at FROM account_legacy_profile_sources " + + "WHERE tenant_id = ? ORDER BY profile_id", + legacyTenantId); + + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + try (DataOutputStream out = + new DataOutputStream(new DigestOutputStream(OutputStream.nullOutputStream(), hash))) { + write(out, DOMAIN); + out.writeLong(legacyTenantId); + out.writeInt(accounts.size()); + for (Record row : accounts) { + if (!"UNVERIFIED".equals(row.get(6, String.class))) { + throw new IllegalStateException("retained Account tenant source is conflicting"); + } + out.writeLong(row.get(0, Long.class)); + out.writeLong(row.get(1, Long.class)); + writeOptionalLong(out, row.get(2, Long.class)); + writeOptionalBoolean(out, row.get(3, Boolean.class)); + out.writeLong(row.get(4, Long.class)); + out.writeLong(row.get(5, Long.class)); + write(out, row.get(6, String.class)); + write(out, row.get(7, LocalDateTime.class).toString()); + } + out.writeInt(memberships.size()); + for (Record row : memberships) { + if (!Boolean.TRUE.equals(row.get(4, Boolean.class)) + || !"UNVERIFIED".equals(row.get(5, String.class))) { + throw new IllegalStateException("retained Account membership source is conflicting"); + } + out.writeLong(row.get(0, Long.class)); + out.writeLong(row.get(1, Long.class)); + out.writeLong(row.get(2, Long.class)); + out.writeBoolean(row.get(3, Boolean.class)); + out.writeBoolean(row.get(4, Boolean.class)); + write(out, row.get(5, String.class)); + write(out, row.get(6, LocalDateTime.class).toString()); + } + out.writeInt(profiles.size()); + for (Record row : profiles) { + if (!Boolean.TRUE.equals(row.get(3, Boolean.class)) + || !"UNVERIFIED".equals(row.get(4, String.class))) { + throw new IllegalStateException("retained Account profile source is conflicting"); + } + out.writeLong(row.get(0, Long.class)); + out.writeLong(row.get(1, Long.class)); + out.writeLong(row.get(2, Long.class)); + out.writeBoolean(row.get(3, Boolean.class)); + write(out, row.get(4, String.class)); + write(out, row.get(5, LocalDateTime.class).toString()); + } + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (IOException | NoSuchAlgorithmException ex) { + throw new IllegalStateException("retained Account source evidence cannot be digested", ex); + } + } + + private static void write(DataOutputStream out, String value) throws IOException { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + out.writeInt(bytes.length); + out.write(bytes); + } + + private static void writeOptionalLong(DataOutputStream out, Long value) throws IOException { + out.writeBoolean(value != null); + if (value != null) { + out.writeLong(value); + } + } + + private static void writeOptionalBoolean(DataOutputStream out, Boolean value) throws IOException { + out.writeBoolean(value != null); + if (value != null) { + out.writeBoolean(value); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java new file mode 100644 index 0000000000..8e6e28ec66 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java @@ -0,0 +1,35 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import net.firedevops.firemud.accountservice.client.GameDesignTenantIdentityClient; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Operator-invoked import; neither lookup nor evidence enumeration grants membership admission. */ +@Service +public class LegacyTenantAssociationImportService { + private final GameDesignTenantIdentityClient ownerClient; + private final ApprovedLegacyTenantAssociationRepository repository; + private final LegacyTenantSourceEvidence sourceEvidence; + + public LegacyTenantAssociationImportService( + GameDesignTenantIdentityClient ownerClient, + ApprovedLegacyTenantAssociationRepository repository, + LegacyTenantSourceEvidence sourceEvidence) { + this.ownerClient = ownerClient; + this.repository = repository; + this.sourceEvidence = sourceEvidence; + } + + @Transactional(readOnly = true) + public String retainedEvidenceDigest(long legacyTenantId) { + return sourceEvidence.digest(legacyTenantId); + } + + public ApprovedAssociation importApproved(long legacyTenantId) { + return repository.importApproved( + legacyTenantId, ownerClient.resolveApprovedAssociation(legacyTenantId)); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql b/services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql new file mode 100644 index 0000000000..761ba9b457 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql @@ -0,0 +1,39 @@ +-- No retained numeric tenant key is mapped by this migration. An Account-owned +-- import verifies exact V26 source evidence against a Game Design approved read. +CREATE TABLE account_approved_legacy_tenant_associations ( + legacy_tenant_id BIGINT PRIMARY KEY CHECK (legacy_tenant_id > 0), + canonical_tenant_id UUID NOT NULL UNIQUE, + source_legacy_game_tenant_id VARCHAR(36) NOT NULL UNIQUE, + source_game_row_id BIGINT NOT NULL UNIQUE CHECK (source_game_row_id > 0), + account_evidence_digest VARCHAR(71) NOT NULL, + operation_id UUID NOT NULL, + manifest_digest VARCHAR(71) NOT NULL, + manifest_signature VARCHAR(128) NOT NULL, + target_namespace VARCHAR(128) NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at VARCHAR(40) NOT NULL, + operation_entry_count INTEGER NOT NULL CHECK (operation_entry_count > 0), + manifest_schema_version INTEGER NOT NULL CHECK (manifest_schema_version = 1), + imported_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_approved_tenant_evidence_digest_shape + CHECK (account_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT account_approved_tenant_manifest_digest_shape + CHECK (manifest_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT account_approved_tenant_signature_shape + CHECK (length(manifest_signature) = 88) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_account_approved_tenant_change() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Approved Account legacy tenant association is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_approved_tenant_association_immutable + BEFORE UPDATE OR DELETE ON account_approved_legacy_tenant_associations + FOR EACH ROW EXECUTE FUNCTION reject_account_approved_tenant_change(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java new file mode 100644 index 0000000000..3d3498038e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java @@ -0,0 +1,132 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Base64; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class LegacyTenantAssociationImportIntegrationTest { + private static final String SCHEMA = "account_tenant_association_proof"; + private static final long LEGACY_TENANT_ID = 41L; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void exactRetainedSourceAndApprovedOwnerReadAreRequiredForImmutableImport() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl() + "?currentSchema=" + SCHEMA); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .locations("classpath:db/migration") + .target("25") + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + long accountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES ('retained-tenant', 'retained@example.test', 'hash', ?) " + + "RETURNING id", + LEGACY_TENANT_ID)) + .longValue(); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed) VALUES (?, ?, TRUE)", + accountId, + LEGACY_TENANT_ID); + dsl.execute( + "INSERT INTO profiles (account_id, tenant_id) VALUES (?, ?)", accountId, LEGACY_TENANT_ID); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .locations("classpath:db/migration") + .load() + .migrate(); + + LegacyTenantSourceEvidence sources = new LegacyTenantSourceEvidence(dsl); + ApprovedLegacyTenantAssociationRepository repository = + new ApprovedLegacyTenantAssociationRepository(dsl, sources, SCHEMA); + String exactDigest = sources.digest(LEGACY_TENANT_ID); + ResolveLegacyAccountTenantAssociationResponse approved = ownerRead(exactDigest); + + assertThatThrownBy(() -> repository.importApproved(42L, approved)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mismatched"); + assertThatThrownBy( + () -> + repository.importApproved(LEGACY_TENANT_ID, ownerRead("sha256:" + "f".repeat(64)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs"); + assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).isEmpty(); + + var first = repository.importApproved(LEGACY_TENANT_ID, approved); + assertThat(first.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); + assertThat(first.accountEvidenceDigest()).isEqualTo(exactDigest); + assertThat(repository.importApproved(LEGACY_TENANT_ID, approved)).isEqualTo(first); + assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).contains(first); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_approved_legacy_tenant_associations " + + "SET canonical_tenant_id = ? WHERE legacy_tenant_id = ?", + UUID.randomUUID(), + LEGACY_TENANT_ID)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Approved Account legacy tenant association is immutable"); + + dsl.execute( + "UPDATE account_legacy_tenant_sources SET disposition = 'CONFLICT' " + + "WHERE account_id = ?", + accountId); + assertThatThrownBy(() -> repository.importApproved(LEGACY_TENANT_ID, approved)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicting"); + assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).contains(first); + } + + private ResolveLegacyAccountTenantAssociationResponse ownerRead(String accountEvidenceDigest) { + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(LEGACY_TENANT_ID) + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setSourceLegacyGameTenantId("legacy-game-7") + .setSourceGameRowId(7L) + .setAccountEvidenceDigest(accountEvidenceDigest) + .setOperationId("11111111-1111-4111-8111-111111111111") + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace(SCHEMA) + .setSignerKeyId("game-design-owner-2026") + .setApprovedBy("owner@example.test") + .setApprovalReference("reviewed-change-123") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java new file mode 100644 index 0000000000..6f7f3c5e17 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.Base64; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class ApprovedLegacyTenantAssociationRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final LegacyTenantSourceEvidence sources = mock(LegacyTenantSourceEvidence.class); + private final ApprovedLegacyTenantAssociationRepository repository = + new ApprovedLegacyTenantAssociationRepository(dsl, sources, "proof"); + + @Test + void mismatchedOrIncompleteOwnerReadNeverTouchesRetainedRows() { + ResolveLegacyAccountTenantAssociationResponse valid = response().build(); + + assertThatThrownBy(() -> repository.importApproved(42L, valid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.importApproved( + 41L, response().setTargetNamespace("other-namespace").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> repository.importApproved(41L, response().clearManifestSignature().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> repository.importApproved(41L, response().clearCanonicalTenantId().build())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl, sources); + } + + private ResolveLegacyAccountTenantAssociationResponse.Builder response() { + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(41L) + .setCanonicalTenantId("22222222-2222-4222-8222-222222222222") + .setSourceLegacyGameTenantId("legacy-game-7") + .setSourceGameRowId(7L) + .setAccountEvidenceDigest("sha256:" + "a".repeat(64)) + .setOperationId("11111111-1111-4111-8111-111111111111") + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace("proof") + .setSignerKeyId("game-design-owner-2026") + .setApprovedBy("owner@example.test") + .setApprovalReference("reviewed-change-123") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifest.java new file mode 100644 index 0000000000..d035d50b7c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifest.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +/** One approved, exact legacy Account-key to Game Design tenant association operation. */ +public record TenantAssociationManifest( + int schemaVersion, + UUID operationId, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + Instant signedAt, + List entries) { + public TenantAssociationManifest { + if (entries != null) { + entries = List.copyOf(entries); + } + } + + @Override + public List entries() { + return entries == null ? null : List.copyOf(entries); + } + + public record Entry( + long legacyAccountTenantId, + String legacyGameTenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String accountEvidenceDigest) {} + + public record Signed(TenantAssociationManifest manifest, String ed25519Signature) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java new file mode 100644 index 0000000000..1d5e4d88df --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** Opt-in, owner-approved one-shot migration; no service mutation endpoint is exposed. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.tenant-association-migration", + name = "enabled", + havingValue = "true") +public class TenantAssociationManifestJobRunner implements ApplicationRunner { + private static final Logger LOG = + LoggerFactory.getLogger(TenantAssociationManifestJobRunner.class); + private static final String MIGRATOR_SERVICE_ACCOUNT = "game-design-tenant-migrator"; + + private final Environment environment; + private final ObjectMapper objectMapper; + private final TenantAssociationMigrationService migrationService; + + public TenantAssociationManifestJobRunner( + Environment environment, + ObjectMapper objectMapper, + TenantAssociationMigrationService migrationService) { + this.environment = environment; + this.objectMapper = objectMapper.copy(); + this.migrationService = migrationService; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + if (!"true".equals(System.getenv("FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED")) + || !"none".equalsIgnoreCase(required("spring.main.web-application-type")) + || environment.getProperty("spring.grpc.server.enabled", Boolean.class, true) + || environment.getProperty("firemud.temporal.enabled", Boolean.class, true)) { + throw new IllegalStateException("tenant migration must not start listeners or workers"); + } + String podNamespace = required("firemud.tenant-association-migration.pod-namespace"); + String targetNamespace = required("firemud.tenant-association-migration.target-namespace"); + if (!podNamespace.equals(targetNamespace) + || !MIGRATOR_SERVICE_ACCOUNT.equals( + required("firemud.tenant-association-migration.pod-service-account"))) { + throw new IllegalStateException("tenant migration Job has the wrong workload scope"); + } + Path manifestPath = + Path.of(required("firemud.tenant-association-migration.signed-manifest-path")); + Path publicKeysPath = + Path.of(required("firemud.tenant-association-migration.owner-public-keys-path")); + ObjectMapper strictMapper = + objectMapper + .copy() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION); + Signed signed = strictMapper.readValue(Files.readAllBytes(manifestPath), Signed.class); + Map trustedKeys = + strictMapper.readValue( + Files.readAllBytes(publicKeysPath), new TypeReference>() {}); + var verified = TenantAssociationManifestVerifier.verify(signed, trustedKeys); + if (!targetNamespace.equals(verified.manifest().targetNamespace())) { + throw new IllegalStateException("signed tenant manifest targets a different namespace"); + } + String mode = required("firemud.tenant-association-migration.mode"); + if ("preflight".equals(mode)) { + LOG.info( + "Tenant association preflight operationId={} manifestDigest={} entries={} namespace={}", + verified.manifest().operationId(), + verified.manifestDigest(), + verified.manifest().entries().size(), + targetNamespace); + } else if ("apply".equals(mode)) { + var applied = migrationService.apply(signed, trustedKeys, targetNamespace); + LOG.info( + "Tenant association applied operationId={} manifestDigest={} readbackEntries={} namespace={}", + verified.manifest().operationId(), + verified.manifestDigest(), + applied.size(), + targetNamespace); + } else { + throw new IllegalArgumentException("unsupported tenant migration Job mode"); + } + } + + private String required(String property) { + String value = environment.getProperty(property); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(property + " is required"); + } + return value; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifier.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifier.java new file mode 100644 index 0000000000..b78237441c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifier.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; + +/** Verifies owner approval over a versioned, byte-length-framed manifest preimage. */ +public final class TenantAssociationManifestVerifier { + private static final String DOMAIN = "firemud/legacy-tenant-association-manifest/v1"; + private static final int MAX_ENTRIES = 5000; + + private TenantAssociationManifestVerifier() {} + + public static Verified verify(Signed signed, Map trustedPublicKeys) { + if (signed == null || signed.manifest() == null || trustedPublicKeys == null) { + throw new IllegalArgumentException("approved tenant-association manifest is required"); + } + TenantAssociationManifest manifest = signed.manifest(); + validate(manifest); + String encodedKey = trustedPublicKeys.get(manifest.signerKeyId()); + if (encodedKey == null || encodedKey.isBlank()) { + throw new IllegalArgumentException("manifest signer is not trusted"); + } + byte[] preimage = preimage(manifest); + try { + PublicKey publicKey = + KeyFactory.getInstance("Ed25519") + .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey))); + Signature signature = Signature.getInstance("Ed25519"); + signature.initVerify(publicKey); + signature.update(preimage); + byte[] signatureBytes = + signed.ed25519Signature() == null + ? new byte[0] + : Base64.getDecoder().decode(signed.ed25519Signature()); + if (signatureBytes.length != 64 + || !Base64.getEncoder().encodeToString(signatureBytes).equals(signed.ed25519Signature()) + || !signature.verify(signatureBytes)) { + throw new IllegalArgumentException("manifest owner signature is invalid"); + } + String digest = + "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + return new Verified(manifest, digest); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalArgumentException("manifest owner signature cannot be verified", ex); + } + } + + /** Exact bytes the offline Game Design owner signs for this manifest version. */ + public static byte[] preimage(TenantAssociationManifest manifest) { + validate(manifest); + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream output = new DataOutputStream(bytes); + write(output, DOMAIN); + output.writeInt(manifest.schemaVersion()); + write(output, manifest.operationId().toString()); + write(output, manifest.targetNamespace()); + write(output, manifest.signerKeyId()); + write(output, manifest.approvedBy()); + write(output, manifest.approvalReference()); + write(output, manifest.signedAt().toString()); + output.writeInt(manifest.entries().size()); + for (Entry entry : manifest.entries()) { + output.writeLong(entry.legacyAccountTenantId()); + write(output, entry.legacyGameTenantId()); + write(output, entry.canonicalTenantId().toString()); + output.writeLong(entry.sourceGameRowId()); + write(output, entry.accountEvidenceDigest()); + } + return bytes.toByteArray(); + } catch (IOException ex) { + throw new IllegalStateException("in-memory manifest framing failed", ex); + } + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(bytes.length); + output.write(bytes); + } + + private static void validate(TenantAssociationManifest manifest) { + if (manifest.schemaVersion() != 1 + || manifest.operationId() == null + || !valid(manifest.targetNamespace(), 63) + || !valid(manifest.signerKeyId(), 128) + || !valid(manifest.approvedBy(), 256) + || !valid(manifest.approvalReference(), 512) + || manifest.signedAt() == null + || manifest.entries() == null + || manifest.entries().isEmpty() + || manifest.entries().size() > MAX_ENTRIES) { + throw new IllegalArgumentException("manifest scope, approval, or version is invalid"); + } + Set gameKeys = new HashSet<>(); + Set canonicalIds = new HashSet<>(); + Set gameRows = new HashSet<>(); + long previousAccountKey = 0; + for (Entry entry : manifest.entries()) { + if (entry == null + || entry.legacyAccountTenantId() <= previousAccountKey + || !valid(entry.legacyGameTenantId(), 36) + || entry.canonicalTenantId() == null + || entry.sourceGameRowId() <= 0 + || entry.accountEvidenceDigest() == null + || !entry.accountEvidenceDigest().matches("sha256:[0-9a-f]{64}") + || !gameKeys.add(entry.legacyGameTenantId()) + || !canonicalIds.add(entry.canonicalTenantId()) + || !gameRows.add(entry.sourceGameRowId())) { + throw new IllegalArgumentException("manifest entries are malformed or ambiguous"); + } + previousAccountKey = entry.legacyAccountTenantId(); + } + } + + private static boolean valid(String value, int maxLength) { + return value != null + && !value.isBlank() + && value.length() <= maxLength + && value.chars().noneMatch(Character::isISOControl); + } + + public record Verified(TenantAssociationManifest manifest, String manifestDigest) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantAssociationMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantAssociationMigrationService.java new file mode 100644 index 0000000000..d434db464b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantAssociationMigrationService.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifestVerifier; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifestVerifier.Verified; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Guarded, immutable Game Design owner assertion for an approved legacy tenant manifest. */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring transaction collaborator.") +public class TenantAssociationMigrationService { + private final DSLContext dsl; + private final GameRepository gameRepository; + + public TenantAssociationMigrationService(DSLContext dsl, GameRepository gameRepository) { + this.dsl = dsl; + this.gameRepository = gameRepository; + } + + @Transactional + public List apply( + Signed signed, Map trustedPublicKeys, String exactNamespace) { + Verified verified = TenantAssociationManifestVerifier.verify(signed, trustedPublicKeys); + TenantAssociationManifest manifest = Objects.requireNonNull(verified).manifest(); + if (exactNamespace == null || !exactNamespace.equals(manifest.targetNamespace())) { + throw new IllegalArgumentException("manifest targets a different namespace"); + } + List existing = findByOperation(manifest.operationId()); + if (!existing.isEmpty() || operationExists(manifest.operationId())) { + assertExactReadback(verified, signed.ed25519Signature(), existing); + return existing; + } + + for (Entry entry : manifest.entries()) { + requireExactSource( + entry.legacyGameTenantId(), entry.canonicalTenantId(), entry.sourceGameRowId()); + } + + int inserted = + dsl.execute( + "INSERT INTO legacy_account_tenant_association_operations " + + "(operation_id, manifest_digest, signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, entry_count, schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (operation_id) DO NOTHING", + manifest.operationId(), + verified.manifestDigest(), + signed.ed25519Signature(), + manifest.targetNamespace(), + manifest.signerKeyId(), + manifest.approvedBy(), + manifest.approvalReference(), + manifest.signedAt().toString(), + manifest.entries().size(), + manifest.schemaVersion()); + if (inserted == 0) { + List concurrent = findByOperation(manifest.operationId()); + assertExactReadback(verified, signed.ed25519Signature(), concurrent); + return concurrent; + } + for (Entry entry : manifest.entries()) { + dsl.execute( + "INSERT INTO legacy_account_tenant_associations " + + "(legacy_account_tenant_id, legacy_game_tenant_id, canonical_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id) " + + "VALUES (?, ?, ?, ?, ?, ?)", + entry.legacyAccountTenantId(), + entry.legacyGameTenantId(), + entry.canonicalTenantId(), + entry.sourceGameRowId(), + entry.accountEvidenceDigest(), + manifest.operationId()); + } + List committed = findByOperation(manifest.operationId()); + assertExactReadback(verified, signed.ed25519Signature(), committed); + return committed; + } + + @Transactional(readOnly = true) + public Optional findByLegacyAccountTenantId(long legacyAccountTenantId) { + if (legacyAccountTenantId <= 0) { + return Optional.empty(); + } + Record row = + dsl.fetchOne( + "SELECT a.legacy_account_tenant_id, a.legacy_game_tenant_id, " + + "a.canonical_tenant_id, a.source_game_row_id, a.account_evidence_digest, " + + "o.operation_id, o.manifest_digest, o.signature, o.target_namespace, o.signer_key_id, " + + "o.approved_by, o.approval_reference, o.signed_at, o.entry_count, " + + "o.schema_version " + + "FROM legacy_account_tenant_associations a " + + "JOIN legacy_account_tenant_association_operations o " + + "ON o.operation_id = a.operation_id " + + "WHERE a.legacy_account_tenant_id = ?", + legacyAccountTenantId); + return Optional.ofNullable(row) + .map(this::map) + .map( + association -> { + requireExactSource( + association.legacyGameTenantId(), + association.canonicalTenantId(), + association.sourceGameRowId()); + return association; + }); + } + + private void requireExactSource(String legacyGameTenantId, UUID canonicalTenantId, long gameId) { + GameTenantIdentity identity = + gameRepository + .findTenantIdentityByLegacyTenantId(legacyGameTenantId) + .orElseThrow(() -> new IllegalStateException("manifest Game Design source is absent")); + if (!canonicalTenantId.equals(identity.canonicalTenantId()) + || !legacyGameTenantId.equals(identity.sourceLegacyTenantId()) + || !Long.valueOf(gameId).equals(identity.sourceGameId())) { + throw new IllegalStateException("manifest Game Design source identity changed"); + } + } + + private boolean operationExists(UUID operationId) { + return Boolean.TRUE.equals( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM legacy_account_tenant_association_operations " + + "WHERE operation_id = ?)", + operationId)) + .get(0, Boolean.class)); + } + + private List findByOperation(UUID operationId) { + List result = new ArrayList<>(); + for (Record row : + dsl.fetch( + "SELECT a.legacy_account_tenant_id, a.legacy_game_tenant_id, " + + "a.canonical_tenant_id, a.source_game_row_id, a.account_evidence_digest, " + + "o.operation_id, o.manifest_digest, o.signature, o.target_namespace, o.signer_key_id, " + + "o.approved_by, o.approval_reference, o.signed_at, o.entry_count, " + + "o.schema_version " + + "FROM legacy_account_tenant_associations a " + + "JOIN legacy_account_tenant_association_operations o " + + "ON o.operation_id = a.operation_id " + + "WHERE o.operation_id = ? ORDER BY a.legacy_account_tenant_id", + operationId)) { + result.add(map(row)); + } + return List.copyOf(result); + } + + private ApprovedAssociation map(Record row) { + return new ApprovedAssociation( + row.get(0, Long.class), + row.get(1, String.class), + row.get(2, UUID.class), + row.get(3, Long.class), + row.get(4, String.class), + row.get(5, UUID.class), + row.get(6, String.class), + row.get(7, String.class), + row.get(8, String.class), + row.get(9, String.class), + row.get(10, String.class), + row.get(11, String.class), + row.get(12, String.class), + row.get(13, Integer.class), + row.get(14, Integer.class)); + } + + private void assertExactReadback( + Verified verified, String signature, List rows) { + TenantAssociationManifest manifest = verified.manifest(); + if (rows.size() != manifest.entries().size()) { + throw new IllegalStateException("manifest operation readback count differs"); + } + for (int index = 0; index < rows.size(); index++) { + Entry expected = manifest.entries().get(index); + ApprovedAssociation actual = rows.get(index); + if (actual.legacyAccountTenantId() != expected.legacyAccountTenantId() + || !actual.legacyGameTenantId().equals(expected.legacyGameTenantId()) + || !actual.canonicalTenantId().equals(expected.canonicalTenantId()) + || actual.sourceGameRowId() != expected.sourceGameRowId() + || !actual.accountEvidenceDigest().equals(expected.accountEvidenceDigest()) + || !actual.operationId().equals(manifest.operationId()) + || !actual.manifestDigest().equals(verified.manifestDigest()) + || !actual.signature().equals(signature) + || !actual.targetNamespace().equals(manifest.targetNamespace()) + || !actual.signerKeyId().equals(manifest.signerKeyId()) + || !actual.approvedBy().equals(manifest.approvedBy()) + || !actual.approvalReference().equals(manifest.approvalReference()) + || !actual.signedAt().equals(manifest.signedAt().toString()) + || actual.entryCount() != manifest.entries().size() + || actual.schemaVersion() != manifest.schemaVersion()) { + throw new IllegalStateException("manifest operation readback differs"); + } + requireExactSource( + actual.legacyGameTenantId(), actual.canonicalTenantId(), actual.sourceGameRowId()); + } + } + + public record ApprovedAssociation( + long legacyAccountTenantId, + String legacyGameTenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String accountEvidenceDigest, + UUID operationId, + String manifestDigest, + String signature, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + int entryCount, + int schemaVersion) {} +} 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 bc403abb4b..cafe76ed7a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -2,10 +2,14 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.util.Base64; import java.util.Optional; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService.ApprovedAssociation; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -17,12 +21,15 @@ public class TenantIdentityGrpcService extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { private final GameRepository gameRepository; + private final TenantAssociationMigrationService associationService; private final String workloadNamespace; public TenantIdentityGrpcService( GameRepository gameRepository, + TenantAssociationMigrationService associationService, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.gameRepository = gameRepository; + this.associationService = associationService; this.workloadNamespace = workloadNamespace; } @@ -30,11 +37,7 @@ public TenantIdentityGrpcService( public void resolveLegacyGameTenantIdentity( ResolveLegacyGameTenantIdentityRequest request, StreamObserver responseObserver) { - GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - if (peer == null - || workloadNamespace == null - || workloadNamespace.isBlank() - || !peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service")) { + if (!isAccountPeer()) { responseObserver.onError( Status.PERMISSION_DENIED .withDescription("Verified Account workload identity is required") @@ -90,4 +93,99 @@ public void resolveLegacyGameTenantIdentity( .build()); responseObserver.onCompleted(); } + + @Override + public void resolveLegacyAccountTenantAssociation( + ResolveLegacyAccountTenantAssociationRequest request, + StreamObserver responseObserver) { + if (!isAccountPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Account workload identity is required") + .asRuntimeException()); + return; + } + if (request.getLegacyAccountTenantId() <= 0) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Positive exact legacy Account tenant key is required") + .asRuntimeException()); + return; + } + Optional resolved; + try { + resolved = associationService.findByLegacyAccountTenantId(request.getLegacyAccountTenantId()); + } catch (IllegalStateException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Approved tenant association provenance is invalid") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No approved association for exact Account legacy tenant key") + .asRuntimeException()); + return; + } + ApprovedAssociation association = resolved.orElseThrow(); + if (!workloadNamespace.equals(association.targetNamespace()) + || association.legacyAccountTenantId() != request.getLegacyAccountTenantId() + || association.canonicalTenantId() == null + || association.sourceGameRowId() <= 0 + || association.operationId() == null + || association.accountEvidenceDigest() == null + || !association.accountEvidenceDigest().matches("sha256:[0-9a-f]{64}") + || association.manifestDigest() == null + || !association.manifestDigest().matches("sha256:[0-9a-f]{64}") + || !validSignature(association.signature()) + || association.entryCount() <= 0 + || association.schemaVersion() != 1) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Approved tenant association readback is incomplete") + .asRuntimeException()); + return; + } + responseObserver.onNext( + ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(association.legacyAccountTenantId()) + .setSourceLegacyGameTenantId(association.legacyGameTenantId()) + .setCanonicalTenantId(association.canonicalTenantId().toString()) + .setSourceGameRowId(association.sourceGameRowId()) + .setAccountEvidenceDigest(association.accountEvidenceDigest()) + .setOperationId(association.operationId().toString()) + .setManifestDigest(association.manifestDigest()) + .setTargetNamespace(association.targetNamespace()) + .setSignerKeyId(association.signerKeyId()) + .setApprovedBy(association.approvedBy()) + .setApprovalReference(association.approvalReference()) + .setSignedAt(association.signedAt()) + .setOperationEntryCount(association.entryCount()) + .setManifestSignature(association.signature()) + .setManifestSchemaVersion(association.schemaVersion()) + .build()); + responseObserver.onCompleted(); + } + + private boolean isAccountPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && workloadNamespace != null + && !workloadNamespace.isBlank() + && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"); + } + + private static boolean validSignature(String value) { + if (value == null) { + return false; + } + try { + byte[] decoded = Base64.getDecoder().decode(value); + return decoded.length == 64 && Base64.getEncoder().encodeToString(decoded).equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } } diff --git a/services/game-design-service/src/main/resources/db/migration/V31__approved_legacy_account_tenant_associations.sql b/services/game-design-service/src/main/resources/db/migration/V31__approved_legacy_account_tenant_associations.sql new file mode 100644 index 0000000000..3ab664e045 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V31__approved_legacy_account_tenant_associations.sql @@ -0,0 +1,48 @@ +-- A Game Design owner-approved manifest is the only source of a retained Account +-- numeric tenant key to canonical Game Design tenant UUID association. No row is +-- inferred from matching numeric/text keys or inserted by this migration. +CREATE TABLE legacy_account_tenant_association_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + manifest_digest VARCHAR(71) NOT NULL UNIQUE, + signature VARCHAR(128) NOT NULL, + target_namespace VARCHAR(128) NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at VARCHAR(40) NOT NULL, + entry_count INTEGER NOT NULL CHECK (entry_count > 0), + committed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT legacy_tenant_manifest_digest_shape + CHECK (manifest_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT legacy_tenant_signature_shape + CHECK (length(signature) = 88) +); + +CREATE TABLE legacy_account_tenant_associations ( + legacy_account_tenant_id BIGINT PRIMARY KEY CHECK (legacy_account_tenant_id > 0), + legacy_game_tenant_id VARCHAR(36) NOT NULL UNIQUE, + canonical_tenant_id UUID NOT NULL UNIQUE, + source_game_row_id BIGINT NOT NULL UNIQUE REFERENCES game(id), + account_evidence_digest VARCHAR(71) NOT NULL, + operation_id UUID NOT NULL REFERENCES legacy_account_tenant_association_operations(operation_id), + CONSTRAINT legacy_tenant_account_evidence_digest_shape + CHECK (account_evidence_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION reject_legacy_tenant_association_change() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Approved legacy tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER legacy_tenant_association_operation_immutable + BEFORE UPDATE OR DELETE ON legacy_account_tenant_association_operations + FOR EACH ROW EXECUTE FUNCTION reject_legacy_tenant_association_change(); + +CREATE TRIGGER legacy_tenant_association_immutable + BEFORE UPDATE OR DELETE ON legacy_account_tenant_associations + FOR EACH ROW EXECUTE FUNCTION reject_legacy_tenant_association_change(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/TenantAssociationMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/TenantAssociationMigrationIntegrationTest.java new file mode 100644 index 0000000000..3129f3e92e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/TenantAssociationMigrationIntegrationTest.java @@ -0,0 +1,203 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifestVerifier; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class TenantAssociationMigrationIntegrationTest { + private static final String SCHEMA = "game_design_tenant_association_proof"; + private static final String ACCOUNT_DIGEST = "sha256:" + "a".repeat(64); + private static final UUID OPERATION_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void approvedAssociationIsImmutableExactRetryableAndConflictsFailClosed() throws Exception { + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .load() + .migrate(); + + try (Connection connection = dataSource.getConnection()) { + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO " + SCHEMA); + } + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + GameRepository repository = new GameRepository(dsl); + Game game = new Game(); + game.setTenantId("legacy-game-7"); + game.setName("Approved game"); + Game saved = repository.save(game); + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + Map trustedKeys = + Map.of( + "game-design-owner-2026", + Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded())); + Signed signed = signed(saved, OPERATION_ID, "legacy-game-7", ownerKey); + String manifestDigest = + TenantAssociationManifestVerifier.verify(signed, trustedKeys).manifestDigest(); + TenantAssociationMigrationService service = + new TenantAssociationMigrationService(dsl, repository); + + var first = + dsl.transactionResult(configuration -> service.apply(signed, trustedKeys, SCHEMA)); + assertThat(first).hasSize(1); + assertThat(first.getFirst().legacyAccountTenantId()).isEqualTo(41L); + assertThat(first.getFirst().canonicalTenantId()).isEqualTo(saved.getCanonicalTenantId()); + assertThat(first.getFirst().manifestDigest()).isEqualTo(manifestDigest); + assertThat(first.getFirst().schemaVersion()).isEqualTo(1); + assertThat(service.findByLegacyAccountTenantId(41L)).contains(first.getFirst()); + assertThat(service.findByLegacyAccountTenantId(42L)).isEmpty(); + + var exactRetry = + dsl.transactionResult(configuration -> service.apply(signed, trustedKeys, SCHEMA)); + assertThat(exactRetry).isEqualTo(first); + assertThat( + dsl.fetchCount(DSL.table(DSL.name("legacy_account_tenant_association_operations")))) + .isEqualTo(1); + assertThat(dsl.fetchCount(DSL.table(DSL.name("legacy_account_tenant_associations")))) + .isEqualTo(1); + + Signed changedDigest = + signed( + saved, + OPERATION_ID, + "legacy-game-7", + KeyPairGenerator.getInstance("Ed25519").generateKeyPair()); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(changedDigest, trustedKeys, SCHEMA))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + TenantAssociationManifest changedApprovalManifest = + new TenantAssociationManifest( + 1, + OPERATION_ID, + SCHEMA, + "game-design-owner-2026", + "different-owner@example.test", + "reviewed-change-123", + signed.manifest().signedAt(), + signed.manifest().entries()); + Signed changedApproval = sign(changedApprovalManifest, ownerKey); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(changedApproval, trustedKeys, SCHEMA))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(signed, trustedKeys, "other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("different namespace"); + + Signed absentSource = + signed( + saved, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "not-a-game", + ownerKey); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(absentSource, trustedKeys, SCHEMA))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source is absent"); + + Signed duplicateAccountKey = + signed( + saved, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "legacy-game-7", + ownerKey); + assertThatThrownBy( + () -> + dsl.transactionResult( + configuration -> service.apply(duplicateAccountKey, trustedKeys, SCHEMA))) + .isInstanceOf(DataAccessException.class); + assertThat( + dsl.fetchCount(DSL.table(DSL.name("legacy_account_tenant_association_operations")))) + .isEqualTo(1); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE legacy_account_tenant_associations SET " + + "account_evidence_digest = ? WHERE legacy_account_tenant_id = ?", + "sha256:" + "f".repeat(64), + 41L)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Approved legacy tenant association evidence is immutable"); + } + } + + private DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private Signed signed(Game saved, UUID operationId, String sourceKey, KeyPair ownerKey) + throws Exception { + TenantAssociationManifest manifest = + new TenantAssociationManifest( + 1, + operationId, + SCHEMA, + "game-design-owner-2026", + "owner@example.test", + "reviewed-change-123", + Instant.parse("2026-09-26T00:00:00Z"), + List.of( + new Entry( + 41L, sourceKey, saved.getCanonicalTenantId(), saved.getId(), ACCOUNT_DIGEST))); + return sign(manifest, ownerKey); + } + + private Signed sign(TenantAssociationManifest manifest, KeyPair ownerKey) throws Exception { + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(ownerKey.getPrivate()); + signature.update(TenantAssociationManifestVerifier.preimage(manifest)); + return new Signed(manifest, Base64.getEncoder().encodeToString(signature.sign())); + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifierTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifierTest.java new file mode 100644 index 0000000000..7547d8610d --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestVerifierTest.java @@ -0,0 +1,131 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; +import org.junit.jupiter.api.Test; + +class TenantAssociationManifestVerifierTest { + private static final String ACCOUNT_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void exactApprovedManifestVerifiesAndChangedAssociationCannotReuseSignature() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + TenantAssociationManifest manifest = manifest(); + Map trustedKeys = + Map.of( + "game-design-owner-2026", + Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded())); + Signed signed = signed(manifest, ownerKey); + + var verified = TenantAssociationManifestVerifier.verify(signed, trustedKeys); + assertThat(verified.manifest()).isEqualTo(manifest); + assertThat(verified.manifestDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(TenantAssociationManifestVerifier.verify(signed, trustedKeys).manifestDigest()) + .isEqualTo(verified.manifestDigest()); + + TenantAssociationManifest changed = + new TenantAssociationManifest( + manifest.schemaVersion(), + manifest.operationId(), + manifest.targetNamespace(), + manifest.signerKeyId(), + manifest.approvedBy(), + manifest.approvalReference(), + manifest.signedAt(), + List.of( + new Entry( + 42, + "legacy-game", + manifest.entries().getFirst().canonicalTenantId(), + 7, + ACCOUNT_DIGEST))); + assertThatThrownBy( + () -> + TenantAssociationManifestVerifier.verify( + new Signed(changed, signed.ed25519Signature()), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + assertThatThrownBy(() -> TenantAssociationManifestVerifier.verify(signed, Map.of())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not trusted"); + } + + @Test + void duplicateAndUnsortedPairsAreRejectedBeforeOwnerApproval() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + TenantAssociationManifest source = manifest(); + Entry first = source.entries().getFirst(); + TenantAssociationManifest duplicate = + withEntries( + source, + List.of( + first, + new Entry(43, first.legacyGameTenantId(), UUID.randomUUID(), 8, ACCOUNT_DIGEST))); + TenantAssociationManifest unsorted = + withEntries( + source, + List.of(new Entry(43, "other-game", UUID.randomUUID(), 8, ACCOUNT_DIGEST), first)); + Map keys = + Map.of( + "game-design-owner-2026", + Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded())); + + assertThatThrownBy( + () -> TenantAssociationManifestVerifier.verify(new Signed(duplicate, ""), keys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ambiguous"); + assertThatThrownBy( + () -> TenantAssociationManifestVerifier.verify(new Signed(unsorted, ""), keys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ambiguous"); + } + + private TenantAssociationManifest manifest() { + return new TenantAssociationManifest( + 1, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "dev", + "game-design-owner-2026", + "owner@example.test", + "reviewed-change-123", + Instant.parse("2026-09-26T00:00:00Z"), + List.of( + new Entry( + 41, + "legacy-game", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 7, + ACCOUNT_DIGEST))); + } + + private TenantAssociationManifest withEntries( + TenantAssociationManifest source, List entries) { + return new TenantAssociationManifest( + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + entries); + } + + private Signed signed(TenantAssociationManifest manifest, KeyPair keyPair) throws Exception { + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(keyPair.getPrivate()); + signature.update(TenantAssociationManifestVerifier.preimage(manifest)); + return new Signed(manifest, Base64.getEncoder().encodeToString(signature.sign())); + } +} 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 f6e65b4f47..9fb1b0a3e1 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 @@ -13,11 +13,15 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.util.Base64; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService.ApprovedAssociation; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; import org.junit.jupiter.api.Test; @@ -29,8 +33,52 @@ class TenantIdentityGrpcServiceTest { UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); private final GameRepository repository = mock(GameRepository.class); + private final TenantAssociationMigrationService associationService = + mock(TenantAssociationMigrationService.class); private final TenantIdentityGrpcService service = - new TenantIdentityGrpcService(repository, "test"); + new TenantIdentityGrpcService(repository, associationService, "test"); + + @Test + void approvedAccountAssociationReadBindsExactOwnerAndManifestEvidence() { + when(associationService.findByLegacyAccountTenantId(41L)) + .thenReturn(Optional.of(approvedAssociation())); + + AssociationObserver observer = associationCall(41L, ACCOUNT_PEER); + + assertNull(observer.errorCode); + assertTrue(observer.completed); + assertNotNull(observer.value); + assertEquals(41L, observer.value.getLegacyAccountTenantId()); + assertEquals("legacy-game-7", observer.value.getSourceLegacyGameTenantId()); + assertEquals(CANONICAL_TENANT_ID.toString(), observer.value.getCanonicalTenantId()); + assertEquals("sha256:" + "a".repeat(64), observer.value.getAccountEvidenceDigest()); + assertEquals("sha256:" + "b".repeat(64), observer.value.getManifestDigest()); + assertEquals( + Base64.getEncoder().encodeToString(new byte[64]), observer.value.getManifestSignature()); + assertEquals("reviewed-change-123", observer.value.getApprovalReference()); + assertEquals(1, observer.value.getManifestSchemaVersion()); + verify(associationService).findByLegacyAccountTenantId(41L); + } + + @Test + void associationReadRejectsMissingPeerAndInvalidNumericKeyBeforeOwnerRead() { + assertEquals(Status.Code.PERMISSION_DENIED, associationStatus(associationCall(41L, null))); + assertEquals( + Status.Code.PERMISSION_DENIED, associationStatus(associationCall(41L, WRONG_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, associationStatus(associationCall(0L, ACCOUNT_PEER))); + verifyNoInteractions(associationService); + } + + @Test + void associationReadFailsClosedForAbsentOrCorruptOwnerEvidence() { + when(associationService.findByLegacyAccountTenantId(41L)).thenReturn(Optional.empty()); + when(associationService.findByLegacyAccountTenantId(42L)) + .thenThrow(new IllegalStateException("corrupt operation")); + assertEquals(Status.Code.NOT_FOUND, associationStatus(associationCall(41L, ACCOUNT_PEER))); + assertEquals( + Status.Code.FAILED_PRECONDITION, associationStatus(associationCall(42L, ACCOUNT_PEER))); + } @Test void exactAccountPeerReadsOwnerSourceAndProvenance() { @@ -119,6 +167,48 @@ private TestObserver call(String sourceKey, String peerUri) { return observer; } + private AssociationObserver associationCall(long accountTenantId, String peerUri) { + AssociationObserver observer = new AssociationObserver(); + Context context = Context.current(); + if (peerUri != null) { + context = + context.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + } + context.run( + () -> + service.resolveLegacyAccountTenantAssociation( + ResolveLegacyAccountTenantAssociationRequest.newBuilder() + .setLegacyAccountTenantId(accountTenantId) + .build(), + observer)); + return observer; + } + + private ApprovedAssociation approvedAssociation() { + return new ApprovedAssociation( + 41L, + "legacy-game-7", + CANONICAL_TENANT_ID, + 7L, + "sha256:" + "a".repeat(64), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "sha256:" + "b".repeat(64), + Base64.getEncoder().encodeToString(new byte[64]), + "test", + "game-design-owner-2026", + "owner@example.test", + "reviewed-change-123", + "2026-09-26T00:00:00Z", + 1, + 1); + } + + private static Status.Code associationStatus(AssociationObserver observer) { + assertNotNull(observer.errorCode); + return observer.errorCode; + } + private static Status.Code status(TestObserver observer) { assertNotNull(observer.errorCode); return observer.errorCode; @@ -145,4 +235,26 @@ public void onCompleted() { completed = true; } } + + private static final class AssociationObserver + implements StreamObserver { + private ResolveLegacyAccountTenantAssociationResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ResolveLegacyAccountTenantAssociationResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } } From 94549904782f25ffff6cb3ade71a5c1c2c58105f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 18:33:58 +1200 Subject: [PATCH 14/28] Keep tenant migration client out of ordinary Account startup --- .../client/GameDesignTenantIdentityClient.java | 5 +++++ .../service/impl/LegacyTenantAssociationImportService.java | 5 +++++ .../LegacyTenantAssociationImportIntegrationTest.java | 3 ++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java index 439f0d6788..07a6e086b6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameDesignTenantIdentityClient.java @@ -12,10 +12,15 @@ import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; /** Account-only authenticated read of a Game Design owner-approved legacy association. */ @Component +@ConditionalOnProperty( + prefix = "firemud.account-tenant-migration", + name = "enabled", + havingValue = "true") public class GameDesignTenantIdentityClient extends AbstractReloadingBlockingGrpcClient< TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java index 8e6e28ec66..7e57d9ca3e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/LegacyTenantAssociationImportService.java @@ -4,11 +4,16 @@ import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** Operator-invoked import; neither lookup nor evidence enumeration grants membership admission. */ @Service +@ConditionalOnProperty( + prefix = "firemud.account-tenant-migration", + name = "enabled", + havingValue = "true") public class LegacyTenantAssociationImportService { private final GameDesignTenantIdentityClient ownerClient; private final ApprovedLegacyTenantAssociationRepository repository; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java index 3d3498038e..a9d450afe4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java @@ -33,7 +33,8 @@ class LegacyTenantAssociationImportIntegrationTest { @Test void exactRetainedSourceAndApprovedOwnerReadAreRequiredForImmutableImport() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setUrl(postgres.getJdbcUrl() + "?currentSchema=" + SCHEMA); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + SCHEMA); dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); Flyway.configure() From 628b5e2d910b5d21f7a22884f605086b41714248 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 18:52:24 +1200 Subject: [PATCH 15/28] Wire dedicated tenant association migration identities and jobs --- .github/workflows/ci.yml | 3 + .../account-service/operations.md | 6 +- .../game-design-service/api-contracts.md | 2 +- .../game-design-service/operations.md | 6 +- design/project-management/ai-observations.md | 4 + ...ame-authoring-publishing-and-activation.md | 2 +- .../player-access-and-session.md | 2 +- ...nsure-standalone-transport-certificates.sh | 35 ++- ...m-tenant-association-migration-contract.sh | 130 +++++++++++ ...d-identity-controller-manifest-contract.sh | 44 ++++ ...ndalone-transport-certificates-contract.sh | 107 ++++++++- .../trust-bootstrap-issuance-contract.sh | 102 ++++++++- .../firemud/templates/network-policies.yaml | 88 ++++++++ .../tenant-association-account-job.yaml | 185 +++++++++++++++ .../tenant-association-game-design-job.yaml | 210 ++++++++++++++++++ k8s/helm/firemud/values.yaml | 18 ++ k8s/hosted-identity-controller/admission.yaml | 84 ++++++- k8s/trust-bootstrap/issuance-admission.yaml | 58 ++++- ...egacyTenantAssociationImportJobRunner.java | 16 +- ...enantAssociationImportIntegrationTest.java | 3 + ...yTenantAssociationImportJobRunnerTest.java | 35 +++ .../firemud/common/grpc/GrpcPeerIdentity.java | 2 + .../common/grpc/GrpcPeerIdentityTest.java | 13 ++ .../TenantAssociationManifestJobRunner.java | 24 ++ .../impl/TenantIdentityGrpcService.java | 13 +- ...enantAssociationManifestJobRunnerTest.java | 34 +++ .../impl/TenantIdentityGrpcServiceTest.java | 17 +- 27 files changed, 1201 insertions(+), 42 deletions(-) create mode 100644 dev-tools/tests/helm-tenant-association-migration-contract.sh create mode 100644 k8s/helm/firemud/templates/tenant-association-account-job.yaml create mode 100644 k8s/helm/firemud/templates/tenant-association-game-design-job.yaml create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e606f5bf12..12ea985a33 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -640,6 +640,9 @@ jobs: - name: 🧪 Validate rendered Helm manifests run: bash ./dev-tools/validation/validate-helm.sh render + - name: 🧪 Validate opt-in tenant migration Jobs + run: bash ./dev-tools/tests/helm-tenant-association-migration-contract.sh + - name: 🧪 Validate hosted Telnet TLS contract run: bash ./dev-tools/tests/hosted-telnet-tls-contract.sh diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 8876853317..bd29c42c19 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -11,9 +11,11 @@ This document collects the Account Service operational behavior, readiness model ### Legacy tenant association import -**Current implementation status:** V30 and the opt-in `LegacyTenantAssociationImportJobRunner` provide an Account-owned read of retained V26 tenant, membership, and profile source rows, a versioned SHA-256 evidence digest, and guarded import from Game Design's exact Account-peer-only owner read. The Account import compares that digest, deployment namespace, source key, UUID, operation and approval evidence before immutable one-to-one storage and exact readback. It does not auto-map rows or enable membership admission. Focused malformed-owner-response unit proof executed; PostgreSQL import/readback proof compiled but skipped without Docker, and no live manifest or cross-service migration has run. +**Current implementation status:** V30 and the opt-in `LegacyTenantAssociationImportJobRunner` provide an Account-owned read of retained V26 tenant, membership, and profile source rows, a versioned SHA-256 evidence digest, and guarded import from Game Design's exact tenant-migrator-only owner read. The Account import compares that digest, deployment namespace, source key, UUID, operation and approval evidence before immutable one-to-one storage and exact readback. It does not auto-map rows or enable membership admission. A focused malformed-owner-response unit test and the dedicated-identity guard tests executed locally; the PostgreSQL import/readback case executed but failed at fixture setup on the preceding CI head and its correction awaits exact-head CI. No live manifest or cross-service migration has run. -An operator first runs `evidence` for an exact positive retained numeric key in a listener-free Account job using the Account workload certificate. Missing or conflicting V26 source rows fail closed. The digest goes into the [Game Design approved manifest](../game-design-service/operations.md#legacy-tenant-association-migration), not into an inferred key match. After Game Design applies and reads back the signed operation, the operator runs Account `import` for the same key. That mode calls Game Design with the exact Account mTLS identity, validates its owner response and the current V26 digest, and commits the immutable local mapping. An exact retry is event-free; changed owner or Account evidence is a conflict. Job deployment and executed PostgreSQL, cross-service, and membership consumer proof remain open; an import cannot be treated as a JOIN, a sequence-zero stream checkpoint, or a working runtime membership RPC. +An operator first runs `evidence` for an exact positive retained numeric key in a listener-free Account job using the dedicated `account-tenant-migrator` certificate and service account. Missing or conflicting V26 source rows fail closed. The digest goes into the [Game Design approved manifest](../game-design-service/operations.md#legacy-tenant-association-migration), not into an inferred key match. After Game Design applies and reads back the signed operation, the operator runs Account `import` for the same key. That mode calls Game Design with the exact migrator mTLS identity, validates its owner response and the current V26 digest, and commits the immutable local mapping. Ordinary Account service identity cannot call this import read; the migrator cannot call the separate former-key read. An exact retry is event-free; changed owner or Account evidence is a conflict. + +The chart's `previewStack.tenantAssociationMigration.account` values are disabled by default. From a trusted operator revision, supply the exact namespace, a reviewed immutable Account image digest, mode (`evidence` or `import`), positive numeric key, and stable run ID; do not leave the Job enabled for ordinary upgrades. The dedicated `firemud-grpc-account-tenant-migrator` Secret must be issued and verified explicitly using `ensure-standalone-transport-certificates.sh --account-tenant-migrator` and `--verify-account-tenant-migrator` before enabling the Job. The Secret is stable and reused, not requested on every deployment; the Job has no Kubernetes API token, no ingress, and only DNS/Postgres egress plus Game Design gRPC for `import`. A rendered Job or successful completion alone is not database or served-mTLS proof. Retain the operation/readback evidence privately, disable the Job after use, and retire the exact certificate and Secret through the trusted operator boundary. Live Job, PostgreSQL, cross-service, and membership consumer proof remain open; an import cannot be treated as a JOIN, a sequence-zero stream checkpoint, or a working runtime membership RPC. ## Saga Participation diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 987efda189..19db5c4f8d 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -10,7 +10,7 @@ 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 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 Account-peer-only, 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. +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 owner-local UUID source/read is being introduced as a bounded prerequisite; it does not make the Account runtime membership snapshot RPC safe to enable. Live retained-row migration, mounted-certificate acceptance, and Account/Game Session consumer proof must be reported separately from schema and unit tests. diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index de2f770aec..9ab7d16f2c 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -30,9 +30,11 @@ The target publication boundary treats object-store export as a durable candidat ### Legacy tenant association migration -**Current implementation status:** V31 and the opt-in `TenantAssociationManifestJobRunner` can verify a trusted Ed25519 owner signature over a versioned, byte-length-framed manifest, compare every former Game Design key and canonical UUID with its persisted V30 source row, and store/read back the immutable operation and one-to-one associations. The job requires an exact deployment namespace and a dedicated `game-design-tenant-migrator` service account, with listeners and Temporal disabled. It is not a public mutation route and ordinary startup does not import any association. Local focused verifier/gRPC tests executed, but the PostgreSQL test skipped without Docker; no real manifest, job deployment, retained-row set, or live readback has been proved. +**Current implementation status:** V31 and the opt-in `TenantAssociationManifestJobRunner` can verify a trusted Ed25519 owner signature over a versioned, byte-length-framed manifest, compare every former Game Design key and canonical UUID with its persisted V30 source row, and store/read back the immutable operation and one-to-one associations. The job requires an exact deployment namespace, dedicated `game-design-tenant-migrator` service account and certificate, with listeners and Temporal disabled. It is not a public mutation route and ordinary startup does not import any association. Local focused verifier/gRPC/identity tests executed, and the V31 PostgreSQL test executed and passed in hosted CI on the preceding head; no real signed manifest, Job deployment, retained-row set, or live readback has been proved. -For an approved operation, first obtain Account's exact retained-source evidence digest from its [Account owner migration mode](../account-service/operations.md#legacy-tenant-association-import). The Game Design owner then reviews the explicit numeric Account key, former Game Design key, V30 game row, canonical UUID, namespace, stable operation identity, and Account evidence digest; records the approval reference; and signs the canonical manifest preimage using an owner-controlled key already trusted by the migration job. A preflight verifies the signed bytes and exact namespace without writing. Only an operator-invoked `apply` with that same signed manifest and trusted public-key set writes V31; an exact retry must return the same readback and a conflicting pair fails. Account then imports from the authenticated owner read and checks its retained evidence before the membership consumer can be considered. This order does not enable the disabled runtime membership RPC. The job image, trusted-key Secret, signed-manifest Secret, certificate/namespace wiring, and an executed migration readback still require deployment proof; do not describe this code-only path as an applied data migration. +For an approved operation, first obtain Account's exact retained-source evidence digest from its [Account owner migration mode](../account-service/operations.md#legacy-tenant-association-import). The Game Design owner then reviews the explicit numeric Account key, former Game Design key, V30 game row, canonical UUID, namespace, stable operation identity, and Account evidence digest; records the approval reference; and signs the canonical manifest preimage using an owner-controlled key already trusted by the migration job. A preflight verifies the signed bytes and exact namespace without writing. Only an operator-invoked `apply` with that same signed manifest and trusted public-key set writes V31; an exact retry must return the same readback and a conflicting pair fails. Account then imports from the authenticated owner read and checks its retained evidence before the membership consumer can be considered. This order does not enable the disabled runtime membership RPC. + +The chart's `previewStack.tenantAssociationMigration.gameDesign` values are disabled by default. A trusted operator supplies an immutable Game Design image digest, exact namespace, stable run ID, mode, signed-manifest Secret and trusted-key Secret. Explicitly issue and verify the stable `firemud-grpc-game-design-tenant-migrator` identity using `ensure-standalone-transport-certificates.sh --game-design-tenant-migrator` and `--verify-game-design-tenant-migrator` before enabling the Job; the ordinary Game Design certificate is not a fallback. This dedicated certificate is a workload attestation guard, not an outbound owner-read credential. The Job has no Kubernetes API token or ingress and only DNS/Postgres egress; no ordinary Helm release creates it. Disable the Job after use and retire its exact certificate and Secret through the trusted operator boundary. A rendered Job is not executed migration proof: the live certificate, trusted Secrets, actual manifest, PostgreSQL readback and Account import still require deployment proof. Do not describe this path as an applied data migration until those checks execute. ### Historical Entity digest baseline migration diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 28c5b8177b..abcd0f9309 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -114,3 +114,7 @@ Entry format: - Context: Account and Game Design added UUID identity-source migrations while preserving numeric retained rows. The configured community jOOQ DDL parser rejected `GENERATED ALWAYS AS` and some grouped `ALTER COLUMN`/PostgreSQL function syntax, even though those are database constructs. - Observation: replacing Account's generated source column with a trigger-bound immutable column and isolating Game Design's PostgreSQL-only DDL behind the existing jOOQ-ignore markers let schema generation proceed. Local Testcontainers cases compiled but skipped without Docker, so parser success is not PostgreSQL migration execution. - Expected pattern: run jOOQ generation, Flyway numbering, and focused Java tests locally; keep a separate exact-head PostgreSQL migration/readback gate on a runner with Docker, and report any skipped integration case as unproved rather than green runtime evidence. + +- `2026-09-26`: Standalone Flyway migration fixtures must reproduce JDBC and placeholder configuration + - Context: #2873's Account tenant-association PostgreSQL test passed local compilation but skipped without Docker. Its first hosted run could not find an inserted table because a new `?currentSchema=` was appended to a Testcontainers JDBC URL that already carried a query string. After preserving the existing separator, the next run reached the later saga migration and failed because the standalone Flyway invocation omitted `${serviceSchema}`. + - Expected pattern: preserve existing JDBC URL parameters when adding a schema selector, and supply the same Flyway placeholders for both target-version setup and subsequent full migration. Treat each hosted failure as fixture evidence until the exact database case executes and passes; local compilation is not that proof. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index b9e6553892..6bfbac7aea 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. -The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30 assigns each retained `game` row a unique UUID with immutable row/former-key provenance, new game rows receive distinct issued UUIDs, and an Account-workload-only read returns the exact persisted source tuple. The in-progress V31 addition defines a separate signed, owner-approved manifest operation for exact Account numeric-key associations. It verifies the former Game Design key, source row, and issued UUID, stores immutable one-to-one evidence, and exposes the exact approved tuple only to the Account workload. Focused manifest and gRPC unit tests execute locally; the new PostgreSQL manifest case compiles but skips without Docker. No actual manifest has been applied or read back in a deployed environment, and the Account bridge/consumer proof remains incomplete. This is not the stable `tenantSlug` catalog/selector or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain non-admitting until the owner assertion, bridge readback, and consumer proof exist. +The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30 assigns each retained `game` row a unique UUID with immutable row/former-key provenance, new game rows receive distinct issued UUIDs, and an Account-workload-only former-key read returns the exact persisted source tuple. The V31 addition defines a separate signed, owner-approved manifest operation for exact Account numeric-key associations. It verifies the former Game Design key, source row, and issued UUID, stores immutable one-to-one evidence, and exposes the exact approved tuple only to the dedicated Account tenant migrator, never ordinary Account or another service peer. Its opt-in chart Job uses a separate, explicitly issued and verified certificate rather than replacing Gameplay or service identities. Focused manifest, gRPC, certificate/admission, and Helm-render tests execute locally; the new PostgreSQL manifest case executed and passed in hosted CI on the preceding head. No actual manifest has been applied or read back in a deployed environment, and the Account bridge/consumer proof remains incomplete. This is not the stable `tenantSlug` catalog/selector or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain non-admitting until the owner assertion, bridge readback, and consumer proof exist. Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 8a303d965d..428475e27a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,7 +14,7 @@ The current Unit 1B draft adds Account-owned provisional JOIN/reactivation trans Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). -The in-progress #2873 tenant bridge now has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact-Account-peer 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 jobs are opt-in and the runtime membership RPC remains denied. Local focused manifest, gRPC, and Account negative tests executed; both new PostgreSQL import/readback cases compiled but skipped without Docker. No real signed manifest, live data association, composed owner/consumer snapshot, or runtime admission proof has been completed. Missing/conflicting rows remain denied; this is not a completed membership authority stream or Unit 1B closure. +The in-progress #2873 tenant bridge now has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact dedicated Account-tenant-migrator gRPC read, and an Account import boundary that recomputes retained V26 source evidence before storing an immutable local mapping. Neither migration auto-creates a pair; both chart Jobs are opt-in and require distinct verified workload certificates, and the runtime membership RPC remains denied. Local focused manifest, gRPC, certificate/admission, Helm-render and Account negative tests executed; Game Design's new V31 PostgreSQL case executed and passed in hosted CI, while Account's new V30 import case has reached Flyway fixture setup but lacks a passing hosted database run after its latest correction. No real signed manifest, live data association, composed owner/consumer snapshot, or runtime admission proof has been completed. Missing/conflicting rows remain denied; this is not a completed membership authority stream or Unit 1B closure. The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. diff --git a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh index 688ad78618..1da17cb453 100755 --- a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh +++ b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh @@ -27,11 +27,29 @@ elif [[ $# -eq 2 && "$1" == --migrator ]]; then elif [[ $# -eq 2 && "$1" == --verify-migrator ]]; then transport_operation='verify-migrator' namespace="$2" +elif [[ $# -eq 2 && "$1" == --account-tenant-migrator ]]; then + transport_operation='write-migrator' + migrator_identity='account-tenant-migrator' + namespace="$2" +elif [[ $# -eq 2 && "$1" == --verify-account-tenant-migrator ]]; then + transport_operation='verify-migrator' + migrator_identity='account-tenant-migrator' + namespace="$2" +elif [[ $# -eq 2 && "$1" == --game-design-tenant-migrator ]]; then + transport_operation='write-migrator' + migrator_identity='game-design-tenant-migrator' + namespace="$2" +elif [[ $# -eq 2 && "$1" == --verify-game-design-tenant-migrator ]]; then + transport_operation='verify-migrator' + migrator_identity='game-design-tenant-migrator' + namespace="$2" else - echo "usage: $0 [--wait|--migrator|--verify-migrator] " >&2 + echo "usage: $0 [--wait|--migrator|--verify-migrator|--account-tenant-migrator|--verify-account-tenant-migrator|--game-design-tenant-migrator|--verify-game-design-tenant-migrator] " >&2 exit 2 fi +migrator_identity="${migrator_identity:-game-design-baseline-migrator}" + if [[ "$transport_operation" == write || "$transport_operation" == wait ]] && [[ ! "$namespace" =~ ^pr-[1-9][0-9]{0,50}$ ]]; then echo "runtime namespace must be canonical pr-N: ${namespace}" >&2 @@ -49,9 +67,14 @@ bridge_certificate="${namespace}-tcp-proxy-bridge" public_hostname="${namespace}.${PREVIEW_DOMAIN}" gateway_dns_name="spring-cloud-gateway-mtls.${namespace}.svc.cluster.local" bridge_uri_san="spiffe://firemud/ns/${namespace}/sa/tcp-proxy-service" -migrator_certificate="${namespace}-grpc-game-design-baseline-migrator" -migrator_secret='firemud-grpc-game-design-baseline-migrator' -migrator_uri_san="spiffe://firemud/ns/${namespace}/sa/game-design-baseline-migrator" +migrator_certificate="${namespace}-grpc-${migrator_identity}" +migrator_secret="firemud-grpc-${migrator_identity}" +migrator_uri_san="spiffe://firemud/ns/${namespace}/sa/${migrator_identity}" +migrator_role="grpc-${migrator_identity}" +migrator_managed_by='entity-baseline-migration' +if [[ "$migrator_identity" == account-tenant-migrator || "$migrator_identity" == game-design-tenant-migrator ]]; then + migrator_managed_by='tenant-association-migration' +fi deadline=$((SECONDS + certificate_wait_timeout_seconds)) write_certificates() { @@ -148,8 +171,8 @@ spec: secretTemplate: metadata: labels: - firemud.dev/managed-by: entity-baseline-migration - firemud.dev/role: grpc-game-design-baseline-migrator + firemud.dev/managed-by: ${migrator_managed_by} + firemud.dev/role: ${migrator_role} firemud.dev/retention: ephemeral annotations: firemud.dev/provenance: cert-manager diff --git a/dev-tools/tests/helm-tenant-association-migration-contract.sh b/dev-tools/tests/helm-tenant-association-migration-contract.sh new file mode 100644 index 0000000000..a3f84a4bc4 --- /dev/null +++ b/dev-tools/tests/helm-tenant-association-migration-contract.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +python3 - "$ROOT_DIR" <<'PY' +import copy +import pathlib +import subprocess +import sys +import tempfile + +import yaml + +root = pathlib.Path(sys.argv[1]) +chart = root / "k8s/helm/firemud" +sha = "a" * 64 + + +def documents(output): + return [document for document in yaml.safe_load_all(output) if isinstance(document, dict)] + + +with tempfile.TemporaryDirectory() as directory: + temporary = pathlib.Path(directory) + values = temporary / "preview-values.yaml" + subprocess.run( + [ + "python3", + str(root / "dev-tools/hosted/preview/render-preview-values.py"), + str(chart / "values-hosted-shared.example.yaml"), + str(values), + "123", + "pr-123", + "pr-123", + "pr-123.preview.firedevops.net", + "pr-123-deadbeef", + "32000", + ], + check=True, + ) + + def render(name, migration=None): + args = ["helm", "template", name, str(chart), "--namespace", "pr-123", "-f", str(values)] + if migration is not None: + override = temporary / f"{name}.yaml" + override.write_text(yaml.safe_dump(migration), encoding="utf-8") + args += ["-f", str(override)] + return subprocess.run(args, capture_output=True, text=True, check=False) + + def require_failure(name, migration, fragment): + result = render(name, migration) + if result.returncode == 0 or fragment not in result.stderr: + raise SystemExit(f"{name} did not fail closed with {fragment}: {result.stderr}") + + disabled = render("tenant-migration-disabled") + if disabled.returncode: + raise SystemExit(disabled.stderr) + forbidden_names = {"game-design-tenant-migrator", "account-tenant-migrator"} + if any( + item.get("metadata", {}).get("name") in forbidden_names + or item.get("metadata", {}).get("name", "").startswith(("game-design-tenant-", "account-tenant-")) + for item in documents(disabled.stdout) + ): + raise SystemExit("ordinary release rendered tenant-migration resources") + + migration = { + "previewStack": { + "tenantAssociationMigration": { + "gameDesign": { + "enabled": True, + "mode": "apply", + "targetNamespace": "pr-123", + "runId": "approved-42", + "image": f"ghcr.io/benhook1013/game-design-service@sha256:{sha}", + "signedManifestSecretName": "tenant-manifest-approved-42", + "trustedKeysSecretName": "tenant-owner-public-keys", + }, + "account": { + "enabled": True, + "mode": "import", + "targetNamespace": "pr-123", + "runId": "approved-42", + "image": f"ghcr.io/benhook1013/account-service@sha256:{sha}", + "legacyTenantId": "41", + }, + } + } + } + enabled = render("tenant-migration-enabled", migration) + if enabled.returncode: + raise SystemExit(enabled.stderr) + by_kind_name = { + (item.get("kind"), item.get("metadata", {}).get("name")): item + for item in documents(enabled.stdout) + } + for service, mode in (("game-design", "apply"), ("account", "import")): + workload = f"{service}-tenant-migrator" + job = by_kind_name[("Job", f"{service}-tenant-{mode}-approved-42")] + pod = job["spec"]["template"]["spec"] + if pod["serviceAccountName"] != workload or pod["automountServiceAccountToken"] is not False: + raise SystemExit(f"{workload} Job did not bind the dedicated tokenless service account") + if by_kind_name[("ServiceAccount", workload)]["automountServiceAccountToken"] is not False: + raise SystemExit(f"{workload} service account mounts an API token") + secret = next(volume["secret"]["secretName"] for volume in pod["volumes"] if volume["name"] == "grpc-identity") + if secret != f"firemud-grpc-{workload}": + raise SystemExit(f"{workload} reused an ordinary service certificate") + policy = by_kind_name[("NetworkPolicy", workload)]["spec"] + if policy["ingress"] != [] or set(policy["policyTypes"]) != {"Ingress", "Egress"}: + raise SystemExit(f"{workload} has an unexpected ingress allowance") + destination_apps = { + selector["podSelector"]["matchLabels"]["app"] + for rule in policy["egress"] + for selector in rule["to"] + if "podSelector" in selector and "app" in selector["podSelector"].get("matchLabels", {}) + } + expected = {"postgres"} | ({"game-design-service"} if service == "account" else set()) + if destination_apps != expected: + raise SystemExit(f"{workload} egress targets differ: {destination_apps}") + + wrong_namespace = copy.deepcopy(migration) + wrong_namespace["previewStack"]["tenantAssociationMigration"]["account"]["targetNamespace"] = "pr-999" + require_failure("wrong-namespace", wrong_namespace, "targetNamespace must match") + mutable_image = copy.deepcopy(migration) + mutable_image["previewStack"]["tenantAssociationMigration"]["gameDesign"]["image"] = "game-design:latest" + require_failure("mutable-image", mutable_image, "image must end in @sha256") + no_policy = copy.deepcopy(migration) + no_policy["previewStack"]["networkPolicies"] = {"enabled": False} + require_failure("missing-policy", no_policy, "networkPolicies.enabled=true") + print("tenant association Helm Job render contract passed") +PY diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index fdda9794e1..dd6e965c49 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -1372,6 +1372,8 @@ for workload in publication_workloads: f"object.metadata.name == 'firemud-grpc-{workload}' && " f"object.metadata.labels['firemud.dev/role'] == 'grpc-publication-{workload}'" ) in controller_grants +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert f"firemud-grpc-{migrator_identity}" not in controller_grants def publication_projection_is_allowed(operation, namespace, name, role=None): @@ -1433,6 +1435,10 @@ assert "object.metadata.name == 'dev-grpc-game-session-service'" in cert_manager assert cert_manager_expression.count( "request.name == 'firemud-grpc-game-design-baseline-migrator'" ) == 1, "migrator Secret admission match must be a single exact branch" +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert cert_manager_expression.count( + f"request.name == 'firemud-grpc-{migrator_identity}'" + ) == 1, f"{migrator_identity} Secret admission match must be a single exact branch" for migration_secret_gate in ( "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')", "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", @@ -1444,6 +1450,34 @@ for migration_secret_gate in ( "ref.name == request.namespace + '-grpc-game-design-baseline-migrator'", ): assert migration_secret_gate in cert_manager_expression, migration_secret_gate +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + for migration_secret_gate in ( + f"object.metadata.name == 'firemud-grpc-{migrator_identity}'", + "object.metadata.labels['firemud.dev/managed-by'] == 'tenant-association-migration'", + f"object.metadata.labels['firemud.dev/role'] == 'grpc-{migrator_identity}'", + "object.metadata.labels['firemud.dev/retention'] == 'ephemeral'", + f"object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-{migrator_identity}'", + "object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer'", + f"ref.name == request.namespace + '-grpc-{migrator_identity}'", + ): + assert migration_secret_gate in cert_manager_expression, migration_secret_gate + assert cert_manager_expression.count( + f"object.metadata.name == 'firemud-grpc-{migrator_identity}'" + ) == 1 + other_identity = ( + "account-tenant-migrator" + if migrator_identity == "game-design-tenant-migrator" + else "game-design-tenant-migrator" + ) + assert ( + f"object.metadata.name == 'firemud-grpc-{migrator_identity}' && " + f"object.spec.secretName == 'firemud-grpc-{other_identity}'" + ) not in cert_manager_expression + assert ( + f"object.metadata.name == 'firemud-grpc-{migrator_identity}' && " + "object.metadata.annotations['cert-manager.io/certificate-name'] == " + f"request.namespace + '-grpc-{other_identity}'" + ) not in cert_manager_expression assert "request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')" not in ( cert_manager_expression.split( "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", 1 @@ -1474,6 +1508,10 @@ assert "request.operation == 'DELETE'" in certificate_namespace_match assert "request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-" in certificate_namespace_match assert "request.name.startsWith(" in certificate_namespace_match assert "request.name == request.namespace + '-grpc-game-design-baseline-migrator'" in certificate_namespace_match +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert ( + f"request.name == request.namespace + '-grpc-{migrator_identity}'" + ) in certificate_namespace_match assert "request.operation != 'DELETE'" in certificate_namespace_match assert "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-" in certificate_namespace_match assert "object.metadata.name.startsWith(" in certificate_namespace_match @@ -1510,6 +1548,10 @@ assert "grpc-account-service" in certificate_match assert "grpc-game-session-service" in certificate_match assert "system:serviceaccount:firemud-system:firemud-standalone-certificate-writer" in certificate_match assert "object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator'" in certificate_match +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert ( + f"object.spec.secretName == 'firemud-grpc-{migrator_identity}'" + ) in certificate_match assert "object.metadata.name == 'firemud-grpc-tls'" not in certificate_match certificate_expressions = [ @@ -1526,6 +1568,8 @@ assert "firemud-grpc-tls" not in controller_non_delete_expression assert "'grpc'" not in controller_non_delete_expression assert "grpc-publication-" in controller_non_delete_expression assert "grpc-account-service" in controller_non_delete_expression +for migrator_identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + assert f"{migrator_identity}" not in controller_certificate_expression assert "has(object.spec.isCA)" in controller_non_delete_expression assert "object.spec.isCA == false" in controller_non_delete_expression assert "(!has(object.spec.commonName) || object.spec.commonName == '')" in controller_non_delete_expression diff --git a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh index e5adfc7ffd..bda51a8b91 100755 --- a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh +++ b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh @@ -57,7 +57,7 @@ case " $* " in pr-42-tcp-proxy-bridge) printf '%s' '{"metadata":{"name":"pr-42-tcp-proxy-bridge"},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' ;; - firemud-grpc-game-design-baseline-migrator) + firemud-grpc-game-design-baseline-migrator|firemud-grpc-account-tenant-migrator|firemud-grpc-game-design-tenant-migrator) if [[ -z "${FAKE_KUBECTL_SECRET_JSON:-}" ]]; then echo "migrator Secret fixture is required" >&2 exit 2 @@ -230,6 +230,68 @@ grep -Fq 'did not become key-complete' "$TEMP_DIR/incomplete.err" || { exit 1 } +for migrator_identity in account-tenant-migrator game-design-tenant-migrator; do + runtime_calls_start="$(wc -l <"$STATE_DIR/calls")" + PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + "$SCRIPT" "--$migrator_identity" dev >"$TEMP_DIR/$migrator_identity-issued.out" + runtime_calls="$(tail -n +$((runtime_calls_start + 1)) "$STATE_DIR/calls")" + if grep -Fq 'get secret' <<<"$runtime_calls"; then + echo "$migrator_identity certificate writer read a Secret" >&2 + exit 1 + fi + cp "$STATE_DIR/applied.yaml" "$TEMP_DIR/$migrator_identity-certificate.yaml" +done +python3 - "$TEMP_DIR" <<'PY' +import sys +from pathlib import Path + +import yaml + +root = Path(sys.argv[1]) +for identity in ("account-tenant-migrator", "game-design-tenant-migrator"): + document = yaml.safe_load((root / f"{identity}-certificate.yaml").read_text(encoding="utf-8")) + if document.get("kind") != "Certificate": + raise SystemExit(f"{identity} opt-in did not apply one Certificate") + namespace = document["metadata"].get("namespace") + if namespace != "dev" or document["metadata"].get("name") != f"{namespace}-grpc-{identity}": + raise SystemExit(f"{identity} Certificate name is not stable and namespace-bound") + spec = document["spec"] + if spec.get("secretName") != f"firemud-grpc-{identity}": + raise SystemExit(f"{identity} Certificate does not use its dedicated Secret") + if spec.get("uris") != [f"spiffe://firemud/ns/{namespace}/sa/{identity}"]: + raise SystemExit(f"{identity} Certificate URI SAN is not exact") + if "dnsNames" in spec or spec.get("usages") != ["digital signature", "key encipherment", "client auth"]: + raise SystemExit(f"{identity} Certificate is not URI-only clientAuth") + if spec.get("issuerRef") != { + "name": "firemud-ca-issuer", + "kind": "ClusterIssuer", + "group": "cert-manager.io", + }: + raise SystemExit(f"{identity} Certificate must use the internal ClusterIssuer") + if spec.get("secretTemplate", {}).get("metadata", {}).get("labels") != { + "firemud.dev/managed-by": "tenant-association-migration", + "firemud.dev/role": f"grpc-{identity}", + "firemud.dev/retention": "ephemeral", + }: + raise SystemExit(f"{identity} Secret labels do not match the tenant-migration profile") +PY + +PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + "$SCRIPT" --account-tenant-migrator dev >"$TEMP_DIR/account-tenant-migrator-repeat.out" +python3 - "$TEMP_DIR/account-tenant-migrator-certificate.yaml" "$STATE_DIR/applied.yaml" <<'PY' +import sys +from pathlib import Path + +import yaml + +first = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) +second = yaml.safe_load(Path(sys.argv[2]).read_text(encoding="utf-8")) +if first["metadata"]["name"] != second["metadata"]["name"]: + raise SystemExit("tenant migrator Certificate name changed on repeat issuance") +if first["spec"] != second["spec"]: + raise SystemExit("tenant migrator Certificate spec changed on repeat issuance") +PY + runtime_calls_start="$(wc -l <"$STATE_DIR/calls")" PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ "$SCRIPT" --migrator dev >"$TEMP_DIR/migrator-issued.out" @@ -298,6 +360,31 @@ if grep -Fq 'tls.key' "$TEMP_DIR/migrator-verified.out"; then exit 1 fi +for migrator_identity in account-tenant-migrator game-design-tenant-migrator; do + openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/$migrator_identity.key" \ + -out "$TEMP_DIR/$migrator_identity.csr" -subj "/CN=$migrator_identity" \ + -addext "subjectAltName=URI:spiffe://firemud/ns/dev/sa/$migrator_identity" \ + -addext 'extendedKeyUsage=clientAuth' \ + -addext 'keyUsage=digitalSignature,keyEncipherment' >/dev/null 2>&1 + openssl x509 -req -in "$TEMP_DIR/$migrator_identity.csr" -CA "$TEMP_DIR/ca.crt" \ + -CAkey "$TEMP_DIR/ca.key" -CAcreateserial -days 1 -copy_extensions copy \ + -out "$TEMP_DIR/$migrator_identity.crt" >/dev/null 2>&1 + jq -n \ + --arg name "firemud-grpc-$migrator_identity" \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/$migrator_identity.crt")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":"c2VjcmV0","ca.crt":$ca}}' \ + >"$TEMP_DIR/$migrator_identity-secret.json" + PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/$migrator_identity-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" "--verify-$migrator_identity" dev >"$TEMP_DIR/$migrator_identity-verified.out" + grep -Fq "uri-san=spiffe://firemud/ns/dev/sa/$migrator_identity" \ + "$TEMP_DIR/$migrator_identity-verified.out" + grep -Fq 'namespace-trust-match=true' "$TEMP_DIR/$migrator_identity-verified.out" + grep -Fq 'client-auth-only=true' "$TEMP_DIR/$migrator_identity-verified.out" +done + openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-leaf.key" \ -out "$TEMP_DIR/wrong-leaf.csr" -subj '/CN=wrong migrator' \ -addext 'subjectAltName=URI:spiffe://firemud/ns/dev/sa/game-design-service' \ @@ -323,6 +410,24 @@ fi grep -Fq 'does not contain only the exact migrator SPIFFE URI SAN' \ "$TEMP_DIR/wrong-migrator.err" +jq -n \ + --arg name firemud-grpc-account-tenant-migrator \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/wrong-leaf.crt")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":"c2VjcmV0","ca.crt":$ca}}' \ + >"$TEMP_DIR/wrong-account-tenant-migrator-secret.json" +if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/wrong-account-tenant-migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" --verify-account-tenant-migrator dev \ + >"$TEMP_DIR/wrong-account-tenant-migrator.out" \ + 2>"$TEMP_DIR/wrong-account-tenant-migrator.err"; then + echo "Account tenant migrator verifier accepted another workload identity" >&2 + exit 1 +fi +grep -Fq 'does not contain only the exact migrator SPIFFE URI SAN' \ + "$TEMP_DIR/wrong-account-tenant-migrator.err" + openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-ca.key" \ -out "$TEMP_DIR/wrong-ca.crt" -subj '/CN=Untrusted test CA' -days 1 >/dev/null 2>&1 if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ diff --git a/dev-tools/tests/trust-bootstrap-issuance-contract.sh b/dev-tools/tests/trust-bootstrap-issuance-contract.sh index 0662af4c22..48d1693fcd 100755 --- a/dev-tools/tests/trust-bootstrap-issuance-contract.sh +++ b/dev-tools/tests/trust-bootstrap-issuance-contract.sh @@ -119,6 +119,16 @@ def check_contract(items: list[dict]) -> None: "object.spec == oldObject.spec", ): require(request, needle, "CertificateRequest boundary") + for identity in ( + "game-design-baseline-migrator", + "game-design-tenant-migrator", + "account-tenant-migrator", + ): + require( + request, + f"owner.name == request.namespace + '-grpc-{identity}'", + f"CertificateRequest {identity} ownership", + ) owner_validation = actual_policies["firemud-trust-bootstrap-certificaterequest"]["spec"][ "validations" ][1]["expression"].rstrip() @@ -134,6 +144,16 @@ def check_contract(items: list[dict]) -> None: "owner.kind == 'Certificate'", ): require(request_subresources, needle, "CertificateRequest subresource boundary") + for identity in ( + "game-design-baseline-migrator", + "game-design-tenant-migrator", + "account-tenant-migrator", + ): + require( + request_subresources, + f"owner.name == request.namespace + '-grpc-{identity}'", + f"CertificateRequest subresource {identity} ownership", + ) subresource_rules = actual_policies["firemud-trust-bootstrap-certificaterequest-subresources"][ "spec" ]["matchConstraints"]["resourceRules"] @@ -209,7 +229,7 @@ def check_contract(items: list[dict]) -> None: fail("Certificate status denial message does not describe the allowed callers") require( certificate_validation, - "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$", + "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator))$", "standalone Certificate validation", ) for needle in ( @@ -247,6 +267,42 @@ def check_contract(items: list[dict]) -> None: "system:serviceaccount:firemud-system:firemud-standalone-certificate-writer", "standalone Certificate validation", ) + for identity in ("game-design-tenant-migrator", "account-tenant-migrator"): + require( + certificate_validation, + f"object.metadata.name.endsWith('-grpc-{identity}')", + f"standalone {identity} Certificate name", + ) + require( + certificate_validation, + f"object.spec.secretName == 'firemud-grpc-{identity}'", + f"standalone {identity} Certificate Secret", + ) + require( + certificate_validation, + "object.spec.issuerRef.name == 'firemud-ca-issuer'", + f"standalone {identity} Certificate issuer", + ) + require( + certificate_validation, + f"'firemud.dev/managed-by': 'tenant-association-migration'", + f"standalone {identity} Secret manager", + ) + require( + certificate_validation, + f"'firemud.dev/role': 'grpc-{identity}'", + f"standalone {identity} Secret role", + ) + require( + certificate_validation, + f"object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/{identity}']", + f"standalone {identity} Certificate URI", + ) + require( + certificate_validation, + "object.spec.usages == ['digital signature', 'key encipherment', 'client auth']", + f"standalone {identity} Certificate usages", + ) issuer = expressions(actual_policies["firemud-trust-bootstrap-ca-issuers"]) issuer_match = actual_policies["firemud-trust-bootstrap-ca-issuers"]["spec"][ @@ -330,5 +386,49 @@ except AssertionError: else: fail("negative mutation changing the CA issuer binding from Deny was accepted") +for identity, other_identity in ( + ("game-design-tenant-migrator", "account-tenant-migrator"), + ("account-tenant-migrator", "game-design-tenant-migrator"), +): + mutation = copy.deepcopy(documents) + mutation_policy = next( + item + for item in mutation + if item.get("metadata", {}).get("name") == "firemud-trust-bootstrap-certificate" + ) + mutation_policy["spec"]["validations"][0]["expression"] = mutation_policy["spec"][ + "validations" + ][0]["expression"].replace( + f"object.spec.secretName == 'firemud-grpc-{identity}'", + f"object.spec.secretName == 'firemud-grpc-{other_identity}'", + 1, + ) + try: + check_contract(mutation) + except AssertionError: + pass + else: + fail(f"negative mutation swapping the {identity} Secret was accepted") + + mutation = copy.deepcopy(documents) + mutation_policy = next( + item + for item in mutation + if item.get("metadata", {}).get("name") == "firemud-trust-bootstrap-certificate" + ) + mutation_policy["spec"]["validations"][0]["expression"] = mutation_policy["spec"][ + "validations" + ][0]["expression"].replace( + f"object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/{identity}']", + f"object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/{other_identity}']", + 1, + ) + try: + check_contract(mutation) + except AssertionError: + pass + else: + fail(f"negative mutation swapping the {identity} URI was accepted") + print(f"trust-bootstrap issuance contract: {len(documents)} documents, fail-closed bindings verified") PY diff --git a/k8s/helm/firemud/templates/network-policies.yaml b/k8s/helm/firemud/templates/network-policies.yaml index 1ad9aec462..e1a35a8893 100644 --- a/k8s/helm/firemud/templates/network-policies.yaml +++ b/k8s/helm/firemud/templates/network-policies.yaml @@ -27,6 +27,9 @@ {{- $gatewayWsTlsTargetPort = required "previewStack.gatewayWsTls.targetPort is required when Gateway WebSocket TLS is enabled" $gatewayWsTls.targetPort }} {{- end }} {{- $entityDigestBaselineMigration := .Values.previewStack.entityDigestBaselineMigration | default (dict) }} +{{- $tenantAssociationMigration := .Values.previewStack.tenantAssociationMigration | default (dict) }} +{{- $gameDesignTenantMigration := $tenantAssociationMigration.gameDesign | default (dict) }} +{{- $accountTenantMigration := $tenantAssociationMigration.account | default (dict) }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -430,4 +433,89 @@ spec: - protocol: TCP port: 6565 {{- end }} +{{- if $gameDesignTenantMigration.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: game-design-tenant-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: game-design-tenant-migrator + firemud.dev/workload: game-design-tenant-migrator + policyTypes: + - Ingress + - Egress + ingress: [] + egress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + - to: + - podSelector: + matchLabels: + app: postgres + ports: + - protocol: TCP + port: 5432 +{{- end }} +{{- if $accountTenantMigration.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: account-tenant-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: account-tenant-migrator + firemud.dev/workload: account-tenant-migrator + policyTypes: + - Ingress + - Egress + ingress: [] + egress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + - to: + - podSelector: + matchLabels: + app: postgres + ports: + - protocol: TCP + port: 5432 + {{- if eq $accountTenantMigration.mode "import" }} + - to: + - podSelector: + matchLabels: + app: game-design-service + ports: + - protocol: TCP + port: 6565 + {{- end }} +{{- end }} {{- end }} diff --git a/k8s/helm/firemud/templates/tenant-association-account-job.yaml b/k8s/helm/firemud/templates/tenant-association-account-job.yaml new file mode 100644 index 0000000000..d7cc2be8a0 --- /dev/null +++ b/k8s/helm/firemud/templates/tenant-association-account-job.yaml @@ -0,0 +1,185 @@ +{{- $migration := .Values.previewStack.tenantAssociationMigration | default (dict) -}} +{{- $job := $migration.account | default (dict) -}} +{{- if ($job.enabled | default false) -}} +{{- if not .Values.previewStack.enabled -}} +{{- fail "Account tenant association import requires previewStack.enabled=true" -}} +{{- end -}} +{{- $networkPolicies := .Values.previewStack.networkPolicies | default (dict) -}} +{{- if not ($networkPolicies.enabled | default false) -}} +{{- fail "Account tenant association import requires previewStack.networkPolicies.enabled=true" -}} +{{- end -}} +{{- $namespace := required "Account tenant association import requires targetNamespace" $job.targetNamespace -}} +{{- if ne $namespace .Release.Namespace -}} +{{- fail "Account tenant association targetNamespace must match the Helm release namespace" -}} +{{- end -}} +{{- $mode := required "Account tenant association import requires mode" $job.mode -}} +{{- if not (has $mode (list "evidence" "import")) -}} +{{- fail "Account tenant association mode must be evidence or import" -}} +{{- end -}} +{{- $runId := required "Account tenant association import requires runId" $job.runId -}} +{{- if or (gt (len $runId) 32) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $runId)) -}} +{{- fail "Account tenant association runId must be a DNS label of at most 32 characters" -}} +{{- end -}} +{{- $image := required "Account tenant association import requires an immutable image" $job.image -}} +{{- if not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $image) -}} +{{- fail "Account tenant association image must end in @sha256:<64 lowercase hex characters>" -}} +{{- end -}} +{{- $tenantId := required "Account tenant association import requires legacyTenantId" $job.legacyTenantId | toString -}} +{{- if not (regexMatch "^[1-9][0-9]*$" $tenantId) -}} +{{- fail "Account tenant association legacyTenantId must be canonical positive decimal" -}} +{{- end -}} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: account-tenant-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +automountServiceAccountToken: false +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ printf "account-tenant-%s-%s" $mode $runId | quote }} + labels: +{{ include "firemud.commonLabels" . | indent 4 }} + annotations: + firemud.dev/migration-mode: {{ $mode | quote }} + firemud.dev/migration-run-id: {{ $runId | quote }} +spec: + completions: 1 + parallelism: 1 + backoffLimit: 0 + activeDeadlineSeconds: 900 + template: + metadata: + labels: + app: account-tenant-migrator + firemud.dev/workload: account-tenant-migrator + spec: + serviceAccountName: account-tenant-migrator + automountServiceAccountToken: false + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + seccompProfile: + type: RuntimeDefault + {{- with .Values.previewStack.imagePullSecrets }} + imagePullSecrets: + {{- range $secret := . }} + {{- if kindIs "string" $secret }} + - name: {{ $secret }} + {{- else }} +{{ toYaml (list $secret) | indent 8 }} + {{- end }} + {{- end }} + {{- end }} + containers: + - name: migration + image: {{ $image | quote }} + imagePullPolicy: IfNotPresent + command: [java] + args: + - -jar + - /app/app.jar + - --spring.main.web-application-type=none + - --spring.grpc.server.enabled=false + - --firemud.account-tenant-migration.enabled=true + env: + - name: SPRING_FLYWAY_TABLE + value: flyway_schema_history_account_service + - name: SERVICE_SCHEMA + value: account_service + - name: FIREMUD_POSTGRES_HOST + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_HOST + - name: FIREMUD_POSTGRES_PORT + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_PORT + - name: FIREMUD_POSTGRES_DB + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_DB + - name: FIREMUD_POSTGRES_USER + valueFrom: + secretKeyRef: + name: firemud-secret + key: FIREMUD_POSTGRES_USER + - name: FIREMUD_POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: firemud-secret + key: FIREMUD_POSTGRES_PASSWORD + - name: FIREMUD_REDIS_ENABLED + value: "false" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_GRPC_CERT_CHAIN_PATH + value: /tls/tls.crt + - name: FIREMUD_GRPC_PRIVATE_KEY_PATH + value: /tls/tls.key + - name: FIREMUD_GRPC_CA_CERT_PATH + value: /grpc-trust/ca.crt + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_ENABLED + value: "true" + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_MODE + value: {{ $mode | quote }} + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_LEGACY_TENANT_ID + value: {{ $tenantId | quote }} + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_TARGET_NAMESPACE + value: {{ $namespace | quote }} + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_ACCOUNT_TENANT_MIGRATION_POD_SERVICE_ACCOUNT + valueFrom: + fieldRef: + fieldPath: spec.serviceAccountName + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsUser: 1000 + runAsGroup: 1000 + capabilities: + drop: [ALL] + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 1 + memory: 768Mi + volumeMounts: + - name: grpc-identity + mountPath: /tls + readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true + - name: migration-tmp + mountPath: /tmp + volumes: + - name: grpc-identity + secret: + secretName: firemud-grpc-account-tenant-migrator + - name: grpc-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt + - name: migration-tmp + emptyDir: + sizeLimit: 64Mi +{{- end -}} diff --git a/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml b/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml new file mode 100644 index 0000000000..447385a318 --- /dev/null +++ b/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml @@ -0,0 +1,210 @@ +{{- $migration := .Values.previewStack.tenantAssociationMigration | default (dict) -}} +{{- $job := $migration.gameDesign | default (dict) -}} +{{- if ($job.enabled | default false) -}} +{{- if not .Values.previewStack.enabled -}} +{{- fail "Game Design tenant association migration requires previewStack.enabled=true" -}} +{{- end -}} +{{- $networkPolicies := .Values.previewStack.networkPolicies | default (dict) -}} +{{- if not ($networkPolicies.enabled | default false) -}} +{{- fail "Game Design tenant association migration requires previewStack.networkPolicies.enabled=true" -}} +{{- end -}} +{{- $namespace := required "Game Design tenant association migration requires targetNamespace" $job.targetNamespace -}} +{{- if ne $namespace .Release.Namespace -}} +{{- fail "Game Design tenant association targetNamespace must match the Helm release namespace" -}} +{{- end -}} +{{- $mode := required "Game Design tenant association migration requires mode" $job.mode -}} +{{- if not (has $mode (list "preflight" "apply")) -}} +{{- fail "Game Design tenant association mode must be preflight or apply" -}} +{{- end -}} +{{- $runId := required "Game Design tenant association migration requires runId" $job.runId -}} +{{- if or (gt (len $runId) 32) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $runId)) -}} +{{- fail "Game Design tenant association runId must be a DNS label of at most 32 characters" -}} +{{- end -}} +{{- $image := required "Game Design tenant association migration requires an immutable image" $job.image -}} +{{- if not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $image) -}} +{{- fail "Game Design tenant association image must end in @sha256:<64 lowercase hex characters>" -}} +{{- end -}} +{{- $manifestSecret := required "Game Design tenant association migration requires signedManifestSecretName" $job.signedManifestSecretName -}} +{{- $keysSecret := required "Game Design tenant association migration requires trustedKeysSecretName" $job.trustedKeysSecretName -}} +{{- if or (not (regexMatch "^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$" $manifestSecret)) (not (regexMatch "^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$" $keysSecret)) -}} +{{- fail "Game Design tenant association evidence Secret names must be DNS names" -}} +{{- end -}} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: game-design-tenant-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +automountServiceAccountToken: false +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ printf "game-design-tenant-%s-%s" $mode $runId | quote }} + labels: +{{ include "firemud.commonLabels" . | indent 4 }} + annotations: + firemud.dev/migration-mode: {{ $mode | quote }} + firemud.dev/migration-run-id: {{ $runId | quote }} +spec: + completions: 1 + parallelism: 1 + backoffLimit: 0 + activeDeadlineSeconds: 900 + template: + metadata: + labels: + app: game-design-tenant-migrator + firemud.dev/workload: game-design-tenant-migrator + spec: + serviceAccountName: game-design-tenant-migrator + automountServiceAccountToken: false + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + seccompProfile: + type: RuntimeDefault + {{- with .Values.previewStack.imagePullSecrets }} + imagePullSecrets: + {{- range $secret := . }} + {{- if kindIs "string" $secret }} + - name: {{ $secret }} + {{- else }} +{{ toYaml (list $secret) | indent 8 }} + {{- end }} + {{- end }} + {{- end }} + containers: + - name: migration + image: {{ $image | quote }} + imagePullPolicy: IfNotPresent + command: [java] + args: + - -jar + - /app/app.jar + - --spring.main.web-application-type=none + - --spring.grpc.server.enabled=false + - --firemud.tenant-association-migration.enabled=true + env: + - name: SPRING_FLYWAY_TABLE + value: flyway_schema_history_game_design_service + - name: SERVICE_SCHEMA + value: game_design_service + - name: FIREMUD_POSTGRES_HOST + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_HOST + - name: FIREMUD_POSTGRES_PORT + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_PORT + - name: FIREMUD_POSTGRES_DB + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_DB + - name: FIREMUD_POSTGRES_USER + valueFrom: + secretKeyRef: + name: firemud-secret + key: FIREMUD_POSTGRES_USER + - name: FIREMUD_POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: firemud-secret + key: FIREMUD_POSTGRES_PASSWORD + - name: FIREMUD_REDIS_ENABLED + value: "false" + - name: FIREMUD_TEMPORAL_ENABLED + value: "false" + - name: FIREMUD_TEMPORAL_WORKERS_ENABLED + value: "false" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_GRPC_CERT_CHAIN_PATH + value: /tls/tls.crt + - name: FIREMUD_GRPC_PRIVATE_KEY_PATH + value: /tls/tls.key + - name: FIREMUD_GRPC_CA_CERT_PATH + value: /grpc-trust/ca.crt + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED + value: "true" + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_MODE + value: {{ $mode | quote }} + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_TARGET_NAMESPACE + value: {{ $namespace | quote }} + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_POD_SERVICE_ACCOUNT + valueFrom: + fieldRef: + fieldPath: spec.serviceAccountName + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_SIGNED_MANIFEST_PATH + value: /migration/manifest.json + - name: FIREMUD_TENANT_ASSOCIATION_MIGRATION_OWNER_PUBLIC_KEYS_PATH + value: /migration-keys/owner-public-keys.json + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsUser: 1000 + runAsGroup: 1000 + capabilities: + drop: [ALL] + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 1 + memory: 768Mi + volumeMounts: + - name: grpc-identity + mountPath: /tls + readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true + - name: signed-manifest + mountPath: /migration + readOnly: true + - name: trusted-keys + mountPath: /migration-keys + readOnly: true + - name: migration-tmp + mountPath: /tmp + volumes: + - name: grpc-identity + secret: + secretName: firemud-grpc-game-design-tenant-migrator + - name: grpc-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt + - name: signed-manifest + secret: + secretName: {{ $manifestSecret | quote }} + items: + - key: manifest.json + path: manifest.json + - name: trusted-keys + secret: + secretName: {{ $keysSecret | quote }} + items: + - key: owner-public-keys.json + path: owner-public-keys.json + - name: migration-tmp + emptyDir: + sizeLimit: 64Mi +{{- end -}} diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index 468a69541b..8c5dcbdafb 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -20,6 +20,24 @@ previewStack: # A dedicated identity Secret must be provisioned by the environment's # trust owner. The chart never falls back to a service certificate. grpcIdentitySecretName: firemud-grpc-game-design-baseline-migrator + tenantAssociationMigration: + # Operator-invoked Jobs only; ordinary chart releases never run them. + # Evidence Secrets and immutable images are supplied by the operator. + gameDesign: + enabled: false + mode: "" + targetNamespace: "" + runId: "" + image: "" + signedManifestSecretName: "" + trustedKeysSecretName: "" + account: + enabled: false + mode: "" + targetNamespace: "" + runId: "" + image: "" + legacyTenantId: "" # Hosted environments use the HostedEnvironmentIdentity controller for # certificate identity. Local installs retain standalone cert-manager mode. certificateIdentity: diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index 35783a9c55..7f6d4d0e2c 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -153,20 +153,22 @@ spec: request.namespace.matches('^(dev|dev-identity|pr-[1-9][0-9]{0,50}|pr-[1-9][0-9]{0,50}-identity)$')) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - request.name == 'firemud-grpc-game-design-baseline-migrator') || + (request.name == 'firemud-grpc-game-design-baseline-migrator' || + request.name == 'firemud-grpc-game-design-tenant-migrator' || + request.name == 'firemud-grpc-account-tenant-migrator')) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')) || ((request.namespace in ['dev', 'dev-identity'] || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || request.name == 'firemud-grpc-game-design-baseline-migrator' || + (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || request.name == 'firemud-grpc-game-design-baseline-migrator' || request.name == 'firemud-grpc-game-design-tenant-migrator' || request.name == 'firemud-grpc-account-tenant-migrator' || request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') || request.name == 'firemud-grpc-tls-previous' || request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))-previous$'))) || (request.operation != 'DELETE' && - (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' || + (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' || object.metadata.name == 'firemud-grpc-game-design-tenant-migrator' || object.metadata.name == 'firemud-grpc-account-tenant-migrator' || object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') || object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || object.metadata.name == 'firemud-grpc-tls-previous' || @@ -182,9 +184,11 @@ spec: (request.namespace in ['dev', 'dev-identity'] || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(firemud-grpc-tls|firemud-grpc-tls-previous|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)-previous|firemud-grpc-game-design-baseline-migrator|(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))(-previous)?)$') && + request.name.matches('^(firemud-grpc-tls|firemud-grpc-tls-previous|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)-previous|firemud-grpc-game-design-baseline-migrator|firemud-grpc-game-design-tenant-migrator|firemud-grpc-account-tenant-migrator|(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))(-previous)?)$') && (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-tls-previous' || request.name == 'firemud-grpc-game-design-baseline-migrator' || + request.name == 'firemud-grpc-game-design-tenant-migrator' || + request.name == 'firemud-grpc-account-tenant-migrator' || request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)(-previous)?$') || request.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : @@ -261,6 +265,46 @@ spec: ref.apiVersion == 'cert-manager.io/v1' && ref.kind == 'Certificate' && ref.name == request.namespace + '-grpc-game-design-baseline-migrator'))) || + (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.type == 'kubernetes.io/tls' && + object.metadata.name == 'firemud-grpc-game-design-tenant-migrator' && + has(object.metadata.labels) && + object.metadata.labels['firemud.dev/managed-by'] == 'tenant-association-migration' && + object.metadata.labels['firemud.dev/role'] == 'grpc-game-design-tenant-migrator' && + object.metadata.labels['firemud.dev/retention'] == 'ephemeral' && + has(object.metadata.annotations) && + object.metadata.annotations['firemud.dev/provenance'] == 'cert-manager' && + object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-game-design-tenant-migrator' && + object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer' && + object.metadata.annotations['cert-manager.io/issuer-kind'] == 'ClusterIssuer' && + object.metadata.annotations['cert-manager.io/issuer-group'] == 'cert-manager.io' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-game-design-tenant-migrator'))) || + (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.type == 'kubernetes.io/tls' && + object.metadata.name == 'firemud-grpc-account-tenant-migrator' && + has(object.metadata.labels) && + object.metadata.labels['firemud.dev/managed-by'] == 'tenant-association-migration' && + object.metadata.labels['firemud.dev/role'] == 'grpc-account-tenant-migrator' && + object.metadata.labels['firemud.dev/retention'] == 'ephemeral' && + has(object.metadata.annotations) && + object.metadata.annotations['firemud.dev/provenance'] == 'cert-manager' && + object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-account-tenant-migrator' && + object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer' && + object.metadata.annotations['cert-manager.io/issuer-kind'] == 'ClusterIssuer' && + object.metadata.annotations['cert-manager.io/issuer-group'] == 'cert-manager.io' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-account-tenant-migrator'))) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.operation in ['CREATE', 'UPDATE'] && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$') && @@ -319,6 +363,20 @@ spec: ref.apiVersion == 'cert-manager.io/v1' && ref.kind == 'Certificate' && ref.name == request.namespace + '-grpc-game-design-baseline-migrator'))) || + (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.metadata.name == 'firemud-grpc-game-design-tenant-migrator' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-game-design-tenant-migrator'))) || + (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.metadata.name == 'firemud-grpc-account-tenant-migrator' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-account-tenant-migrator'))) || (request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$') && object.metadata.name != 'firemud-grpc-tls' && ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || @@ -360,7 +418,9 @@ spec: request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - request.name == request.namespace + '-grpc-game-design-baseline-migrator') || + (request.name == request.namespace + '-grpc-game-design-baseline-migrator' || + request.name == request.namespace + '-grpc-game-design-tenant-migrator' || + request.name == request.namespace + '-grpc-account-tenant-migrator')) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')) || (request.userInfo.groups.exists(group, group == 'system:masters') && @@ -391,6 +451,20 @@ spec: request.name == request.namespace + '-grpc-game-design-baseline-migrator' && object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator' && object.spec.issuerRef.name == 'firemud-ca-issuer') || + (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && + request.subResource == '' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == request.namespace + '-grpc-game-design-tenant-migrator' && + object.spec.secretName == 'firemud-grpc-game-design-tenant-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer') || + (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && + request.subResource == '' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == request.namespace + '-grpc-account-tenant-migrator' && + object.spec.secretName == 'firemud-grpc-account-tenant-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer') || (request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && request.subResource == '' && request.operation == 'DELETE' && diff --git a/k8s/trust-bootstrap/issuance-admission.yaml b/k8s/trust-bootstrap/issuance-admission.yaml index b273c80a6a..3fe8b335d2 100644 --- a/k8s/trust-bootstrap/issuance-admission.yaml +++ b/k8s/trust-bootstrap/issuance-admission.yaml @@ -59,7 +59,9 @@ spec: owner.blockOwnerDeletion == true && (owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - owner.name == request.namespace + '-grpc-game-design-baseline-migrator')))) + (owner.name == request.namespace + '-grpc-game-design-baseline-migrator' || + owner.name == request.namespace + '-grpc-game-design-tenant-migrator' || + owner.name == request.namespace + '-grpc-account-tenant-migrator')))) message: internal CertificateRequests must use the canonical ClusterIssuer and be owned by a canonical Certificate reason: Forbidden - expression: >- @@ -116,7 +118,9 @@ spec: owner.blockOwnerDeletion == true && (owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && - owner.name == request.namespace + '-grpc-game-design-baseline-migrator')))) + (owner.name == request.namespace + '-grpc-game-design-baseline-migrator' || + owner.name == request.namespace + '-grpc-game-design-tenant-migrator' || + owner.name == request.namespace + '-grpc-account-tenant-migrator')))) message: internal CertificateRequest approval and status may not alter its canonical spec or ownership reason: Forbidden @@ -153,24 +157,24 @@ spec: (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || ((oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'CREATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || ((object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'UPDATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || (object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')) || (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || (oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) validations: - expression: >- @@ -178,21 +182,21 @@ spec: (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$')) || + request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator))$')) || (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && (request.namespace == 'dev' || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$')) || + request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator))$')) || (request.operation != 'DELETE' && ((request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && (request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || object.metadata.name.contains('-grpc-')) && - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$') && + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator))$') && object.metadata.name.startsWith(request.namespace + '-') && has(object.spec.secretName) && ((object.metadata.name.contains('-grpc-') && - object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$')) || + object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator|game-design-tenant-migrator|account-tenant-migrator)$')) || (!object.metadata.name.contains('-grpc-') && object.spec.secretName == object.metadata.name)) && has(object.spec.isCA) && @@ -282,8 +286,40 @@ spec: object.spec.secretTemplate.metadata.annotations == { 'firemud.dev/provenance': 'cert-manager' } && - (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-design-baseline-migrator'] && + object.spec.usages == ['digital signature', 'key encipherment', 'client auth']) || + (object.metadata.name.endsWith('-grpc-game-design-tenant-migrator') && + object.spec.secretName == 'firemud-grpc-game-design-tenant-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + has(object.spec.secretTemplate) && + has(object.spec.secretTemplate.metadata) && + object.spec.secretTemplate.metadata.labels == { + 'firemud.dev/managed-by': 'tenant-association-migration', + 'firemud.dev/role': 'grpc-game-design-tenant-migrator', + 'firemud.dev/retention': 'ephemeral' + } && + object.spec.secretTemplate.metadata.annotations == { + 'firemud.dev/provenance': 'cert-manager' + } && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-design-tenant-migrator'] && + object.spec.usages == ['digital signature', 'key encipherment', 'client auth']) || + (object.metadata.name.endsWith('-grpc-account-tenant-migrator') && + object.spec.secretName == 'firemud-grpc-account-tenant-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + has(object.spec.secretTemplate) && + has(object.spec.secretTemplate.metadata) && + object.spec.secretTemplate.metadata.labels == { + 'firemud.dev/managed-by': 'tenant-association-migration', + 'firemud.dev/role': 'grpc-account-tenant-migrator', + 'firemud.dev/retention': 'ephemeral' + } && + object.spec.secretTemplate.metadata.annotations == { + 'firemud.dev/provenance': 'cert-manager' + } && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/account-tenant-migrator'] && object.spec.usages == ['digital signature', 'key encipherment', 'client auth']))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java index d8f2489f4e..945f47e64e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java @@ -44,15 +44,12 @@ public void run(ApplicationArguments args) throws Exception { String podNamespace = required("firemud.account-tenant-migration.pod-namespace"); String targetNamespace = required("firemud.account-tenant-migration.target-namespace"); if (!podNamespace.equals(targetNamespace) - || !"account-service" + || !"account-tenant-migrator" .equals(required("firemud.account-tenant-migration.pod-service-account"))) { throw new IllegalStateException("Account tenant migration Job has the wrong workload scope"); } GrpcPeerIdentity identity = verifiedWorkloadIdentity(); - if (!identity.isService("account-service") || !identity.isInNamespace(podNamespace)) { - throw new IllegalStateException( - "Account tenant migration certificate has the wrong identity"); - } + requireJobIdentity(podNamespace, identity); long legacyTenantId = Long.parseLong(required("firemud.account-tenant-migration.legacy-tenant-id")); if (legacyTenantId <= 0) { @@ -80,6 +77,15 @@ public void run(ApplicationArguments args) throws Exception { } } + static void requireJobIdentity(String podNamespace, GrpcPeerIdentity identity) { + if (identity == null + || !identity.isService("account-tenant-migrator") + || !identity.isInNamespace(podNamespace)) { + throw new IllegalStateException( + "Account tenant migration certificate has the wrong identity"); + } + } + private GrpcPeerIdentity verifiedWorkloadIdentity() throws Exception { Path certificatePath = Path.of(required("FIREMUD_GRPC_CERT_CHAIN_PATH")); X509Certificate leaf; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java index a9d450afe4..9dc8228ba4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Base64; +import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; @@ -41,6 +42,7 @@ void exactRetainedSourceAndApprovedOwnerReadAreRequiredForImmutableImport() { .dataSource(dataSource) .schemas(SCHEMA) .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) .locations("classpath:db/migration") .target("25") .load() @@ -66,6 +68,7 @@ void exactRetainedSourceAndApprovedOwnerReadAreRequiredForImmutableImport() { .dataSource(dataSource) .schemas(SCHEMA) .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) .locations("classpath:db/migration") .load() .migrate(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java new file mode 100644 index 0000000000..7bc963307c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java @@ -0,0 +1,35 @@ +package net.firedevops.firemud.accountservice.maintenance; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class LegacyTenantAssociationImportJobRunnerTest { + @Test + void acceptsOnlyExactDedicatedMigratorCertificate() { + assertThatCode( + () -> + LegacyTenantAssociationImportJobRunner.requireJobIdentity( + "dev", peer("dev", "account-tenant-migrator"))) + .doesNotThrowAnyException(); + for (GrpcPeerIdentity wrong : + new GrpcPeerIdentity[] { + null, + peer("dev", "account-service"), + peer("pr-12", "account-tenant-migrator"), + peer("dev", "game-design-tenant-migrator") + }) { + assertThatThrownBy( + () -> LegacyTenantAssociationImportJobRunner.requireJobIdentity("dev", wrong)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("wrong identity"); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java index 3d15d9f402..1a596507b4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java @@ -28,10 +28,12 @@ public record GrpcPeerIdentity(String uri, String namespace, String service) { public static final Set ALLOWED_SERVICE_NAMES = Set.of( "account-service", + "account-tenant-migrator", "automation-scripting-service", "entity-management-service", "game-design-baseline-migrator", "game-design-service", + "game-design-tenant-migrator", "game-logic-service", "game-session-service", "logging-admin-service", diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java index cc30881086..ed0d651d6d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java @@ -39,6 +39,19 @@ void extractsDedicatedEntityBaselineMigratorIdentity() throws Exception { .containsExactly(uri, "firemud", "game-design-baseline-migrator"); } + @Test + void extractsOnlyTheTwoDedicatedTenantMigratorIdentityNames() throws Exception { + for (String service : List.of("account-tenant-migrator", "game-design-tenant-migrator")) { + String uri = "spiffe://firemud/ns/firemud/sa/" + service; + assertThat(GrpcPeerIdentity.fromSslSession(sessionWithUriSans(uri))) + .get() + .extracting(GrpcPeerIdentity::uri, GrpcPeerIdentity::namespace, GrpcPeerIdentity::service) + .containsExactly(uri, "firemud", service); + } + assertThat(GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/tenant-migrator")) + .isEmpty(); + } + @Test void normalizesCanonicalEquivalentUriSanBeforeValidatingWorkloadIdentity() { assertThat(GrpcPeerIdentity.parseUri("spiffe://FIREMUD/ns/%66iremud/sa/game-%64esign-service")) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java index 1d5e4d88df..fd67935402 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java @@ -4,9 +4,13 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; import java.util.Map; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService; import org.slf4j.Logger; @@ -56,6 +60,7 @@ public void run(ApplicationArguments args) throws Exception { required("firemud.tenant-association-migration.pod-service-account"))) { throw new IllegalStateException("tenant migration Job has the wrong workload scope"); } + requireJobIdentity(podNamespace, verifiedWorkloadIdentity()); Path manifestPath = Path.of(required("firemud.tenant-association-migration.signed-manifest-path")); Path publicKeysPath = @@ -94,6 +99,25 @@ public void run(ApplicationArguments args) throws Exception { } } + static void requireJobIdentity(String podNamespace, GrpcPeerIdentity identity) { + if (identity == null + || !identity.isService(MIGRATOR_SERVICE_ACCOUNT) + || !identity.isInNamespace(podNamespace)) { + throw new IllegalStateException("tenant migration certificate has the wrong identity"); + } + } + + private GrpcPeerIdentity verifiedWorkloadIdentity() throws Exception { + Path certificatePath = Path.of(required("FIREMUD_GRPC_CERT_CHAIN_PATH")); + X509Certificate leaf; + try (InputStream input = Files.newInputStream(certificatePath)) { + leaf = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + return GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow( + () -> new IllegalStateException("tenant migration certificate lacks a valid URI SAN")); + } + private String required(String property) { String value = environment.getProperty(property); if (value == null || value.isBlank()) { 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 cafe76ed7a..29579328f2 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 @@ -98,10 +98,10 @@ public void resolveLegacyGameTenantIdentity( public void resolveLegacyAccountTenantAssociation( ResolveLegacyAccountTenantAssociationRequest request, StreamObserver responseObserver) { - if (!isAccountPeer()) { + if (!isAccountTenantMigratorPeer()) { responseObserver.onError( Status.PERMISSION_DENIED - .withDescription("Verified Account workload identity is required") + .withDescription("Verified Account tenant migrator identity is required") .asRuntimeException()); return; } @@ -177,6 +177,15 @@ private boolean isAccountPeer() { && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"); } + private boolean isAccountTenantMigratorPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && workloadNamespace != null + && !workloadNamespace.isBlank() + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-tenant-migrator"); + } + private static boolean validSignature(String value) { if (value == null) { return false; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java new file mode 100644 index 0000000000..b944cf69ab --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class TenantAssociationManifestJobRunnerTest { + @Test + void acceptsOnlyExactDedicatedMigratorCertificate() { + assertThatCode( + () -> + TenantAssociationManifestJobRunner.requireJobIdentity( + "dev", peer("dev", "game-design-tenant-migrator"))) + .doesNotThrowAnyException(); + for (GrpcPeerIdentity wrong : + new GrpcPeerIdentity[] { + null, + peer("dev", "game-design-service"), + peer("pr-12", "game-design-tenant-migrator"), + peer("dev", "account-tenant-migrator") + }) { + assertThatThrownBy(() -> TenantAssociationManifestJobRunner.requireJobIdentity("dev", wrong)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("wrong identity"); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } +} 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 9fb1b0a3e1..6a132383bd 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 @@ -28,6 +28,8 @@ class TenantIdentityGrpcServiceTest { private static final String ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; + private static final String ACCOUNT_MIGRATOR_PEER = + "spiffe://firemud/ns/test/sa/account-tenant-migrator"; private static final String WRONG_PEER = "spiffe://firemud/ns/test/sa/game-session-service"; private static final UUID CANONICAL_TENANT_ID = UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); @@ -43,7 +45,7 @@ void approvedAccountAssociationReadBindsExactOwnerAndManifestEvidence() { when(associationService.findByLegacyAccountTenantId(41L)) .thenReturn(Optional.of(approvedAssociation())); - AssociationObserver observer = associationCall(41L, ACCOUNT_PEER); + AssociationObserver observer = associationCall(41L, ACCOUNT_MIGRATOR_PEER); assertNull(observer.errorCode); assertTrue(observer.completed); @@ -66,7 +68,10 @@ void associationReadRejectsMissingPeerAndInvalidNumericKeyBeforeOwnerRead() { assertEquals( Status.Code.PERMISSION_DENIED, associationStatus(associationCall(41L, WRONG_PEER))); assertEquals( - Status.Code.INVALID_ARGUMENT, associationStatus(associationCall(0L, ACCOUNT_PEER))); + Status.Code.PERMISSION_DENIED, associationStatus(associationCall(41L, ACCOUNT_PEER))); + assertEquals( + Status.Code.INVALID_ARGUMENT, + associationStatus(associationCall(0L, ACCOUNT_MIGRATOR_PEER))); verifyNoInteractions(associationService); } @@ -75,9 +80,11 @@ void associationReadFailsClosedForAbsentOrCorruptOwnerEvidence() { when(associationService.findByLegacyAccountTenantId(41L)).thenReturn(Optional.empty()); when(associationService.findByLegacyAccountTenantId(42L)) .thenThrow(new IllegalStateException("corrupt operation")); - assertEquals(Status.Code.NOT_FOUND, associationStatus(associationCall(41L, ACCOUNT_PEER))); assertEquals( - Status.Code.FAILED_PRECONDITION, associationStatus(associationCall(42L, ACCOUNT_PEER))); + Status.Code.NOT_FOUND, associationStatus(associationCall(41L, ACCOUNT_MIGRATOR_PEER))); + assertEquals( + Status.Code.FAILED_PRECONDITION, + associationStatus(associationCall(42L, ACCOUNT_MIGRATOR_PEER))); } @Test @@ -106,6 +113,8 @@ void exactAccountPeerReadsOwnerSourceAndProvenance() { void wrongOrMissingPeerNeverReadsOwnerRows() { assertEquals(Status.Code.PERMISSION_DENIED, status(call("legacy-game-7", WRONG_PEER))); assertEquals(Status.Code.PERMISSION_DENIED, status(call("legacy-game-7", null))); + assertEquals( + Status.Code.PERMISSION_DENIED, status(call("legacy-game-7", ACCOUNT_MIGRATOR_PEER))); verifyNoInteractions(repository); } From 2cf17da797ac163044cbae636c6b4f37642c7ef8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 13:06:16 +1300 Subject: [PATCH 16/28] Supply active membership lifecycle in Game Session integration fixture --- .../websocket/GameSessionWebSocketHandlerIntegrationTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 7fb1938f05..bfabacb888 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -265,6 +265,7 @@ void setUp() { .setAccountId("123") .setTenantId("22") .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") From b71ae2e15688ea878a6effbe159d51743c724c32 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:36:12 +1300 Subject: [PATCH 17/28] Disable Account scheduling in tenant migration jobs --- .../account-service/operations.md | 2 + .../AccountServiceApplication.java | 2 - .../AccountSchedulingConfiguration.java | 15 ++++++++ ...egacyTenantAssociationImportJobRunner.java | 12 +++++- .../AccountSchedulingConfigurationTest.java | 38 +++++++++++++++++++ ...yTenantAssociationImportJobRunnerTest.java | 30 +++++++++++++++ 6 files changed, 96 insertions(+), 3 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountSchedulingConfiguration.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountSchedulingConfigurationTest.java diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index bd29c42c19..df00e29299 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -15,6 +15,8 @@ This document collects the Account Service operational behavior, readiness model An operator first runs `evidence` for an exact positive retained numeric key in a listener-free Account job using the dedicated `account-tenant-migrator` certificate and service account. Missing or conflicting V26 source rows fail closed. The digest goes into the [Game Design approved manifest](../game-design-service/operations.md#legacy-tenant-association-migration), not into an inferred key match. After Game Design applies and reads back the signed operation, the operator runs Account `import` for the same key. That mode calls Game Design with the exact migrator mTLS identity, validates its owner response and the current V26 digest, and commits the immutable local mapping. Ordinary Account service identity cannot call this import read; the migrator cannot call the separate former-key read. An exact retry is event-free; changed owner or Account evidence is a conflict. +When this Job is enabled, Account's scheduling configuration is absent so audit delivery, JOIN reconciliation, and credential cleanup cannot run in the migration process. The runner also fails before owner evidence or import if a `ScheduledAnnotationBeanPostProcessor` is present. + The chart's `previewStack.tenantAssociationMigration.account` values are disabled by default. From a trusted operator revision, supply the exact namespace, a reviewed immutable Account image digest, mode (`evidence` or `import`), positive numeric key, and stable run ID; do not leave the Job enabled for ordinary upgrades. The dedicated `firemud-grpc-account-tenant-migrator` Secret must be issued and verified explicitly using `ensure-standalone-transport-certificates.sh --account-tenant-migrator` and `--verify-account-tenant-migrator` before enabling the Job. The Secret is stable and reused, not requested on every deployment; the Job has no Kubernetes API token, no ingress, and only DNS/Postgres egress plus Game Design gRPC for `import`. A rendered Job or successful completion alone is not database or served-mTLS proof. Retain the operation/readback evidence privately, disable the Job after use, and retire the exact certificate and Secret through the trusted operator boundary. Live Job, PostgreSQL, cross-service, and membership consumer proof remain open; an import cannot be treated as a JOIN, a sequence-zero stream checkpoint, or a working runtime membership RPC. ## Saga Participation diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java index b6dcb023b4..702b66fb6d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java @@ -5,11 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; import org.springframework.context.annotation.Import; -import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @ConfigurationPropertiesScan -@EnableScheduling @Import(GlobalExceptionHandler.class) public class AccountServiceApplication { public static void main(String[] args) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountSchedulingConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountSchedulingConfiguration.java new file mode 100644 index 0000000000..8396e0e332 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountSchedulingConfiguration.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.accountservice.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** Enables Account maintenance jobs only during ordinary service operation. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account-tenant-migration", + name = "enabled", + havingValue = "false", + matchIfMissing = true) +@EnableScheduling +public class AccountSchedulingConfiguration {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java index 945f47e64e..c366ad46ef 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java @@ -9,10 +9,12 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.core.env.Environment; +import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; /** Opt-in Account owner import; ordinary service startup performs no legacy mapping. */ @@ -27,15 +29,23 @@ public class LegacyTenantAssociationImportJobRunner implements ApplicationRunner private final Environment environment; private final LegacyTenantAssociationImportService importService; + private final ObjectProvider schedulingPostProcessor; public LegacyTenantAssociationImportJobRunner( - Environment environment, LegacyTenantAssociationImportService importService) { + Environment environment, + LegacyTenantAssociationImportService importService, + ObjectProvider schedulingPostProcessor) { this.environment = environment; this.importService = importService; + this.schedulingPostProcessor = schedulingPostProcessor; } @Override public void run(ApplicationArguments args) throws Exception { + if (schedulingPostProcessor.getIfAvailable() != null) { + throw new IllegalStateException( + "Account tenant migration must not start with scheduling enabled"); + } if (!"true".equals(System.getenv("FIREMUD_ACCOUNT_TENANT_MIGRATION_ENABLED")) || !"none".equalsIgnoreCase(required("spring.main.web-application-type")) || environment.getProperty("spring.grpc.server.enabled", Boolean.class, true)) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountSchedulingConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountSchedulingConfigurationTest.java new file mode 100644 index 0000000000..2ad14c6a89 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountSchedulingConfigurationTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; + +class AccountSchedulingConfigurationTest { + @Test + void migrationModeDoesNotRegisterSchedulingPostProcessor() { + try (AnnotationConfigApplicationContext context = contextWithMigrationEnabled(true)) { + assertThat(context.getBeansOfType(ScheduledAnnotationBeanPostProcessor.class)).isEmpty(); + } + } + + @Test + void ordinaryModeRegistersSchedulingPostProcessor() { + try (AnnotationConfigApplicationContext context = contextWithMigrationEnabled(false)) { + assertThat(context.getBeansOfType(ScheduledAnnotationBeanPostProcessor.class)).hasSize(1); + } + } + + private static AnnotationConfigApplicationContext contextWithMigrationEnabled(boolean enabled) { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "test", Map.of("firemud.account-tenant-migration.enabled", enabled))); + context.register(AccountSchedulingConfiguration.class); + context.refresh(); + return context; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java index 7bc963307c..e8bb72c3af 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java @@ -2,11 +2,41 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import net.firedevops.firemud.accountservice.service.impl.LegacyTenantAssociationImportService; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.core.env.Environment; +import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; class LegacyTenantAssociationImportJobRunnerTest { + @Test + void failsBeforeOwnerEvidenceOrImportWhenSchedulingIsPresent() { + Environment environment = mock(Environment.class); + LegacyTenantAssociationImportService importService = + mock(LegacyTenantAssociationImportService.class); + @SuppressWarnings("unchecked") + ObjectProvider schedulingPostProcessor = + mock(ObjectProvider.class); + ScheduledAnnotationBeanPostProcessor processor = + mock(ScheduledAnnotationBeanPostProcessor.class); + when(schedulingPostProcessor.getIfAvailable()).thenReturn(processor); + + LegacyTenantAssociationImportJobRunner runner = + new LegacyTenantAssociationImportJobRunner( + environment, importService, schedulingPostProcessor); + + assertThatThrownBy(() -> runner.run(new DefaultApplicationArguments())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("scheduling enabled"); + verifyNoInteractions(importService); + } + @Test void acceptsOnlyExactDedicatedMigratorCertificate() { assertThatCode( From 36f7b61b33ea53e2614f70ed71e1e8f6088baff4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:46:05 +1300 Subject: [PATCH 18/28] Fail closed on incomplete PLAY membership and entitlement evidence --- .../account-service/runtime-and-data.md | 4 +- .../realm-routing-and-playable-state.md | 2 +- .../command/text/PlayCommandHandler.java | 28 ++++- .../command/text/PlayCommandHandlerTest.java | 104 ++++++++++++++++-- 4 files changed, 127 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index e59901a9e3..7b8d87ca63 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -22,7 +22,7 @@ The current public registration path creates only a global Account row and a pla Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The proto and Account producer emit lifecycle state and generation, but Game Session does not validate them; `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes fail with `FAILED_PRECONDITION` before Account reads until a typed verified player/target contract and consumer are implemented. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public missing or `INACTIVE` membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`; an existing `ACTIVE` non-admitting membership returns `CONNECT_TOKEN_REJECTED`, and a missing Account-owned non-public grant returns `REALM_ACCESS_DENIED`. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. Game Session `PLAY` validates lifecycle consistency against existence, admission, and version fields and rejects a missing or nonpositive membership authority generation. It does not validate `authorityAvailability`, roles, the complete `authorityTuple`, or `outboxCheckpoints`; those fields remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. The current entitlement response likewise lacks the complete Account-authenticated bundle, caller/target binding, authority tuple, billing cutoff, checkpoint set, and fence evidence required by the target contract. Its consumer checks only the represented tenant, positive entitlement version, and evaluation-time fields; this subset does not establish complete snapshot or fence proof. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes fail with `FAILED_PRECONDITION` before Account reads until a typed verified player/target contract and consumer are implemented. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public missing or `INACTIVE` membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`; an existing `ACTIVE` non-admitting membership returns `CONNECT_TOKEN_REJECTED`, and a missing Account-owned non-public grant returns `REALM_ACCESS_DENIED`. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. Account still cannot treat their bare request-body `accountId`/`tenantId` as verified player or lifecycle context. These runtime reads and the similarly bare realm-grant read must reject before Account data access until the exact Game Session or World Management peer, typed caller/target context, and applicable private delegation are carried and verified. The Game Session consumer still sends the older request shape, so this containment is not a working admission path or proof of the target membership/entitlement snapshot. @@ -182,7 +182,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and the opaque generation, but current runtime callers do not enforce either field. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. +- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and `membershipAuthorityGeneration`. Game Session `PLAY` validates lifecycle consistency against `membershipExists`, `gameplayAdmissionAllowed`, and `membershipVersion`, and rejects a missing or nonpositive generation. It does not validate `authorityAvailability`, roles, the complete tuple, or outbox checkpoints; those fields are absent from the current response. The live Account RPC still rejects before data access, so mocked consumer checks do not establish a fresh atomic target snapshot or fail-closed proof over its complete evidence bundle. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 1fb0dc9932..cb6b1985a4 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -101,7 +101,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- Explicit `JOIN`/`Join & Play` now has a local Account operation and Game Session scope/translation seam, but the complete bridge remains unproved. Current Game Session membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access, so valid-route direct-text `PLAY` returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Membership outcome branches in Game Session are currently reachable only with successful mocked Account responses. Account REST connect-token issuance is a separate path with its own current behavior and is not covered by this gRPC failure. The target requires explicit lifecycle, authority-generation, and independent membership-version checks, which are not currently proved. PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, and the target membership-authority-generation reread at issuance remain gaps. See [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status) for the canonical direct-text outcome. +- Explicit `JOIN`/`Join & Play` now has a local Account operation and Game Session scope/translation seam, but the complete bridge remains unproved. Current Game Session membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access, so valid-route direct-text `PLAY` returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Membership outcome branches in Game Session are currently reachable only with successful mocked Account responses. In those mocked `PLAY` branches, membership lifecycle consistency and a positive `membershipAuthorityGeneration` are checked alongside the independent `membershipVersion`; this does not prove an Account-authenticated atomic snapshot because `authorityAvailability`, tuple, and checkpoints are absent. The entitlement consumer checks only the represented target, version, and evaluation time; the response lacks the complete target bundle and fence evidence, and the runtime RPC remains disabled before Account data access. Account REST connect-token issuance is a separate path with its own current behavior and is not covered by this gRPC failure. PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, and the target membership-authority-generation reread at issuance remain gaps. See [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status) for the canonical direct-text outcome. - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index b4e70732ea..7af38668e8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -5,6 +5,7 @@ import io.micrometer.core.instrument.MeterRegistry; import java.time.Instant; import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; import java.util.Objects; @@ -893,6 +894,11 @@ private Optional validateEntitlementsResponse( tenantBillingBlockedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } + if (!isSafeEntitlementAuthorityResponse(response, selectedRealm)) { + return Optional.of( + entitlementUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } if (!response.getGameplayAvailable()) { return Optional.of( tenantBillingBlockedFailure( @@ -1031,7 +1037,27 @@ private boolean isSafeMembershipAuthorityResponse( } catch (DateTimeParseException | NumberFormatException ex) { return false; } - return true; + return response.getMembershipAuthorityGeneration() > 0L; + } + + private boolean isSafeEntitlementAuthorityResponse( + GetTenantEntitlementsForRuntimeResponse response, + GameplayWorldCatalog.RealmView selectedRealm) { + if (!StringUtils.hasText(response.getTenantId()) + || !StringUtils.hasText(response.getEvaluatedAt()) + || response.getEntitlementVersion() <= 0L) { + return false; + } + try { + long tenantId = Long.parseLong(response.getTenantId()); + Instant evaluatedAt = Instant.parse(response.getEvaluatedAt()); + Instant now = Instant.now(); + return tenantId == selectedRealm.tenantId() + && !evaluatedAt.isAfter(now) + && evaluatedAt.isAfter(now.minus(15, ChronoUnit.SECONDS)); + } catch (DateTimeParseException | NumberFormatException ex) { + return false; + } } private void maybeRecordFreshEntryFallback( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 6b56b01405..185d1bd6f9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -5,6 +5,8 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Optional; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; @@ -110,6 +112,7 @@ void setUp() { .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) @@ -120,7 +123,7 @@ void setUp() { .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1058,6 +1061,7 @@ void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding( .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1086,6 +1090,7 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .setMembershipExists(false) .setMembershipLifecycleState("MISSING") .setGameplayAdmissionAllowed(false) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1126,6 +1131,7 @@ void playNonPublicInactiveMembershipDoesNotUsePublicJoin() { .setMembershipLifecycleState("INACTIVE") .setGameplayAdmissionAllowed(false) .setMembershipVersion(3L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1232,7 +1238,9 @@ void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { .setTenantId("22") .setGameplayAvailable(true) .setAllowPublicJoin(false) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEntitlementVersion(1L) + .setTenantBillingSequence(0L) + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1368,6 +1376,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { .setMembershipLifecycleState("MISSING") .setGameplayAdmissionAllowed(false) .setMembershipVersion(5L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); PlayCommandHandlingResult result = @@ -1399,6 +1408,7 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta .setMembershipLifecycleState(lifecycleState) .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1429,6 +1439,7 @@ void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleSt .setMembershipLifecycleState(lifecycleState) .setGameplayAdmissionAllowed(true) .setMembershipVersion(membershipExists ? 3L : 5L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1455,6 +1466,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { .setMembershipLifecycleState("INACTIVE") .setGameplayAdmissionAllowed(false) .setMembershipVersion(4L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); @@ -1485,6 +1497,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { .setMembershipLifecycleState("MISSING") .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) @@ -1525,6 +1538,7 @@ void playBillingDenialMasksMissingPublicMembership() { .setMembershipLifecycleState("MISSING") .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) @@ -1533,7 +1547,9 @@ void playBillingDenialMasksMissingPublicMembership() { .setTenantId("22") .setGameplayAvailable(false) .setAllowPublicJoin(true) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEntitlementVersion(1L) + .setTenantBillingSequence(0L) + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1563,6 +1579,7 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { .setMembershipLifecycleState("MISSING") .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) @@ -1571,7 +1588,9 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { .setTenantId("22") .setGameplayAvailable(true) .setAllowPublicJoin(false) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEntitlementVersion(1L) + .setTenantBillingSequence(0L) + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1602,7 +1621,9 @@ void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { .setTenantId("22") .setGameplayAvailable(true) .setAllowPublicJoin(false) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEntitlementVersion(1L) + .setTenantBillingSequence(0L) + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1627,6 +1648,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti .setMembershipLifecycleState("MISSING") .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) @@ -1635,7 +1657,9 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti .setTenantId("22") .setGameplayAvailable(true) .setAllowPublicJoin(true) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEntitlementVersion(1L) + .setTenantBillingSequence(0L) + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1666,6 +1690,7 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("not-a-timestamp") .build()); @@ -1684,6 +1709,71 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + } + + @ParameterizedTest + @ValueSource(strings = {"target", "version", "stale", "future", "malformed"}) + void unsafeEntitlementSnapshotFailsClosed(String defect) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + String tenantId = "target".equals(defect) ? "23" : "22"; + long entitlementVersion = "version".equals(defect) ? 0L : 1L; + String evaluatedAt = + switch (defect) { + case "stale" -> Instant.now().minus(16L, ChronoUnit.SECONDS).toString(); + case "future" -> Instant.now().plus(1L, ChronoUnit.SECONDS).toString(); + case "malformed" -> "not-a-timestamp"; + default -> Instant.now().toString(); + }; + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId(tenantId) + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(entitlementVersion) + .setTenantBillingSequence(0L) + .setEvaluatedAt(evaluatedAt) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE); + Mockito.verify(accountClient, never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + } + @Test void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = @@ -1696,7 +1786,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { .setGameplayAvailable(false) .setEntitlementVersion(5L) .setTenantBillingSequence(5L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = From 5e9f9050c362bb9a10741255b98d143b3aed5c5b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:01:42 +1300 Subject: [PATCH 19/28] fix(account): deny legacy private-grant authority on REST reads --- .../account-service/runtime-and-data.md | 4 +- .../player-access-and-session.md | 4 +- .../service/impl/AccountServiceImpl.java | 11 +- .../service/impl/AccountServiceImplTest.java | 304 ++++++++++-------- 4 files changed, 177 insertions(+), 146 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 7b8d87ca63..500428d45e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -22,7 +22,7 @@ The current public registration path creates only a global Account row and a pla Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. Game Session `PLAY` validates lifecycle consistency against existence, admission, and version fields and rejects a missing or nonpositive membership authority generation. It does not validate `authorityAvailability`, roles, the complete `authorityTuple`, or `outboxCheckpoints`; those fields remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. The current entitlement response likewise lacks the complete Account-authenticated bundle, caller/target binding, authority tuple, billing cutoff, checkpoint set, and fence evidence required by the target contract. Its consumer checks only the represented tenant, positive entitlement version, and evaluation-time fields; this subset does not establish complete snapshot or fence proof. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes fail with `FAILED_PRECONDITION` before Account reads until a typed verified player/target contract and consumer are implemented. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public missing or `INACTIVE` membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`; an existing `ACTIVE` non-admitting membership returns `CONNECT_TOKEN_REJECTED`, and a missing Account-owned non-public grant returns `REALM_ACCESS_DENIED`. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. Game Session `PLAY` validates lifecycle consistency against existence, admission, and version fields and rejects a missing or nonpositive membership authority generation. It does not validate `authorityAvailability`, roles, the complete `authorityTuple`, or `outboxCheckpoints`; those fields remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. The current entitlement response likewise lacks the complete Account-authenticated bundle, caller/target binding, authority tuple, billing cutoff, checkpoint set, and fence evidence required by the target contract. Its consumer checks only the represented tenant, positive entitlement version, and evaluation-time fields; this subset does not establish complete snapshot or fence proof. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes fail with `FAILED_PRECONDITION` before Account reads until a typed verified player/target contract and consumer are implemented. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public REST realm discovery, character listing, and connect-token issuance now fail closed even when the legacy four-field grant row exists, because it cannot prove the current lifecycle and state generation. The target lifecycle-qualified grant authority is not implemented; public-production REST behavior remains unchanged. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. Account still cannot treat their bare request-body `accountId`/`tenantId` as verified player or lifecycle context. These runtime reads and the similarly bare realm-grant read must reject before Account data access until the exact Game Session or World Management peer, typed caller/target context, and applicable private delegation are carried and verified. The Game Session consumer still sends the older request shape, so this containment is not a working admission path or proof of the target membership/entitlement snapshot. @@ -143,7 +143,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - Audience is `player-bootstrap`. - It is issued only by `POST /auth/player-bootstrap` / `IssuePlayerBootstrapToken`. - `POST /auth/player-bootstrap` is the canonical first-party browser/mobile player-login endpoint. It authenticates player credentials directly under the same password, OTP, brute-force defense, and account-lock policy used for gameplay login rather than deriving bootstrap from a pre-existing admin/creator session. -- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current Account REST runtime requires existing caller-bound membership for character discovery and connect-token issuance and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. The separate Game Session text `PLAY` path is currently blocked earlier by Account runtime membership/grant/entitlement gRPC methods returning `FAILED_PRECONDITION` before reads, producing `AUTH_UNAVAILABLE`; its downstream membership outcomes require successful mocked Account responses. For a publicly visible public-production target whose joining policy permits entry, the Account connect-token issuance branch may return `JOIN_REQUIRED` without creating or restoring membership; the latter existing-membership case is not lifecycle-aware while explicit `JOIN` is a separate local action. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. +- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current Account REST runtime requires existing caller-bound membership for character discovery and connect-token issuance and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. Non-public REST realm discovery, character listing, and connect-token issuance fail closed even when a legacy four-field grant row exists, because it cannot prove the current lifecycle and state generation; public-production behavior remains unchanged. The separate Game Session text `PLAY` path is currently blocked earlier by Account runtime membership/grant/entitlement gRPC methods returning `FAILED_PRECONDITION` before reads, producing `AUTH_UNAVAILABLE`; its downstream membership outcomes require successful mocked Account responses. For a publicly visible public-production target whose joining policy permits entry, the Account connect-token issuance branch may return `JOIN_REQUIRED` without creating or restoring membership; the latter existing-membership case is not lifecycle-aware while explicit `JOIN` is a separate local action. The target lifecycle-qualified grant authority is not implemented. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. - Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish that proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f2bb694609..c326a75839 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -104,7 +104,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. Fresh connect-token issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership lifecycle, and current four-field non-public grant before token storage. This bounded lookup does not prove the target lifecycle-qualified, expiring five-field grant, atomic membership-generation reread, or cached-success freshness. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). +`POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Non-public REST realm discovery, character listing, and connect-token issuance now fail closed even when a legacy four-field Account grant row exists, because it cannot prove the current playtest lifecycle and state generation; public-production behavior remains unchanged. Runtime gRPC grant reads also remain denied before Account reads, so text `PLAY` cannot consume a grant result. The target lifecycle-qualified, expiring grant authority, atomic membership-generation reread, and cached-success freshness remain unimplemented. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit `JOIN`/`Join & Play` is implemented locally through the canonical `JoinPublicProductionMembership` Account writer, including a policy-bound v1 digest and membership/audit outbox transaction. Its bounded `PENDING` readback worker is local, but PostgreSQL recovery/concurrency and direct text-client proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). @@ -188,7 +188,7 @@ The evidence records focused unit, controller, gRPC, WebSocket, cross-service, a The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. First-party proofs cover fresh-token enforcement, bare verified-identity login, `PLAY` scope binding, replay/expiry/context/scope failures, screen-buffer restore, and fresh redraw. -Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and the contained export/deletion/recovery boundaries. `DeleteAccount` now denies before account or financial-row mutation rather than relying on a partial active-subscription guard. Explicit `JOIN`/`Join & Play` and its bounded readback worker are local, while PostgreSQL lost-acknowledgement/concurrency, the connect-token membership-authority-generation reread, and canonical tenant-role, lifecycle-state, and authority-generation follow-through remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, REST denial of non-public admission from legacy grant rows, cross-tenant membership enforcement, and the contained export/deletion/recovery boundaries. `DeleteAccount` now denies before account or financial-row mutation rather than relying on a partial active-subscription guard. Explicit `JOIN`/`Join & Play` and its bounded readback worker are local, while PostgreSQL lost-acknowledgement/concurrency, the connect-token membership-authority-generation reread, lifecycle-qualified grant authority, and canonical tenant-role, lifecycle-state, and authority-generation follow-through remain partial or unproved. - **Validation record:** Required current documentation, contract, settings-generation, allocation, ADR, and `git diff --check` gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Runtime proof is not applicable to this documentation-only change. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 540d1c05c9..2f43507c72 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1010,6 +1010,12 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR if (cachedReplay.isPresent()) { var replay = cachedReplay.orElseThrow(); if (replay.success()) { + RuntimeRealmTarget currentRealm = requireCurrentConnectScopeTarget(scopeContext); + if (!isPublicProductionRealm(currentRealm)) { + throw new AuthenticationException( + "REALM_ACCESS_DENIED", + "The selected non-public realm does not have an active access grant"); + } logger.info( "Replayed connect-token attempt for account {} tenant {} world {} realm {} requestId {}", bootstrapContext.accountId(), @@ -1732,8 +1738,9 @@ private Account requireAccount(Long accountId) { private boolean hasRealmAccessGrant( Long accountId, Long tenantId, String worldSlug, String realmSlug) { - return accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - accountId, tenantId, worldSlug, realmSlug); + // The retained four-field row cannot prove the current playtest lifecycle and state generation. + // Keep legacy grant records for write/history paths, but do not use them as REST authority. + return false; } private String mintToken(String subject, long expirationMs, Map claims) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 366601422f..340e2957b9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -2265,28 +2265,30 @@ void issueConnectTokenReturnsShortLivedConnectToken() { } @Test - void issueConnectTokenRequiresCurrentGrantForNonPublicRealm() { + void issueConnectTokenRejectsLegacyGrantWithoutLifecycleProof() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); - ConnectTokenResult result = - service.issueConnectToken( - context.bootstrapToken(), - new ConnectTokenRequest(context.connectScopeId(), "req-private-grant")); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-private-grant"))); - assertNotNull(result.connectToken()); - assertFalse(result.replayed()); - org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.times(2)) + assertEquals("REALM_ACCESS_DENIED", exception.getCode()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); - org.mockito.Mockito.verify(sessionService) + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) .storeSession( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.eq(30000L)); + org.mockito.ArgumentMatchers.anyLong()); } @Test @@ -2306,7 +2308,7 @@ void issueConnectTokenRejectsNonPublicRealmWhenCurrentGrantIsMissing() { new ConnectTokenRequest(context.connectScopeId(), "req-private-grant-denied"))); assertEquals("REALM_ACCESS_DENIED", exception.getCode()); - org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.times(2)) + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) .storeSession( @@ -2390,7 +2392,7 @@ void issueConnectTokenRequiresActiveMembershipForNonPublicRealm() { assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); verifyConnectTokenFailureDoesNotStoreSuccess( context.connectScopeId(), "req-inactive-private", "NON_PUBLIC_ENROLLMENT_REQUIRED"); - org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.times(1)) + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @@ -2616,7 +2618,7 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { } @Test - void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() { + void issueConnectTokenReplaysSameTokenWhenPublicScopeStillMatchesPointer() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -2642,6 +2644,17 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, firstResult, "", ""))); + + ConnectTokenResult replayed = + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); + + assertEquals(firstResult.connectToken(), replayed.connectToken()); + assertEquals(firstResult.issuedAt(), replayed.issuedAt()); + assertEquals(firstResult.expiresAt(), replayed.expiresAt()); + assertEquals(firstResult.requestId(), replayed.requestId()); + assertTrue(replayed.replayed()); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() @@ -2662,15 +2675,52 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setCharacterCreationPolicy("ALLOW_NEW") .build()); - ConnectTokenResult replayed = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); + AuthenticationException staleReplayException = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-replay-1"))); - assertEquals(firstResult.connectToken(), replayed.connectToken()); - assertEquals(firstResult.issuedAt(), replayed.issuedAt()); - assertEquals(firstResult.expiresAt(), replayed.expiresAt()); - assertEquals(firstResult.requestId(), replayed.requestId()); - assertTrue(replayed.replayed()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", staleReplayException.getCode()); + } + + @Test + void issueConnectTokenRejectsCachedSuccessForNonPublicRealm() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + ConnectTokenResult cachedResult = + new ConnectTokenResult( + 11L, + 7L, + 55L, + "preview", + context.connectScopeId(), + "cached-private-connect-token", + "cached-jti", + "req-private-cached", + "2026-09-30T00:00:00Z", + "2026-09-30T00:00:30Z", + false); + when(sessionService.getConnectTokenReplay( + 7L, 11L, context.connectScopeId(), "req-private-cached")) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, cachedResult, "", ""))); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-private-cached"))); + + assertEquals("REALM_ACCESS_DENIED", exception.getCode()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @Test @@ -2831,6 +2881,34 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); + if (!publicProductionRealm) { + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + AccountTenantMembership deniedMembership = membership(account, 7L); + deniedMembership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(deniedMembership)); + + AuthenticationException privateException = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-membership-denied"))); + + assertEquals("CONNECT_TOKEN_REJECTED", privateException.getCode()); + assertEquals( + "Gameplay admission is not allowed for this account", privateException.getMessage()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + return; + } when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); AccountTenantMembership deniedMembership = membership(account, 7L); @@ -3163,67 +3241,44 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L)), Optional.empty()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "production")) - .thenReturn(true); - var privateRealm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Private Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(privateRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Private Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + .thenReturn(Optional.empty()); AuthenticationException exception = assertThrows( AuthenticationException.class, () -> service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + context.bootstrapToken(), "demo", "preview", context.connectScopeId())); assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); assertEquals( "Existing game membership is required for this non-public realm", exception.getMessage()); verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); + } + + @Test + void listBootstrapCharactersRejectsLegacyGrantWithoutLifecycleProof() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + context.bootstrapToken(), "demo", "preview", context.connectScopeId())); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @Test @@ -3931,7 +3986,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( @ParameterizedTest @CsvSource({"true, false", "false, true"}) - void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( + void listBootstrapRealmsDoesNotUseLegacyGrantAsLifecycleProof( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); @@ -3985,9 +4040,9 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - assertEquals(1, realms.size()); - assertEquals("preview", realms.getFirst().realmSlug()); - assertFalse(realms.getFirst().connectScopeId().isBlank()); + assertTrue(realms.isEmpty()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } @ParameterizedTest @@ -4052,86 +4107,34 @@ void listBootstrapRealmsExcludesInactiveMembershipDespiteAdmissionFlag( .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } - @ParameterizedTest - @CsvSource({"true, false", "false, true"}) - void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( - boolean visible, boolean publicProductionRealm) { + @Test + void issueConnectTokenRequiresMembershipForPrivateTargetDespiteLegacyGrant() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + PrivateConnectTokenContext context = preparePrivateConnectTokenContext(account, true); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L)), Optional.empty()); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("preview") - .setRealmDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + .thenReturn(Optional.empty()); AuthenticationException exception = assertThrows( AuthenticationException.class, () -> service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-preview-1"))); + context.bootstrapToken(), + new ConnectTokenRequest(context.connectScopeId(), "req-preview-1"))); assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); assertEquals( "Existing game membership is required for this non-public realm", exception.getMessage()); + org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) + .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); org.mockito.Mockito.verify(sessionService) .storeConnectTokenReplay( org.mockito.ArgumentMatchers.eq(7L), org.mockito.ArgumentMatchers.eq(11L), - org.mockito.ArgumentMatchers.eq(connectScopeId), + org.mockito.ArgumentMatchers.eq(context.connectScopeId()), org.mockito.ArgumentMatchers.eq("req-preview-1"), org.mockito.ArgumentMatchers.argThat( replay -> @@ -4783,7 +4786,7 @@ private PrivateConnectTokenContext preparePrivateConnectTokenContext( AccountTenantMembership tenantMembership = membership(account, 7L); tenantMembership.setLifecycleState(membershipLifecycleState); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L)), Optional.of(tenantMembership)); + .thenReturn(Optional.of(tenantMembership)); Subscription active = new Subscription(); active.setId(22L); active.setTenantId(7L); @@ -4813,12 +4816,33 @@ private PrivateConnectTokenContext preparePrivateConnectTokenContext( admissionPointer(7L, "demo", "preview", "55", 19L, true, false, "SHARED", "ALLOW_NEW")); when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( 11L, 7L, "demo", "preview")) - .thenReturn(true, grantAtIssuance); + .thenReturn(grantAtIssuance); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + java.time.Instant evaluatedAt = java.time.Instant.now(); + java.time.Instant expiresAt = + evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + // Simulate a retained legacy scope that has no lifecycle-qualified grant evidence. String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + new JwtUtil(JWT_SECRET, 30000L) + .generateToken( + "11", + tokenProperties.getConnectScopeExpirationMs(), + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", 11L), + Map.entry("tenantId", 7L), + Map.entry("realmId", REALM_ID), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "preview"), + Map.entry("playableStateNamespaceId", "production-namespace-7"), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", 55L), + Map.entry("catalogRevision", 23L), + Map.entry("pointerVersion", 19L), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", expiresAt.toString()))); return new PrivateConnectTokenContext(bootstrap.bootstrapToken(), connectScopeId); } From 99b55895ae5549ff3c6cbbeea9c22f9374186a6c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:37:46 +1300 Subject: [PATCH 20/28] Keep Game Session admission fixtures within authority freshness --- .../command/text/SessionResumptionFlowTest.java | 9 ++++++--- .../command/text/TextCommandInterpreterTest.java | 6 ++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 2ca798ce01..8f37e66e14 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; @@ -173,7 +174,8 @@ void setUp() { .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -195,7 +197,7 @@ void setUp() { .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(entityManagementClient.listCharactersByAccount( Mockito.anyString(), @@ -465,7 +467,8 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:01:00Z") + .setMembershipAuthorityGeneration(2L) + .setEvaluatedAt(Instant.now().toString()) .build()); TextCommandInterpretationResult secondLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index bd33c933a0..d7c3611021 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -12,6 +12,7 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; @@ -173,7 +174,8 @@ void setUp() { .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -194,7 +196,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(gameLogicClient.queryInventory(Mockito.any(SessionContext.class))) .thenReturn( From 2d35064586197e53ffff85ba5cec0209273e7de5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:39:54 +1300 Subject: [PATCH 21/28] Record isolated PR branch publication guardrail --- design/project-management/ai-observations.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8ab701b3b7..22a18eaf78 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -123,3 +123,8 @@ Entry format: - Context: Account V25's duplicate-detection preflight requires a PostgreSQL `DO` block and wraps it in `-- [jooq ignore start]` and `-- [jooq ignore stop]` markers. - Observation: this qualifies the 2026-09-20 expected pattern: declarative constraints remain preferred when sufficient, but a necessary procedural preflight can be excluded from jOOQ parsing while retaining separate PostgreSQL migration proof. - Expected pattern: prefer declarative constraints when sufficient; when procedural preflight is necessary, wrap it in the jOOQ ignore markers, run `generateJooq`, and run separate PostgreSQL migration proof. + +- `2026-09-30`: Verify a PR's remote head branch before publishing from an isolated worktree + - Context: #2873 was reconciled in a local preparation branch whose name differed from the PR head branch; an initial push mistakenly named #2880's branch as its destination. + - Observation: Git rejected that push as non-fast-forward, so no remote branch changed. The local commit was then pushed to #2873's verified `headRefName`. + - Expected pattern: read the live PR `headRefName` and exact remote head immediately before each push from an isolated branch; use the verified destination, and treat a non-fast-forward rejection as a stop-and-recheck signal rather than forcing it. From 3bd23a2bc02bb03cc92b752f4c49e51b9f5b14ee Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:56:34 +1300 Subject: [PATCH 22/28] test(account): align retained identity and runtime proof fixtures --- .../account-service/api-contracts.md | 4 +-- .../test/AccountRuntimeStubServerTest.java | 4 +++ .../test/AccountRuntimeStubServer.java | 8 +++--- .../impl/TenantIdentityGrpcService.java | 5 ++-- .../impl/TenantIdentityGrpcServiceTest.java | 13 ++++++++++ ...essionWebSocketHandlerIntegrationTest.java | 5 ++-- .../command/text/PlayCommandHandlerTest.java | 26 +++++++++---------- 7 files changed, 42 insertions(+), 23 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 89e93aaa0e..26f65e05ee 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -62,7 +62,7 @@ The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `Ver `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Fresh connect-token issuance now treats `INACTIVE` membership as nonadmitting and checks the current four-field non-public grant row, but it lacks an atomic membership-version/authority-generation commit gate and lifecycle-qualified, expiring grant proof. Text `PLAY` still does not enforce the emitted lifecycle state or generation; its conditional entitlement/public-policy order is unit-tested, while live Account gRPC reads deny before data access. Current non-public or non-visible target handling remains split across discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Fresh connect-token issuance treats `INACTIVE` membership as nonadmitting and fails closed for non-public targets until lifecycle-qualified, expiring grant authority is available; it also lacks an atomic membership-version/authority-generation commit gate. Text `PLAY` locally checks lifecycle consistency and a positive membership authority generation on mocked Account responses, but complete authenticated same-snapshot evidence is absent and live Account gRPC reads deny before data access; its conditional entitlement/public-policy order is unit-tested only. Current non-public or non-visible target handling remains split across discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Current JOIN Readback Behavior @@ -196,7 +196,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route is implementation drift only and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** fresh issuance checks tenant `gameplayAvailable`, treats `INACTIVE` membership as nonadmitting, and checks public `allowPublicJoin` or the current four-field non-public grant. It does not yet enforce the atomic membership-version/authority-generation commit gate or the complete lifecycle-qualified private/playtest grant-and-entitlement target. **Current response boundary:** the live `ConnectTokenResponse` is metadata-only and exposes neither the internal `jti` nor any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** fresh issuance checks tenant `gameplayAvailable`, treats `INACTIVE` membership as nonadmitting, and checks public `allowPublicJoin`; non-public issuance fails closed until lifecycle-qualified grant authority is implemented. It does not yet enforce the atomic membership-version/authority-generation commit gate or the complete lifecycle-qualified private/playtest grant-and-entitlement target. **Current response boundary:** the live `ConnectTokenResponse` is metadata-only and exposes neither the internal `jti` nor any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | | `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope yields nonterminal `AUTH_UNAVAILABLE` without invented policy evidence or membership mutation; expiry alone never terminalizes the operation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. A bounded Account-owned worker revisits abandoned `PENDING` intents and terminalizes only from exact operation, membership, and audit readback; absent or uncertain evidence remains nonterminal with capped attempts and diagnostics. Exact-final-head PostgreSQL lost-acknowledgement and concurrency proof, direct text end-to-end proof, and membership-generation snapshot proof remain open. | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index b6485d69f6..41fc73619e 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -41,6 +41,10 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio .build(); assertThat(stub.getTenantMembershipForRuntime(request).getMembershipLifecycleState()) .isEqualTo("ACTIVE"); + var activeMembership = stub.getTenantMembershipForRuntime(request); + assertThat(activeMembership.getMembershipAuthorityGeneration()).isPositive(); + assertThat(java.time.Instant.parse(activeMembership.getEvaluatedAt())) + .isAfter(java.time.Instant.now().minusSeconds(5)); server.denyGameplayAdmission(); var inactive = stub.getTenantMembershipForRuntime(request); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 0bc0f4bf81..ae206c0252 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -40,7 +40,6 @@ /** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase implements AutoCloseable { - private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; private static final Set IMPLEMENTED_RUNTIME_METHODS = Set.of( "Ping", @@ -177,7 +176,8 @@ public void getTenantMembershipForRuntime( .setMembershipLifecycleState(membershipLifecycleState.get()) .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) .setMembershipVersion(exists ? 1L : 0L) - .setEvaluatedAt(EVALUATED_AT) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); responseObserver.onCompleted(); } @@ -194,7 +194,7 @@ public void getRealmAccessGrantForRuntime( .setRealmSlug(request.getRealmSlug()) .setGranted(realmAccessGranted.get()) .setGrantVersion(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(Instant.now().toString()) .build()); responseObserver.onCompleted(); } @@ -210,7 +210,7 @@ public void getTenantEntitlementsForRuntime( .setAllowPublicJoin(allowPublicJoin.get()) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(Instant.now().toString()) .build()); responseObserver.onCompleted(); } 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 29579328f2..7ff3a9aaac 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 @@ -13,6 +13,7 @@ import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.jooq.exception.TooManyRowsException; import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; @@ -57,10 +58,10 @@ public void resolveLegacyGameTenantIdentity( Optional resolved; try { resolved = gameRepository.findTenantIdentityByLegacyTenantId(sourceKey); - } catch (IllegalStateException ex) { + } catch (IllegalStateException | TooManyRowsException ex) { responseObserver.onError( Status.FAILED_PRECONDITION - .withDescription("Game Design tenant identity provenance is invalid") + .withDescription("Game Design tenant identity is ambiguous or provenance is invalid") .asRuntimeException()); return; } 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 4b6538fe9a..02b8b8e9a9 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 @@ -24,6 +24,7 @@ import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; +import org.jooq.exception.TooManyRowsException; import org.junit.jupiter.api.Test; class TenantIdentityGrpcServiceTest { @@ -163,6 +164,18 @@ void invalidStoredProvenanceFailsClosed() { assertNull(observer.value); } + @Test + void duplicateRetainedLegacyTenantKeyFailsAsPrecondition() { + when(repository.findTenantIdentityByLegacyTenantId("legacy-game-7")) + .thenThrow(new TooManyRowsException("duplicate retained tenant key")); + + TestObserver observer = call("legacy-game-7", ACCOUNT_PEER); + + assertEquals(Status.Code.FAILED_PRECONDITION, status(observer)); + assertNull(observer.value); + assertFalse(observer.completed); + } + private TestObserver call(String sourceKey, String peerUri) { TestObserver observer = new TestObserver(); Context context = Context.current(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index bfabacb888..9b2868f925 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -268,7 +268,8 @@ void setUp() { .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) .getTenantMembershipForRuntime( @@ -281,7 +282,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) .getTenantEntitlementsForRuntime( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 185d1bd6f9..df27fbbf84 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -113,7 +113,7 @@ void setUp() { .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1062,7 +1062,7 @@ void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding( .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1091,7 +1091,7 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .setMembershipLifecycleState("MISSING") .setGameplayAdmissionAllowed(false) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1132,7 +1132,7 @@ void playNonPublicInactiveMembershipDoesNotUsePublicJoin() { .setGameplayAdmissionAllowed(false) .setMembershipVersion(3L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1377,7 +1377,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { .setGameplayAdmissionAllowed(false) .setMembershipVersion(5L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1409,7 +1409,7 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1440,7 +1440,7 @@ void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleSt .setGameplayAdmissionAllowed(true) .setMembershipVersion(membershipExists ? 3L : 5L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1467,7 +1467,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { .setGameplayAdmissionAllowed(false) .setMembershipVersion(4L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1498,7 +1498,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1539,7 +1539,7 @@ void playBillingDenialMasksMissingPublicMembership() { .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1580,7 +1580,7 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1649,7 +1649,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1724,7 +1724,7 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = From 1e9be76e24aa1bb8244ee5d3fbc3731cfbe2edaa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 19:34:25 +1300 Subject: [PATCH 23/28] test(game-session): assert exact retry replays base mismatch (cherry picked from commit fd7c3c37e722bfb064e2de6d610f6175f8abaf8b) --- ...PinOperationRepositoryIntegrationTest.java | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java index d8af33defc..f5bc14447a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java @@ -576,8 +576,28 @@ void pinAdmissionBaseMustStillMatchTheRowLockedRuntimeAndIsBoundToTheReceipt() { 100L); assertThat(replay).isEqualTo(mismatch); - assertThat(changedAdmission.errorCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(changedAdmission).isEqualTo(mismatch); assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isEqualTo(1); + assertThat( + dsl.select(SCRIPT_PIN_OPERATION.VALIDATED_BASE_VERSION_ID) + .from(SCRIPT_PIN_OPERATION) + .where(SCRIPT_PIN_OPERATION.CONTROL_PLANE_REQUEST_ID.eq("request-base-mismatch")) + .fetchOne(SCRIPT_PIN_OPERATION.VALIDATED_BASE_VERSION_ID)) + .isEqualTo(101L); + assertThat( + dsl.select( + GAME_INSTANCES.SCRIPT_PATCH_VERSION, + GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID, + GAME_INSTANCES.SCRIPT_PIN_EPOCH) + .from(GAME_INSTANCES) + .where(GAME_INSTANCES.ID.eq(7L)) + .fetchOne()) + .satisfies( + instance -> { + assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID)).isNull(); + assertThat(instance.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); } @Test From 29776ee4d3f38a161a0045d1cdf6a84532aa0a59 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 01:50:02 +1300 Subject: [PATCH 24/28] Disable implicit Flyway writes in tenant-association Jobs --- .../account-service/operations.md | 2 + .../game-design-service/operations.md | 2 + .../system-architecture-authz-route-matrix.md | 2 +- ...m-tenant-association-migration-contract.sh | 132 +++++++++++------- .../tenant-association-account-job.yaml | 1 + .../tenant-association-game-design-job.yaml | 1 + 6 files changed, 90 insertions(+), 50 deletions(-) diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 826c94cd7c..e4683c8507 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -70,6 +70,8 @@ ORDER BY legacy_source.tenant_id, legacy_source.account_id, legacy_source.member An operator first runs `evidence` for an exact positive retained numeric key in a listener-free Account job using the dedicated `account-tenant-migrator` certificate and service account. Missing or conflicting V26 source rows fail closed. The digest goes into the [Game Design approved manifest](../game-design-service/operations.md#legacy-tenant-association-migration), not into an inferred key match. After Game Design applies and reads back the signed operation, the operator runs Account `import` for the same key. That mode calls Game Design with the exact migrator mTLS identity, validates its owner response and the current V26 digest, and commits the immutable local mapping. Ordinary Account service identity cannot call this import read; the migrator cannot call the separate former-key read. An exact retry is event-free; changed owner or Account evidence is a conflict. +Deploy and independently verify the required Account schema through the normal reviewed deployment boundary, never through this Job: `evidence` needs its retained V26 source tables, and `import` additionally needs V30 association storage. Neither mode runs Flyway; the rendered Job explicitly disables it for every mode. Missing required tables or evidence fail the affected operation rather than triggering automatic schema repair. + When this Job is enabled, Account's scheduling configuration is absent so audit delivery, JOIN reconciliation, and credential cleanup cannot run in the migration process. The runner also fails before owner evidence or import if a `ScheduledAnnotationBeanPostProcessor` is present. The chart's `previewStack.tenantAssociationMigration.account` values are disabled by default. From a trusted operator revision, supply the exact namespace, a reviewed immutable Account image digest, mode (`evidence` or `import`), positive numeric key, and stable run ID; do not leave the Job enabled for ordinary upgrades. The dedicated `firemud-grpc-account-tenant-migrator` Secret must be issued and verified explicitly using `ensure-standalone-transport-certificates.sh --account-tenant-migrator` and `--verify-account-tenant-migrator` before enabling the Job. The Secret is stable and reused, not requested on every deployment; the Job has no Kubernetes API token, no ingress, and only DNS/Postgres egress plus Game Design gRPC for `import`. A rendered Job or successful completion alone is not database or served-mTLS proof. Retain the operation/readback evidence privately, disable the Job after use, and retire the exact certificate and Secret through the trusted operator boundary. Live Job, PostgreSQL, cross-service, and membership consumer proof remain open; an import cannot be treated as a JOIN, a sequence-zero stream checkpoint, or a working runtime membership RPC. diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 89659e7ffb..371e7c5020 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -34,6 +34,8 @@ The target publication boundary treats object-store export as a durable candidat For an approved operation, first obtain Account's exact retained-source evidence digest from its [Account owner migration mode](../account-service/operations.md#legacy-tenant-association-import). The Game Design owner then reviews the explicit numeric Account key, former Game Design key, V30 game row, canonical UUID, namespace, stable operation identity, and Account evidence digest; records the approval reference; and signs the canonical manifest preimage using an owner-controlled key already trusted by the migration job. A preflight verifies the signed bytes and exact namespace without writing. Only an operator-invoked `apply` with that same signed manifest and trusted public-key set writes V31; an exact retry must return the same readback and a conflicting pair fails. Account then imports from the authenticated owner read and checks its retained evidence before the membership consumer can be considered. This order does not enable the disabled runtime membership RPC. +Separately deploy the reviewed V31 schema migration and independently verify its readback before `apply`; missing required storage fails application rather than triggering automatic schema repair. Neither `preflight` nor `apply` runs Flyway; the rendered Job explicitly disables it for every mode. A successful signature-and-namespace-only `preflight` does not verify database schema readiness or replace that separate readback prerequisite. + The chart's `previewStack.tenantAssociationMigration.gameDesign` values are disabled by default. A trusted operator supplies an immutable Game Design image digest, exact namespace, stable run ID, mode, signed-manifest Secret and trusted-key Secret. Explicitly issue and verify the stable `firemud-grpc-game-design-tenant-migrator` identity using `ensure-standalone-transport-certificates.sh --game-design-tenant-migrator` and `--verify-game-design-tenant-migrator` before enabling the Job; the ordinary Game Design certificate is not a fallback. This dedicated certificate is a workload attestation guard, not an outbound owner-read credential. The Job has no Kubernetes API token or ingress and only DNS/Postgres egress; no ordinary Helm release creates it. Disable the Job after use and retire its exact certificate and Secret through the trusted operator boundary. A rendered Job is not executed migration proof: the live certificate, trusted Secrets, actual manifest, PostgreSQL readback and Account import still require deployment proof. Do not describe this path as an applied data migration until those checks execute. ### Historical Entity digest baseline migration diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 138f367a02..f8e04c767c 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -258,7 +258,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `DeleteAccount` (`DELETE /accounts/{accountId}`) | `account_scoped` | Current REST and direct service entries deny with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before mutation, after the route's subject or explicit platform-admin check. The target route additionally requires complete billing/provider/transfer clearance and the ADR 0043/`DATA-01` pending-deletion and retention workflow; it is not enabled by the old subscription-only precondition. | | Account Service | `ExportAccount` (`GET /accounts/{accountId}/export`) | `account_scoped` | **Status: `current_openapi_operator_surface`; synchronous Account/profile-local REST read only, not a second target operation.** The legacy account-ID gRPC export denies before data access. Target RPC semantics are protocol-equivalent to the sole canonical `POST /accounts/{accountId}/exports` route. The current local response and legacy `platformAdmin` override are known drift; the target canonical path is caller-subject-only. | | Account Service | `LinkExternalAccount` (`POST /accounts/{accountId}/external`) | `account_scoped` | **Target-only; currently unavailable.** Do not expose or advertise the current tenant-scoped caller-asserted scaffold. The target is the globally bound flow defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md), and requires server-verified provider authorization plus recent ordinary reauthentication before it becomes routable. | -| Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing; fresh issuance checks only the current four-field non-public grant row, not the lifecycle-qualified/expiring target grant and complete entitlement predicate. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Private/playtest targets require both membership and grant; global roles alone do not grant gameplay admission. | +| Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing, and lifecycle-qualified grant authority is unavailable. Fresh and cached-success private/playtest issuance remain denied until that grant authority exists; a retained four-field grant row does not authorize these targets. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Global roles alone do not grant gameplay admission. | | Account Service | `Authenticate` | `internal_workload` | Exact Game Session mTLS identity, no pre-existing issued token, and trusted server-derived credential source context | | Account Service | `RefreshGameplayServiceToken` | `internal_workload` | Exact Game Session mTLS identity plus current `game-session-account-delegation` authority with audience `account-service` | | Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus current Account-issued `game-session-account-delegation` authority with audience `account-service` and validated typed player/target context. Credential-bearing `LOGIN` obtains that private token from Account authentication; bare first-party `LOGIN` requires the separate Account-owned one-use exchange over proved committed connect issuance and verified signed context. Gateway context or a connect-token `jti` alone does not authorize the read, and Game Session never passes an end-user token as a substitute. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); the RPCs remain denied until the producer and consumer proof is complete. | diff --git a/dev-tools/tests/helm-tenant-association-migration-contract.sh b/dev-tools/tests/helm-tenant-association-migration-contract.sh index a3f84a4bc4..5bc50fe26e 100644 --- a/dev-tools/tests/helm-tenant-association-migration-contract.sh +++ b/dev-tools/tests/helm-tenant-association-migration-contract.sh @@ -52,6 +52,23 @@ with tempfile.TemporaryDirectory() as directory: if result.returncode == 0 or fragment not in result.stderr: raise SystemExit(f"{name} did not fail closed with {fragment}: {result.stderr}") + def require_flyway_disabled(args, workload): + expected = "--spring.flyway.enabled=false" + flyway_args = [arg for arg in args if arg.startswith("--spring.flyway.enabled=")] + if flyway_args != [expected]: + raise SystemExit(f"{workload} Job must disable Flyway explicitly, found {flyway_args}") + + def require_flyway_guard_negative_proof(args, workload): + for invalid_args in ( + [arg for arg in args if arg != "--spring.flyway.enabled=false"], + ["--spring.flyway.enabled=true" if arg == "--spring.flyway.enabled=false" else arg for arg in args], + ): + try: + require_flyway_disabled(invalid_args, workload) + except SystemExit: + continue + raise SystemExit(f"{workload} Flyway check accepted a missing or enabled property") + disabled = render("tenant-migration-disabled") if disabled.returncode: raise SystemExit(disabled.stderr) @@ -63,59 +80,76 @@ with tempfile.TemporaryDirectory() as directory: ): raise SystemExit("ordinary release rendered tenant-migration resources") - migration = { - "previewStack": { - "tenantAssociationMigration": { - "gameDesign": { - "enabled": True, - "mode": "apply", - "targetNamespace": "pr-123", - "runId": "approved-42", - "image": f"ghcr.io/benhook1013/game-design-service@sha256:{sha}", - "signedManifestSecretName": "tenant-manifest-approved-42", - "trustedKeysSecretName": "tenant-owner-public-keys", - }, - "account": { - "enabled": True, - "mode": "import", - "targetNamespace": "pr-123", - "runId": "approved-42", - "image": f"ghcr.io/benhook1013/account-service@sha256:{sha}", - "legacyTenantId": "41", + def migration_for(game_design_mode, account_mode): + return { + "previewStack": { + "tenantAssociationMigration": { + "gameDesign": { + "enabled": True, + "mode": game_design_mode, + "targetNamespace": "pr-123", + "runId": "approved-42", + "image": f"ghcr.io/benhook1013/game-design-service@sha256:{sha}", + "signedManifestSecretName": "tenant-manifest-approved-42", + "trustedKeysSecretName": "tenant-owner-public-keys", + }, + "account": { + "enabled": True, + "mode": account_mode, + "targetNamespace": "pr-123", + "runId": "approved-42", + "image": f"ghcr.io/benhook1013/account-service@sha256:{sha}", + "legacyTenantId": "41", + }, }, } } - } - enabled = render("tenant-migration-enabled", migration) - if enabled.returncode: - raise SystemExit(enabled.stderr) - by_kind_name = { - (item.get("kind"), item.get("metadata", {}).get("name")): item - for item in documents(enabled.stdout) - } - for service, mode in (("game-design", "apply"), ("account", "import")): - workload = f"{service}-tenant-migrator" - job = by_kind_name[("Job", f"{service}-tenant-{mode}-approved-42")] - pod = job["spec"]["template"]["spec"] - if pod["serviceAccountName"] != workload or pod["automountServiceAccountToken"] is not False: - raise SystemExit(f"{workload} Job did not bind the dedicated tokenless service account") - if by_kind_name[("ServiceAccount", workload)]["automountServiceAccountToken"] is not False: - raise SystemExit(f"{workload} service account mounts an API token") - secret = next(volume["secret"]["secretName"] for volume in pod["volumes"] if volume["name"] == "grpc-identity") - if secret != f"firemud-grpc-{workload}": - raise SystemExit(f"{workload} reused an ordinary service certificate") - policy = by_kind_name[("NetworkPolicy", workload)]["spec"] - if policy["ingress"] != [] or set(policy["policyTypes"]) != {"Ingress", "Egress"}: - raise SystemExit(f"{workload} has an unexpected ingress allowance") - destination_apps = { - selector["podSelector"]["matchLabels"]["app"] - for rule in policy["egress"] - for selector in rule["to"] - if "podSelector" in selector and "app" in selector["podSelector"].get("matchLabels", {}) + + def validate_rendered_jobs(name, migration, modes): + result = render(name, migration) + if result.returncode: + raise SystemExit(result.stderr) + by_kind_name = { + (item.get("kind"), item.get("metadata", {}).get("name")): item + for item in documents(result.stdout) } - expected = {"postgres"} | ({"game-design-service"} if service == "account" else set()) - if destination_apps != expected: - raise SystemExit(f"{workload} egress targets differ: {destination_apps}") + for service, mode in modes: + workload = f"{service}-tenant-migrator" + job = by_kind_name[("Job", f"{service}-tenant-{mode}-approved-42")] + pod = job["spec"]["template"]["spec"] + if pod["serviceAccountName"] != workload or pod["automountServiceAccountToken"] is not False: + raise SystemExit(f"{workload} Job did not bind the dedicated tokenless service account") + if by_kind_name[("ServiceAccount", workload)]["automountServiceAccountToken"] is not False: + raise SystemExit(f"{workload} service account mounts an API token") + secret = next(volume["secret"]["secretName"] for volume in pod["volumes"] if volume["name"] == "grpc-identity") + if secret != f"firemud-grpc-{workload}": + raise SystemExit(f"{workload} reused an ordinary service certificate") + require_flyway_disabled(pod["containers"][0]["args"], workload) + require_flyway_guard_negative_proof(pod["containers"][0]["args"], workload) + policy = by_kind_name[("NetworkPolicy", workload)]["spec"] + if policy["ingress"] != [] or set(policy["policyTypes"]) != {"Ingress", "Egress"}: + raise SystemExit(f"{workload} has an unexpected ingress allowance") + destination_apps = { + selector["podSelector"]["matchLabels"]["app"] + for rule in policy["egress"] + for selector in rule["to"] + if "podSelector" in selector and "app" in selector["podSelector"].get("matchLabels", {}) + } + expected = {"postgres"} | ({"game-design-service"} if service == "account" and mode == "import" else set()) + if destination_apps != expected: + raise SystemExit(f"{workload} egress targets differ: {destination_apps}") + + validate_rendered_jobs( + "tenant-migration-read-only", + migration_for("preflight", "evidence"), + (("game-design", "preflight"), ("account", "evidence")), + ) + migration = migration_for("apply", "import") + validate_rendered_jobs( + "tenant-migration-writing", + migration, + (("game-design", "apply"), ("account", "import")), + ) wrong_namespace = copy.deepcopy(migration) wrong_namespace["previewStack"]["tenantAssociationMigration"]["account"]["targetNamespace"] = "pr-999" diff --git a/k8s/helm/firemud/templates/tenant-association-account-job.yaml b/k8s/helm/firemud/templates/tenant-association-account-job.yaml index d7cc2be8a0..c609397385 100644 --- a/k8s/helm/firemud/templates/tenant-association-account-job.yaml +++ b/k8s/helm/firemud/templates/tenant-association-account-job.yaml @@ -85,6 +85,7 @@ spec: args: - -jar - /app/app.jar + - --spring.flyway.enabled=false - --spring.main.web-application-type=none - --spring.grpc.server.enabled=false - --firemud.account-tenant-migration.enabled=true diff --git a/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml b/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml index 447385a318..7d58b2a9d3 100644 --- a/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml +++ b/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml @@ -86,6 +86,7 @@ spec: args: - -jar - /app/app.jar + - --spring.flyway.enabled=false - --spring.main.web-application-type=none - --spring.grpc.server.enabled=false - --firemud.tenant-association-migration.enabled=true From efb6e943398059fb180096624dddcf68bbd7f8cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 02:52:53 +1300 Subject: [PATCH 25/28] Guard migration startup and retained admission evidence --- .../account-service/operations.md | 2 +- .../game-design-service/operations.md | 12 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../player-access-and-session.md | 4 +- .../AccountServiceApplication.java | 32 +++- .../service/impl/AccountServiceImpl.java | 127 ++++++++-------- ...account_membership_transition_receipts.sql | 14 ++ .../AccountJoinPostgresIntegrationTest.java | 111 +++++++++++--- .../AccountServiceApplicationTest.java | 85 +++++++++++ .../AccountMigrationVersionTest.java | 24 ++- .../service/impl/AccountServiceImplTest.java | 138 ++++++++++++++++++ .../GameDesignServiceApplication.java | 44 +++++- ...V30.1__canonical_game_tenant_identity.sql} | 0 .../GameDesignServiceApplicationTest.java | 87 +++++++++++ .../GameDesignMigrationVersionTest.java | 69 +++++++++ 15 files changed, 654 insertions(+), 97 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V41__protect_account_membership_transition_receipts.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountServiceApplicationTest.java rename services/game-design-service/src/main/resources/db/migration/{V30__canonical_game_tenant_identity.sql => V30.1__canonical_game_tenant_identity.sql} (100%) create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignServiceApplicationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameDesignMigrationVersionTest.java diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index e4683c8507..b4d91e3bda 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -70,7 +70,7 @@ ORDER BY legacy_source.tenant_id, legacy_source.account_id, legacy_source.member An operator first runs `evidence` for an exact positive retained numeric key in a listener-free Account job using the dedicated `account-tenant-migrator` certificate and service account. Missing or conflicting V26 source rows fail closed. The digest goes into the [Game Design approved manifest](../game-design-service/operations.md#legacy-tenant-association-migration), not into an inferred key match. After Game Design applies and reads back the signed operation, the operator runs Account `import` for the same key. That mode calls Game Design with the exact migrator mTLS identity, validates its owner response and the current V26 digest, and commits the immutable local mapping. Ordinary Account service identity cannot call this import read; the migrator cannot call the separate former-key read. An exact retry is event-free; changed owner or Account evidence is a conflict. -Deploy and independently verify the required Account schema through the normal reviewed deployment boundary, never through this Job: `evidence` needs its retained V26 source tables, and `import` additionally needs V30 association storage. Neither mode runs Flyway; the rendered Job explicitly disables it for every mode. Missing required tables or evidence fail the affected operation rather than triggering automatic schema repair. +Deploy and independently verify the required Account schema through the normal reviewed deployment boundary, never through this Job: `evidence` needs its retained V26 source tables, and `import` additionally needs V30 association storage. Neither mode runs Flyway; the rendered Job explicitly disables it for every mode, and one-shot startup requires the effective `spring.flyway.enabled` property to be explicitly `false` before refreshing the Spring context. Missing, true, or invalid values refuse startup before bean initialization; ordinary service startup retains its normal Flyway behavior. Missing required tables or evidence fail the affected operation rather than triggering automatic schema repair. When this Job is enabled, Account's scheduling configuration is absent so audit delivery, JOIN reconciliation, and credential cleanup cannot run in the migration process. The runner also fails before owner evidence or import if a `ScheduledAnnotationBeanPostProcessor` is present. diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 371e7c5020..73f94d48ce 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -28,11 +28,17 @@ The target publication boundary treats object-store export as a durable candidat ## Local Development Notes +### One-shot migration startup prerequisites + +The Entity baseline and legacy tenant-association Jobs are mutually exclusive one-shot modes. Set only the intended `FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED` or `FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED` flag. Each Job requires the effective `spring.flyway.enabled` property to be explicitly `false`; startup rejects a missing, true, or invalid value before the Spring context is refreshed. Ordinary Game Design service startup retains its normal Flyway behavior. + +Before deploying a Game Design image that includes the canonical tenant identity migration, the Game Design operator must inventory and read back Flyway history for any previously applied draft canonical-identity V30. The identity migration now runs as V30.1 after the retained V30 baseline-lock migration and before V31 associations. A history row whose version or checksum conflicts with the reviewed migration remains blocked pending an explicit database recovery decision; do not rewrite Flyway history, enable out-of-order or baseline repair, infer data, or bypass migration validation automatically. + ### Legacy tenant association migration -**Current implementation status:** V31 and the opt-in `TenantAssociationManifestJobRunner` can verify a trusted Ed25519 owner signature over a versioned, byte-length-framed manifest, compare every former Game Design key and canonical UUID with its persisted V30 source row, and store/read back the immutable operation and one-to-one associations. The job requires an exact deployment namespace, dedicated `game-design-tenant-migrator` service account and certificate, with listeners and Temporal disabled. It is not a public mutation route and ordinary startup does not import any association. Local focused verifier/gRPC/identity tests executed, and the V31 PostgreSQL test executed and passed in hosted CI on the preceding head; no real signed manifest, Job deployment, retained-row set, or live readback has been proved. +**Current implementation status:** V31 and the opt-in `TenantAssociationManifestJobRunner` can verify a trusted Ed25519 owner signature over a versioned, byte-length-framed manifest, compare every former Game Design key and canonical UUID with its persisted V30.1 source row, and store/read back the immutable operation and one-to-one associations. The job requires an exact deployment namespace, dedicated `game-design-tenant-migrator` service account and certificate, with listeners and Temporal disabled. It is not a public mutation route and ordinary startup does not import any association. Local focused verifier/gRPC/identity and startup-mode tests execute, and the Docker-free V30/V30.1/V31 uniqueness/order test passes against the service migration resources. The V31 PostgreSQL test executed and passed in hosted CI on a preceding head, but the newly composed migration sequence has not executed against PostgreSQL locally. No real signed manifest, Job deployment, retained-row set, or live readback has been proved. -For an approved operation, first obtain Account's exact retained-source evidence digest from its [Account owner migration mode](../account-service/operations.md#legacy-tenant-association-import). The Game Design owner then reviews the explicit numeric Account key, former Game Design key, V30 game row, canonical UUID, namespace, stable operation identity, and Account evidence digest; records the approval reference; and signs the canonical manifest preimage using an owner-controlled key already trusted by the migration job. A preflight verifies the signed bytes and exact namespace without writing. Only an operator-invoked `apply` with that same signed manifest and trusted public-key set writes V31; an exact retry must return the same readback and a conflicting pair fails. Account then imports from the authenticated owner read and checks its retained evidence before the membership consumer can be considered. This order does not enable the disabled runtime membership RPC. +For an approved operation, first obtain Account's exact retained-source evidence digest from its [Account owner migration mode](../account-service/operations.md#legacy-tenant-association-import). The Game Design owner then reviews the explicit numeric Account key, former Game Design key, V30.1 game row, canonical UUID, namespace, stable operation identity, and Account evidence digest; records the approval reference; and signs the canonical manifest preimage using an owner-controlled key already trusted by the migration job. A preflight verifies the signed bytes and exact namespace without writing. Only an operator-invoked `apply` with that same signed manifest and trusted public-key set writes V31; an exact retry must return the same readback and a conflicting pair fails. Account then imports from the authenticated owner read and checks its retained evidence before the membership consumer can be considered. This order does not enable the disabled runtime membership RPC. Separately deploy the reviewed V31 schema migration and independently verify its readback before `apply`; missing required storage fails application rather than triggering automatic schema repair. Neither `preflight` nor `apply` runs Flyway; the rendered Job explicitly disables it for every mode. A successful signature-and-namespace-only `preflight` does not verify database schema readiness or replace that separate readback prerequisite. @@ -50,7 +56,7 @@ Before invoking a Job, verify the exact Kubernetes context and namespace, the au The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. The chart requires the separately provisioned `firemud-game-design-baseline-reader-db` Secret for `enumerate` and `preflight`, and `firemud-game-design-baseline-writer-db` for `migrate`; both must provide `FIREMUD_POSTGRES_USER` and `FIREMUD_POSTGRES_PASSWORD`. A trusted database operator provisions these least-privilege credentials; the chart does not create them, and the Job never consumes the shared `firemud-secret` bootstrap credentials. The migration Job disables Flyway. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID and reports each scope's migration status, including `BLOCKED_DRAFT`; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, unsupported, or `BLOCKED_DRAFT`, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. It rejects a DRAFT Version before reading the Entity digest, captures the non-DRAFT Version's state epoch, then locks the Version row and requires both non-DRAFT state and the same epoch in the transaction that performs the guarded baseline update and audit insertion. A lifecycle transition during the external digest read therefore fails closed before either write, even if the Version returns to Published. This guard does not freeze authoring while the external digest is read. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. -Before enabling the Job, a trusted database operator provisions `firemud_game_design_baseline_reader` and `firemud_game_design_baseline_writer` as separate login roles with no superuser, database/role-creation, replication, bypass-RLS, inherited-role, or application-object ownership powers. Both may connect to the selected database, use `game_design_service`, and select only Game Design `version` and `publish_recorded_participant_digest`; the writer additionally needs audit-table select/insert, usage/select on `entity_digest_baseline_migration_audit_id_seq`, and column-limited update of only `applied_commit_id`, `content_digest`, and `digest_schema_version` on the baseline table. Neither role gets Entity or another service's schema access, Version or Flyway-history writes, baseline insert/delete, broad table grants, or DDL. V30 creates a Game Design-owned `SECURITY DEFINER` function that locks and reads only the exact tenant/version row for the guarded migration transaction, with public execute revoked. After V30 is applied and the restricted roles exist, the trusted database operator grants `EXECUTE` on `game_design_service.lock_version_for_entity_digest_baseline_migration(VARCHAR(36), BIGINT)` only to the writer; the reader and public roles must remain denied. This narrow call replaces direct `SELECT ... FOR UPDATE`, which requires Version UPDATE privilege even when the Job changes no Version column. Revoke broader/default grants first, then read back effective role attributes, memberships, ownership, table/column/sequence/function grants, and denied direct Version lock/update operations as the restricted users. Verify the mode-specific Secret's exact username/password authentication and both V29 and V30 presence before live activation; a rendered Secret reference is not proof of those facts. Retire both Secrets and roles after final database readback and the approved rollback window. +Before enabling the Job, a trusted database operator provisions `firemud_game_design_baseline_reader` and `firemud_game_design_baseline_writer` as separate login roles with no superuser, database/role-creation, replication, bypass-RLS, inherited-role, or application-object ownership powers. Both may connect to the selected database, use `game_design_service`, and select only Game Design `version` and `publish_recorded_participant_digest`; the writer additionally needs audit-table select/insert, usage/select on `entity_digest_baseline_migration_audit_id_seq`, and column-limited update of only `applied_commit_id`, `content_digest`, and `digest_schema_version` on the baseline table. Neither role gets Entity or another service's schema access, Version or Flyway-history writes, baseline insert/delete, broad table grants, or DDL. V30 creates a Game Design-owned `SECURITY DEFINER` function that locks and reads only the exact tenant/version row for the guarded migration transaction, with public execute revoked. After V30 is applied and the restricted roles exist, the trusted database operator grants `EXECUTE` on `game_design_service.lock_version_for_entity_digest_baseline_migration(VARCHAR(36), BIGINT)` only to the writer; the reader and public roles must remain denied. This narrow call replaces direct `SELECT ... FOR UPDATE`, which requires Version UPDATE privilege even when the Job changes no Version column. Revoke broader/default grants first, then read back effective role attributes, memberships, ownership, table/column/sequence/function grants, and denied direct Version lock/update operations as the restricted users. Verify the mode-specific Secret's exact username/password authentication and V29, V30, and V30.1 presence before live activation; a rendered Secret reference is not proof of those facts. Retire both Secrets and roles after final database readback and the approved rollback window. For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. The live row retains its original and last real publish-workflow IDs and timestamps; only the audit's operation ID and committed time describe the maintenance transition. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit and preserved publish provenance, complete old tuple, observed v2 tuple, migration operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index a4ad8de292..68e3dd2e4e 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. -The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30 assigns each retained `game` row a unique UUID with immutable row/former-key provenance, new game rows receive distinct issued UUIDs, and an Account-workload-only former-key read returns the exact persisted source tuple. The V31 addition defines a separate signed, owner-approved manifest operation for exact Account numeric-key associations. It verifies the former Game Design key, source row, and issued UUID, stores immutable one-to-one evidence, and exposes the exact approved tuple only to the dedicated Account tenant migrator, never ordinary Account or another service peer. Its opt-in chart Job uses a separate, explicitly issued and verified certificate rather than replacing Gameplay or service identities. Focused manifest, gRPC, certificate/admission, and Helm-render tests execute locally; the new PostgreSQL manifest case executed and passed in hosted CI on the preceding head. No actual manifest has been applied or read back in a deployed environment, and the Account bridge/consumer proof remains incomplete. This is not the stable `tenantSlug` catalog/selector or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain non-admitting until the owner assertion, bridge readback, and consumer proof exist. +The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30.1 assigns each retained `game` row a unique UUID with immutable row/former-key provenance after the V30 baseline-lock migration, new game rows receive distinct issued UUIDs, and an Account-workload-only former-key read returns the exact persisted source tuple. The V31 addition defines a separate signed, owner-approved manifest operation for exact Account numeric-key associations. It verifies the former Game Design key, source row, and issued UUID, stores immutable one-to-one evidence, and exposes the exact approved tuple only to the dedicated Account tenant migrator, never ordinary Account or another service peer. Its opt-in chart Job uses a separate, explicitly issued and verified certificate rather than replacing Gameplay or service identities. Focused manifest, gRPC, certificate/admission, and Helm-render tests execute locally; the new PostgreSQL manifest case executed and passed in hosted CI on a preceding head. The Docker-free V30/V30.1/V31 uniqueness/order and startup-mode regressions pass, and the combined local Account/Game Design service checks and boot-JAR packaging pass with cached/up-to-date results disclosed. Local PostgreSQL tests skip without Docker, so the newly composed database sequence and live consumer boundary remain unproved. No actual manifest has been applied or read back in a deployed environment, and the Account bridge/consumer proof remains incomplete. This is not the stable `tenantSlug` catalog/selector or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain non-admitting until the owner assertion, bridge readback, and consumer proof exist. Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 35b6995e41..6d534ed630 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -22,7 +22,7 @@ Reconnect/context persistence is partial: private retained-context replay is cur Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. -The current Unit 1B draft adds Account-owned provisional JOIN/reactivation transition receipts, separate from the canonical authority outbox. A `JOINED` recovery readback requires the matching operation, membership, receipt, and audit evidence; event-free `ALREADY_ACTIVE` requires matching positive prior receipt history. Legacy active/inactive rows without that receipt, and absent rows with retained history, fail closed rather than restart at sequence one. The receipt is not a complete authority tuple, fenced runtime snapshot, or sequence-zero absence proof. All 11 focused PostgreSQL integration cases skipped locally without Docker; their database behavior and lost-acknowledgement/concurrency remain unproved until executed. +The current Unit 1B draft adds Account-owned provisional JOIN/reactivation transition receipts, separate from the canonical authority outbox. A `JOINED` recovery readback requires the matching operation, membership, receipt, and audit evidence; event-free `ALREADY_ACTIVE` requires matching positive prior receipt history. Legacy active/inactive rows without that receipt, and absent rows with retained history, fail closed rather than restart at sequence one. Forward V41 guards receipt updates/deletes while preserving legitimate inserts and stream-head advancement; V40 remains unchanged. The receipt is not a complete authority tuple, fenced runtime snapshot, or sequence-zero absence proof. All 12 focused PostgreSQL integration cases skipped locally without Docker, including the immutability/append and retained minimized-audit negatives; their database behavior and lost-acknowledgement/concurrency remain unproved until executed. Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). @@ -70,7 +70,7 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | Incorrect currently reachable Game Session behavior | Unit 1B #2857 | This draft removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests run; composed validation below remains red and the correction is not merge-ready. | | Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | | First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | The hosted values do not supply Game Session's dedicated context-verifier secret; an unset secret makes the current parser reject before using claims. Gateway currently signs with its generic auth JWT utility, while the consumer does not yet enforce the complete target audience, recipient, lifetime, authority tuple, realm/namespace and claim-equality schema. The current Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, provision and prove matching protected signing/verification material, complete producer/consumer schema and negative predicates, and execute a hosted handshake through admission; a signed partial context or local Compose key match is not proof. | -| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | +| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | The current correction rechecks public target eligibility, membership lifecycle/admission and entitlement before returning the exact cached token; private cached replay remains denied, and no retry remints or extends a token. This is not a durable immutable issuance baseline, membership-version/generation/fence comparison, complete same-snapshot authority proof or ambiguous-ack protocol. Current Game Session runtime-read denial separately prevents replay alone from admitting gameplay. Prove those remaining issuer and consumer boundaries before admission activation; pointer-cutover retry expectations alone are not proof of current authorization. | | Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after logout, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | | Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Exact code-head CI run `36006632988` executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green; all 27 WebSocket integration cases passed, clearing the seven #2857-owned failures from the preceding run. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures repeated and block the full Validation Gate. This executed proof does not activate typed Account admission or the remaining successor contracts. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java index 5abab131d9..869208b209 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountServiceApplication.java @@ -5,6 +5,7 @@ import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Import; @@ -15,13 +16,7 @@ public class AccountServiceApplication { public static void main(String[] args) { if ("true".equals(System.getenv("FIREMUD_ACCOUNT_TENANT_MIGRATION_ENABLED"))) { requireNoSharedJwtSecret(); - SpringApplication application = new SpringApplication(AccountServiceApplication.class); - application.setWebApplicationType(WebApplicationType.NONE); - application.setDefaultProperties( - java.util.Map.of( - "spring.main.web-application-type", "none", - "spring.grpc.server.enabled", "false", - "firemud.auth.jwt-secret", oneShotJwtSecret())); + SpringApplication application = createMigrationApplication(AccountServiceApplication.class); try (ConfigurableApplicationContext ignored = application.run(args)) { // The conditional migration runner completed its one-shot evidence or import operation. } @@ -30,6 +25,29 @@ public static void main(String[] args) { } } + static SpringApplication createMigrationApplication(Class source) { + SpringApplication application = new SpringApplication(source); + application.setWebApplicationType(WebApplicationType.NONE); + application.addInitializers(requireFlywayDisabledInitializer()); + application.setDefaultProperties( + java.util.Map.of( + "spring.main.web-application-type", "none", + "spring.grpc.server.enabled", "false", + "firemud.auth.jwt-secret", oneShotJwtSecret())); + return application; + } + + private static ApplicationContextInitializer + requireFlywayDisabledInitializer() { + return context -> { + String flywayEnabled = context.getEnvironment().getProperty("spring.flyway.enabled"); + if (flywayEnabled == null || !"false".equalsIgnoreCase(flywayEnabled.trim())) { + throw new IllegalStateException( + "Account migration Job requires explicit spring.flyway.enabled=false"); + } + }; + } + private static void requireNoSharedJwtSecret() { if (System.getenv("FIREMUD_AUTH_JWT_SECRET") != null || System.getenv("FIREMUD_AUTH_JWT_SECRET_PATH") != null) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 663aa2df10..03aac99601 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1140,12 +1140,7 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR if (cachedReplay.isPresent()) { var replay = cachedReplay.orElseThrow(); if (replay.success()) { - RuntimeRealmTarget currentRealm = requireCurrentConnectScopeTarget(scopeContext); - if (!isPublicProductionRealm(currentRealm)) { - throw new AuthenticationException( - "REALM_ACCESS_DENIED", - "The selected non-public realm does not have an active access grant"); - } + requireCurrentConnectTokenEligibility(bootstrapContext, scopeContext, request, true); logger.info( "Replayed connect-token attempt for account {} tenant {} world {} realm {} requestId {}", bootstrapContext.accountId(), @@ -1187,58 +1182,8 @@ private ConnectTokenResult issueConnectTokenFresh( BootstrapContext bootstrapContext, ConnectScopeContext scopeContext, ConnectTokenRequest request) { - RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(scopeContext.tenantId(), request.requestId()); - if (!entitlements.gameplayAvailable()) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - RuntimeMembershipDto membership = - getTenantMembershipForRuntime( - bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); - - if (membership.membershipExists() - && !"ACTIVE".equals(membership.membershipLifecycleState()) - && !"INACTIVE".equals(membership.membershipLifecycleState())) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); - } - if (membership.membershipExists() - && "INACTIVE".equals(membership.membershipLifecycleState()) - && isPublicProductionRealm(realm)) { - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - if (membership.membershipExists() && "INACTIVE".equals(membership.membershipLifecycleState())) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } - if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } - - if (!membership.membershipExists()) { - if (!isPublicProductionRealm(realm)) { - throw new AuthenticationException( - "NON_PUBLIC_ENROLLMENT_REQUIRED", - "Existing game membership is required for this non-public realm"); - } - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - + RuntimeRealmTarget realm = + requireCurrentConnectTokenEligibility(bootstrapContext, scopeContext, request, false); if (!isPublicProductionRealm(realm) && !hasRealmAccessGrant( bootstrapContext.accountId(), @@ -1325,6 +1270,72 @@ && isPublicProductionRealm(realm)) { return result; } + private RuntimeRealmTarget requireCurrentConnectTokenEligibility( + BootstrapContext bootstrapContext, + ConnectScopeContext scopeContext, + ConnectTokenRequest request, + boolean cachedSuccessReplay) { + RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); + boolean publicProductionRealm = isPublicProductionRealm(realm); + if (cachedSuccessReplay && !publicProductionRealm) { + throw new AuthenticationException( + "REALM_ACCESS_DENIED", + "The selected non-public realm does not have an active access grant"); + } + + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(scopeContext.tenantId(), request.requestId()); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + RuntimeMembershipDto membership = + getTenantMembershipForRuntime( + bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); + + if (membership.membershipExists() + && !"ACTIVE".equals(membership.membershipLifecycleState()) + && !"INACTIVE".equals(membership.membershipLifecycleState())) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); + } + if (membership.membershipExists() + && "INACTIVE".equals(membership.membershipLifecycleState()) + && publicProductionRealm) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } + if (membership.membershipExists() && "INACTIVE".equals(membership.membershipLifecycleState())) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); + } + if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); + } + + if (!membership.membershipExists()) { + if (!publicProductionRealm) { + throw new AuthenticationException( + "NON_PUBLIC_ENROLLMENT_REQUIRED", + "Existing game membership is required for this non-public realm"); + } + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } + return realm; + } + @Override @Transactional(readOnly = true) @Timed(value = "account.runtime_membership") diff --git a/services/account-service/src/main/resources/db/migration/V41__protect_account_membership_transition_receipts.sql b/services/account-service/src/main/resources/db/migration/V41__protect_account_membership_transition_receipts.sql new file mode 100644 index 0000000000..90937be90e --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V41__protect_account_membership_transition_receipts.sql @@ -0,0 +1,14 @@ +-- JOIN transition receipts are retained recovery evidence and may only be appended. +-- The independent stream head remains mutable so legitimate receipt appends can advance it. +-- [jooq ignore start] +CREATE FUNCTION reject_account_membership_transition_receipt_mutation() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Account membership transition receipts are append-only' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_membership_transition_receipts_append_only + BEFORE UPDATE OR DELETE ON account_membership_transition_receipts + FOR EACH ROW EXECUTE FUNCTION reject_account_membership_transition_receipt_mutation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index b3c09f1bd5..6f052cf92b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -361,39 +361,110 @@ void committedMembershipTransitionReceiptHistorySurvivesAbsenceOfCurrentMembersh } @Test - void absentMembershipWithPriorAuditHistoryCannotRestartAtSequenceOne() { + void membershipTransitionReceiptsRejectMutationAndStillAllowAppendAndStreamAdvance() { JoinFixture initialJoin = fixture("active"); assertThat(join(initialJoin).success()).isTrue(); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + + assertThrows( + org.jooq.exception.DataAccessException.class, + () -> + dsl.execute( + "UPDATE account_membership_transition_receipts " + + "SET transition_type = 'MEMBERSHIP_REACTIVATED' " + + "WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId())); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + + assertThrows( + org.jooq.exception.DataAccessException.class, + () -> + dsl.execute( + "DELETE FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId())); + assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + assertThat( + dsl.resultQuery( + "SELECT last_receipt_sequence " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + dsl.execute( - "DELETE FROM account_membership_transition_receipts WHERE account_id = ? AND tenant_id = ?", - initialJoin.accountId(), - initialJoin.tenantId()); - dsl.execute( - "DELETE FROM account_membership_transition_receipt_stream_heads " - + "WHERE account_id = ? AND tenant_id = ?", - initialJoin.accountId(), - initialJoin.tenantId()); - dsl.execute( - "DELETE FROM account_join_operations WHERE request_id = ?", initialJoin.requestId()); - dsl.execute( - "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + + "gameplay_admission_allowed = FALSE WHERE account_id = ? AND tenant_id = ?", initialJoin.accountId(), initialJoin.tenantId()); - JoinFixture retry = fixtureForMembership(initialJoin); + JoinFixture reactivation = fixtureForMembership(initialJoin); - AuthenticationException blocked = - assertThrows(AuthenticationException.class, () -> join(retry)); + assertThat(join(reactivation).success()).isTrue(); + assertMembershipTransitionReceipt(reactivation, "MEMBERSHIP_REACTIVATED", 2L); + assertThat(countMembershipTransitionReceipts(reactivation)).isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT last_receipt_sequence " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + reactivation.accountId(), + reactivation.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(2L); + } + + @Test + void minimizedPriorJoinAuditWithoutMembershipOrReceiptKeepsJoinRetryable() { + JoinFixture retry = fixture("active"); + dsl.execute( + "INSERT INTO account_audit_outbox " + + "(audit_event_id, scope, tenant_id, producer_service, event_type, occurred_at, " + + "schema_version, payload_digest_version, payload_digest, payload, delivery_status, " + + "next_attempt_at) " + + "VALUES (?, 'tenant', ?, 'account-service', " + + "'ACCOUNT_JOINED_PUBLIC_PRODUCTION', CURRENT_TIMESTAMP, 1, 1, ?, NULL, 'MINIMIZED', NULL)", + UUID.randomUUID(), + retry.tenantId(), + "sha256:" + "0".repeat(64)); + + for (int attempt = 0; attempt < 2; attempt++) { + AuthenticationException blocked = + assertThrows(AuthenticationException.class, () -> join(retry)); + assertThat(blocked.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + } - assertThat(blocked.getCode()).isEqualTo("AUTH_UNAVAILABLE"); assertThat(countMemberships(retry)).isZero(); assertThat(countMembershipTransitionReceipts(retry)).isZero(); + assertThat(countJoinOutbox(retry)).isZero(); assertThat(countTenantJoinOutboxEvents(retry)).isEqualTo(1L); assertThat( dsl.resultQuery( - "SELECT status FROM account_join_operations WHERE request_id = ?", + "SELECT status, last_attempt_failure_code FROM account_join_operations " + + "WHERE request_id = ?", retry.requestId()) - .fetchOne(0, String.class)) - .isEqualTo("PENDING"); + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("last_attempt_failure_code", String.class)) + .isEqualTo("AUTH_UNAVAILABLE"); + }); + assertThat( + dsl.resultQuery( + "SELECT delivery_status, payload FROM account_audit_outbox " + + "WHERE scope = 'tenant' AND tenant_id = ? " + + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + retry.tenantId()) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("delivery_status", String.class)).isEqualTo("MINIMIZED"); + assertThat(row.get("payload", String.class)).isNull(); + }); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountServiceApplicationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountServiceApplicationTest.java new file mode 100644 index 0000000000..2ef2377d62 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountServiceApplicationTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.accountservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +class AccountServiceApplicationTest { + private static final AtomicInteger BEAN_INITIALIZATIONS = new AtomicInteger(); + private static final AtomicInteger MIGRATION_SIDE_EFFECTS = new AtomicInteger(); + + @BeforeEach + void resetStartupEffects() { + BEAN_INITIALIZATIONS.set(0); + MIGRATION_SIDE_EFFECTS.set(0); + } + + @Test + void oneShotStartupRejectsMissingFlywaySettingBeforeBeanOrMigrationInitialization() { + var application = + AccountServiceApplication.createMigrationApplication(StartupProbeConfiguration.class); + + assertThrows( + IllegalStateException.class, + () -> + application.run( + "--spring.config.location=optional:classpath:/missing-account-test.yml")); + + assertEquals(0, BEAN_INITIALIZATIONS.get()); + assertEquals(0, MIGRATION_SIDE_EFFECTS.get()); + } + + @Test + void oneShotStartupRejectsEnabledOrInvalidFlywaySettingBeforeInitialization() { + for (String value : new String[] {"true", "enabled"}) { + resetStartupEffects(); + var application = + AccountServiceApplication.createMigrationApplication(StartupProbeConfiguration.class); + + assertThrows( + IllegalStateException.class, + () -> + application.run( + "--spring.config.location=optional:classpath:/missing-account-test.yml", + "--spring.flyway.enabled=" + value)); + + assertEquals(0, BEAN_INITIALIZATIONS.get()); + assertEquals(0, MIGRATION_SIDE_EFFECTS.get()); + } + } + + @Test + void explicitFlywayFalseAllowsOneShotStartupInitialization() { + var application = + AccountServiceApplication.createMigrationApplication(StartupProbeConfiguration.class); + + try (var ignored = + application.run( + "--spring.config.location=optional:classpath:/missing-account-test.yml", + "--spring.flyway.enabled=false")) { + assertEquals(2, BEAN_INITIALIZATIONS.get()); + assertEquals(1, MIGRATION_SIDE_EFFECTS.get()); + } + } + + @Configuration(proxyBeanMethods = false) + static class StartupProbeConfiguration { + @Bean + Object beanInitializationProbe() { + BEAN_INITIALIZATIONS.incrementAndGet(); + return new Object(); + } + + @Bean + ApplicationRunner migrationProbe() { + BEAN_INITIALIZATIONS.incrementAndGet(); + return args -> MIGRATION_SIDE_EFFECTS.incrementAndGet(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java index 3782153a6a..fa52c73c14 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java @@ -28,7 +28,8 @@ void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws "V28__account_audit_delivery_backoff.sql", "V37__verified_audit_projection_evidence.sql", "V38__account_join_reconciliation.sql", - "V40__account_membership_transition_receipts.sql") + "V40__account_membership_transition_receipts.sql", + "V41__protect_account_membership_transition_receipts.sql") .doesNotContain( "V28__account_join_reconciliation.sql", "V28__account_membership_transition_receipts.sql", @@ -41,6 +42,27 @@ void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws assertThat(version("V40__account_membership_transition_receipts.sql")) .isGreaterThan(version("V38__account_join_reconciliation.sql")) .isGreaterThan(MigrationVersion.fromVersion("39.1")); + assertThat(version("V41__protect_account_membership_transition_receipts.sql")) + .isGreaterThan(version("V40__account_membership_transition_receipts.sql")); + } + + @Test + void receiptProtectionMigrationGuardsOnlyUpdatesAndDeletesWithoutDocker() throws IOException { + String migration = + Files.readString( + Path.of( + "src/main/resources/db/migration/" + + "V41__protect_account_membership_transition_receipts.sql")); + + assertThat(migration) + .contains( + "CREATE TRIGGER account_membership_transition_receipts_append_only", + "BEFORE UPDATE OR DELETE ON account_membership_transition_receipts", + "EXECUTE FUNCTION reject_account_membership_transition_receipt_mutation()") + .doesNotContain( + "BEFORE INSERT ON account_membership_transition_receipts", + "INSERT OR UPDATE OR DELETE ON account_membership_transition_receipts", + "ON account_membership_transition_receipt_stream_heads"); } private static MigrationVersion version(String name) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index e0925ee8bc..a94d0254cc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -3893,6 +3893,7 @@ void issueConnectTokenReplaysSameTokenWhenPublicScopeStillMatchesPointer() { when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, firstResult, "", ""))); + org.mockito.Mockito.clearInvocations(sessionService); ConnectTokenResult replayed = service.issueConnectToken( @@ -3903,6 +3904,20 @@ void issueConnectTokenReplaysSameTokenWhenPublicScopeStillMatchesPointer() { assertEquals(firstResult.expiresAt(), replayed.expiresAt()); assertEquals(firstResult.requestId(), replayed.requestId()); assertTrue(replayed.replayed()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), + org.mockito.ArgumentMatchers.anyLong()); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( @@ -3923,6 +3938,7 @@ void issueConnectTokenReplaysSameTokenWhenPublicScopeStillMatchesPointer() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build()); + org.mockito.Mockito.clearInvocations(sessionService); AuthenticationException staleReplayException = assertThrows( @@ -3933,6 +3949,79 @@ void issueConnectTokenReplaysSameTokenWhenPublicScopeStillMatchesPointer() { new ConnectTokenRequest(connectScopeId, "req-replay-1"))); assertEquals("ADMISSION_POINTER_UNAVAILABLE", staleReplayException.getCode()); + verifyCachedConnectTokenReplayDidNotWrite(); + } + + @ParameterizedTest + @CsvSource({ + "MISSING,JOIN_REQUIRED", + "INACTIVE,JOIN_REQUIRED", + "NON_ADMITTING,CONNECT_TOKEN_REJECTED" + }) + void issueConnectTokenRevalidatesMembershipBeforeCachedSuccessReplay( + String currentMembershipState, String expectedCode) { + CachedPublicConnectTokenReplay cached = prepareCachedPublicConnectTokenReplay(); + if ("MISSING".equals(currentMembershipState)) { + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + } else { + Account account = new Account(); + account.setId(11L); + AccountTenantMembership currentMembership = membership(account, 7L); + if ("INACTIVE".equals(currentMembershipState)) { + currentMembership.setLifecycleState("INACTIVE"); + currentMembership.setGameplayAdmissionAllowed(false); + } else { + currentMembership.setGameplayAdmissionAllowed(false); + } + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(currentMembership)); + } + org.mockito.Mockito.clearInvocations(accountTenantMembershipRepository); + org.mockito.Mockito.clearInvocations(sessionService); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + cached.bootstrapToken(), + new ConnectTokenRequest(cached.connectScopeId(), cached.requestId()))); + + assertEquals(expectedCode, exception.getCode()); + verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); + verifyCachedConnectTokenReplayDidNotWrite(); + } + + @ParameterizedTest + @CsvSource({"BLOCKED,TENANT_BILLING_BLOCKED", "UNAVAILABLE,ENTITLEMENT_UNAVAILABLE"}) + void issueConnectTokenRevalidatesEntitlementBeforeCachedSuccessReplay( + String currentEntitlementState, String expectedCode) { + CachedPublicConnectTokenReplay cached = prepareCachedPublicConnectTokenReplay(); + if ("BLOCKED".equals(currentEntitlementState)) { + Subscription canceled = new Subscription(); + canceled.setId(22L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + } else { + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + } + org.mockito.Mockito.clearInvocations(accountTenantMembershipRepository); + org.mockito.Mockito.clearInvocations(sessionService); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + cached.bootstrapToken(), + new ConnectTokenRequest(cached.connectScopeId(), cached.requestId()))); + + assertEquals(expectedCode, exception.getCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .findByAccountIdAndTenantId(11L, 7L); + verifyCachedConnectTokenReplayDidNotWrite(); } @Test @@ -6837,6 +6926,55 @@ private void verifyConnectTokenFailureDoesNotStoreSuccess( org.mockito.ArgumentMatchers.longThat(ttl -> ttl > 0L)); } + private CachedPublicConnectTokenReplay prepareCachedPublicConnectTokenReplay() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + String requestId = "req-cached-current-authority"; + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, requestId); + ConnectTokenResult storedResult = + service.issueConnectToken(bootstrap.bootstrapToken(), request); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, requestId)) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, storedResult, "", ""))); + return new CachedPublicConnectTokenReplay( + bootstrap.bootstrapToken(), connectScopeId, requestId); + } + + private void verifyCachedConnectTokenReplayDidNotWrite() { + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), + org.mockito.ArgumentMatchers.anyLong()); + } + + private record CachedPublicConnectTokenReplay( + String bootstrapToken, String connectScopeId, String requestId) {} + private record PrivateConnectTokenContext(String bootstrapToken, String connectScopeId) {} private DirectTextJoinScope issueDirectTextConnectScopeForTest() { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java index 61c8366c8e..346e38e895 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java @@ -5,6 +5,7 @@ import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Import; @@ -13,10 +14,15 @@ @Import(GlobalExceptionHandler.class) public class GameDesignServiceApplication { public static void main(String[] args) { - if (oneShotMigrationRequested()) { + MigrationMode migrationMode = + selectMigrationMode( + System.getenv("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED"), + System.getenv("FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED")); + if (migrationMode != MigrationMode.NORMAL) { requireNoSharedJwtSecret(); SpringApplication application = new SpringApplication(GameDesignServiceApplication.class); application.setWebApplicationType(WebApplicationType.NONE); + application.addInitializers(new RequireFlywayDisabledInitializer()); application.setDefaultProperties( java.util.Map.of( "spring.main.web-application-type", "none", @@ -33,9 +39,39 @@ public static void main(String[] args) { } } - private static boolean oneShotMigrationRequested() { - return "true".equals(System.getenv("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED")) - || "true".equals(System.getenv("FIREMUD_TENANT_ASSOCIATION_MIGRATION_ENABLED")); + static MigrationMode selectMigrationMode(String entityBaseline, String tenantAssociation) { + boolean entityBaselineEnabled = "true".equals(entityBaseline); + boolean tenantAssociationEnabled = "true".equals(tenantAssociation); + if (entityBaselineEnabled && tenantAssociationEnabled) { + throw new IllegalStateException( + "Game Design one-shot migration modes cannot be enabled together"); + } + if (entityBaselineEnabled) { + return MigrationMode.ENTITY_BASELINE; + } + if (tenantAssociationEnabled) { + return MigrationMode.TENANT_ASSOCIATION; + } + return MigrationMode.NORMAL; + } + + enum MigrationMode { + NORMAL, + ENTITY_BASELINE, + TENANT_ASSOCIATION + } + + static final class RequireFlywayDisabledInitializer + implements ApplicationContextInitializer { + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + String flywayEnabled = + applicationContext.getEnvironment().getProperty("spring.flyway.enabled"); + if (!"false".equalsIgnoreCase(flywayEnabled)) { + throw new IllegalStateException( + "Game Design one-shot migration Jobs require spring.flyway.enabled=false explicitly"); + } + } } private static void requireNoSharedJwtSecret() { diff --git a/services/game-design-service/src/main/resources/db/migration/V30__canonical_game_tenant_identity.sql b/services/game-design-service/src/main/resources/db/migration/V30.1__canonical_game_tenant_identity.sql similarity index 100% rename from services/game-design-service/src/main/resources/db/migration/V30__canonical_game_tenant_identity.sql rename to services/game-design-service/src/main/resources/db/migration/V30.1__canonical_game_tenant_identity.sql diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignServiceApplicationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignServiceApplicationTest.java new file mode 100644 index 0000000000..f363a7aa74 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignServiceApplicationTest.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +class GameDesignServiceApplicationTest { + private static final AtomicInteger MIGRATION_SIDE_EFFECTS = new AtomicInteger(); + + @BeforeEach + void resetMigrationSideEffect() { + MIGRATION_SIDE_EFFECTS.set(0); + } + + @Test + void selectsOneShotModesIndependentlyAndRejectsBothTogether() { + assertThat(GameDesignServiceApplication.selectMigrationMode("true", null)) + .isEqualTo(GameDesignServiceApplication.MigrationMode.ENTITY_BASELINE); + assertThat(GameDesignServiceApplication.selectMigrationMode(null, "true")) + .isEqualTo(GameDesignServiceApplication.MigrationMode.TENANT_ASSOCIATION); + assertThat(GameDesignServiceApplication.selectMigrationMode(null, null)) + .isEqualTo(GameDesignServiceApplication.MigrationMode.NORMAL); + + assertThatThrownBy(() -> GameDesignServiceApplication.selectMigrationMode("true", "true")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot be enabled together"); + } + + @Test + void missingFlywaySettingStopsBeforeBeanMigrationSideEffect() { + assertThatThrownBy(() -> startOneShotApplication()) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Game Design one-shot migration Jobs require spring.flyway.enabled=false explicitly"); + + assertThat(MIGRATION_SIDE_EFFECTS).hasValue(0); + } + + @Test + void explicitFalseAllowsApplicationInitialization() { + try (ConfigurableApplicationContext context = + startOneShotApplication("--spring.flyway.enabled=false")) { + assertThat(context.isActive()).isTrue(); + assertThat(MIGRATION_SIDE_EFFECTS).hasValue(1); + } + } + + @Test + void trueOrInvalidFlywaySettingStopsBeforeBeanMigrationSideEffect() { + for (String setting : new String[] {"true", "invalid"}) { + assertThatThrownBy(() -> startOneShotApplication("--spring.flyway.enabled=" + setting)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Game Design one-shot migration Jobs require spring.flyway.enabled=false explicitly"); + assertThat(MIGRATION_SIDE_EFFECTS).hasValue(0); + } + } + + private static ConfigurableApplicationContext startOneShotApplication(String... args) { + SpringApplication application = new SpringApplication(SideEffectConfiguration.class); + application.setWebApplicationType(WebApplicationType.NONE); + application.setLogStartupInfo(false); + application.addInitializers( + new GameDesignServiceApplication.RequireFlywayDisabledInitializer()); + String[] isolatedArgs = new String[args.length + 1]; + isolatedArgs[0] = "--spring.config.location=optional:classpath:/missing-game-design-test.yml"; + System.arraycopy(args, 0, isolatedArgs, 1, args.length); + return application.run(isolatedArgs); + } + + @Configuration(proxyBeanMethods = false) + static class SideEffectConfiguration { + @Bean + Object migrationSideEffect() { + MIGRATION_SIDE_EFFECTS.incrementAndGet(); + return new Object(); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameDesignMigrationVersionTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameDesignMigrationVersionTest.java new file mode 100644 index 0000000000..be412f3071 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameDesignMigrationVersionTest.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; + +class GameDesignMigrationVersionTest { + private static final Pattern VERSIONED_MIGRATION = Pattern.compile("^V([^_]+)__.*\\.sql$"); + + @Test + void migrationVersionsAreUniqueAndTenantIdentityFollowsBaselineLockBeforeAssociations() + throws Exception { + List versions = allMigrationVersions(); + MigrationVersion baselineLock = + migrationVersion("V30__restricted_entity_digest_baseline_version_lock.sql"); + MigrationVersion canonicalIdentity = + migrationVersion("V30.1__canonical_game_tenant_identity.sql"); + MigrationVersion associations = + migrationVersion("V31__approved_legacy_account_tenant_associations.sql"); + + assertThat(versions).doesNotHaveDuplicates(); + assertThat(versions).contains(baselineLock, canonicalIdentity, associations); + assertThat(baselineLock).isEqualTo(MigrationVersion.fromVersion("30")); + assertThat(baselineLock).isLessThan(canonicalIdentity); + assertThat(canonicalIdentity).isLessThan(associations); + + // Flyway considers both former V30 filenames the same version, so they cannot coexist. + assertThat(migrationVersion("V30__canonical_game_tenant_identity.sql")).isEqualTo(baselineLock); + } + + private static List allMigrationVersions() throws Exception { + Path migrationDirectory = migrationDirectory(); + try (Stream files = Files.list(migrationDirectory)) { + return files + .map(path -> Objects.requireNonNull(path.getFileName()).toString()) + .filter(name -> VERSIONED_MIGRATION.matcher(name).matches()) + .map(GameDesignMigrationVersionTest::migrationVersion) + .toList(); + } + } + + private static MigrationVersion migrationVersion(String filename) { + Matcher matcher = VERSIONED_MIGRATION.matcher(filename); + if (!matcher.matches()) { + throw new IllegalArgumentException("Not a versioned Flyway migration: " + filename); + } + return MigrationVersion.fromVersion(matcher.group(1)); + } + + private static Path migrationDirectory() throws URISyntaxException { + return Path.of( + Objects.requireNonNull( + GameDesignMigrationVersionTest.class + .getClassLoader() + .getResource("db/migration/V30.1__canonical_game_tenant_identity.sql"), + "Missing canonical Game Design tenant-identity migration resource") + .toURI()) + .getParent(); + } +} From 6c22279fec84636653d5b38b37505747651a7c18 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 05:44:21 +1300 Subject: [PATCH 26/28] Scope tenant association migration database credentials by mode --- .../account-service/operations.md | 4 + .../game-design-service/operations.md | 4 + ...ame-authoring-publishing-and-activation.md | 2 + ...m-tenant-association-migration-contract.sh | 42 ++++++ .../tenant-association-account-job.yaml | 10 +- .../tenant-association-game-design-job.yaml | 10 +- k8s/helm/firemud/values.yaml | 2 + ...egacyTenantAssociationImportJobRunner.java | 55 +++++++- ...yTenantAssociationImportJobRunnerTest.java | 122 ++++++++++++++++- .../TenantAssociationManifestJobRunner.java | 51 ++++++- ...enantAssociationManifestJobRunnerTest.java | 124 ++++++++++++++++++ 11 files changed, 417 insertions(+), 9 deletions(-) diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index b4d91e3bda..3a7fea7392 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -72,6 +72,10 @@ An operator first runs `evidence` for an exact positive retained numeric key in Deploy and independently verify the required Account schema through the normal reviewed deployment boundary, never through this Job: `evidence` needs its retained V26 source tables, and `import` additionally needs V30 association storage. Neither mode runs Flyway; the rendered Job explicitly disables it for every mode, and one-shot startup requires the effective `spring.flyway.enabled` property to be explicitly `false` before refreshing the Spring context. Missing, true, or invalid values refuse startup before bean initialization; ordinary service startup retains its normal Flyway behavior. Missing required tables or evidence fail the affected operation rather than triggering automatic schema repair. +Each mode requires its own fixed database Secret and authenticated PostgreSQL role: `evidence` uses `firemud-account-tenant-evidence-db` as `firemud_account_tenant_evidence`, and `import` uses `firemud-account-tenant-import-db` as `firemud_account_tenant_import`. Both roles may connect only to the selected database and use `account_service`; the evidence role receives only `SELECT` on the queried columns of `account_legacy_tenant_sources`, `account_legacy_membership_sources`, and `account_legacy_profile_sources`. The import role receives those same source reads plus only the required `SELECT` and `INSERT` on queried association columns in `account_approved_legacy_tenant_associations`. Neither mode needs `UPDATE`, `DELETE`, sequence, DDL, or lock-function privileges. These credentials are separately provisioned operator inputs, not shared bootstrap, application, or baseline credentials; a missing mode Secret must fail closed, with no optional fallback or chart-created credential. This follows the [Secret Delivery Boundary](../../system-architecture-security.md#secret-delivery-boundary) and [per-service migration ownership](../../system-architecture-database-migrations.md#per-service-organization). + +Before enabling the ordinary-disabled Job, the trusted database operator must provision each role without `SUPERUSER`, `CREATEDB`, `CREATEROLE`, `REPLICATION`, or `BYPASSRLS`, ensure it is not `INHERIT` and has no inherited role memberships, and grant no application-object ownership or unrelated-schema access. Independently read back effective memberships, required grants and prohibited grants, and verify that each Secret-authenticated connection is the exact expected role. Retire the scoped role and Secret after the operation and its recovery window. A rendered Job, Helm check, or role-name assertion is not live grant, Secret-authentication, or PostgreSQL readback proof. + When this Job is enabled, Account's scheduling configuration is absent so audit delivery, JOIN reconciliation, and credential cleanup cannot run in the migration process. The runner also fails before owner evidence or import if a `ScheduledAnnotationBeanPostProcessor` is present. The chart's `previewStack.tenantAssociationMigration.account` values are disabled by default. From a trusted operator revision, supply the exact namespace, a reviewed immutable Account image digest, mode (`evidence` or `import`), positive numeric key, and stable run ID; do not leave the Job enabled for ordinary upgrades. The dedicated `firemud-grpc-account-tenant-migrator` Secret must be issued and verified explicitly using `ensure-standalone-transport-certificates.sh --account-tenant-migrator` and `--verify-account-tenant-migrator` before enabling the Job. The Secret is stable and reused, not requested on every deployment; the Job has no Kubernetes API token, no ingress, and only DNS/Postgres egress plus Game Design gRPC for `import`. A rendered Job or successful completion alone is not database or served-mTLS proof. Retain the operation/readback evidence privately, disable the Job after use, and retire the exact certificate and Secret through the trusted operator boundary. Live Job, PostgreSQL, cross-service, and membership consumer proof remain open; an import cannot be treated as a JOIN, a sequence-zero stream checkpoint, or a working runtime membership RPC. diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 73f94d48ce..63de588fa5 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -42,6 +42,10 @@ For an approved operation, first obtain Account's exact retained-source evidence Separately deploy the reviewed V31 schema migration and independently verify its readback before `apply`; missing required storage fails application rather than triggering automatic schema repair. Neither `preflight` nor `apply` runs Flyway; the rendered Job explicitly disables it for every mode. A successful signature-and-namespace-only `preflight` does not verify database schema readiness or replace that separate readback prerequisite. +Each mode requires its own fixed database Secret and authenticated PostgreSQL role: `preflight` uses `firemud-game-design-tenant-preflight-db` as `firemud_game_design_tenant_preflight`, and `apply` uses `firemud-game-design-tenant-apply-db` as `firemud_game_design_tenant_apply`. Both roles may connect only to the selected database; only `apply` may use `game_design_service`. `preflight` verifies the signature and exact namespace only; it performs no owner-table SQL and must not receive schema or table grants. `apply` receives only `SELECT` on the required identity/provenance columns of the Game Design `game` source table and `SELECT`/`INSERT` on the required operation and association fields in `legacy_account_tenant_association_operations` and `legacy_account_tenant_associations`. Neither mode needs `UPDATE`, `DELETE`, sequence, DDL, or lock-function privileges. These credentials are separately provisioned operator inputs, not shared bootstrap, application, or baseline credentials; a missing mode Secret must fail closed, with no optional fallback or chart-created credential. This follows the [Secret Delivery Boundary](../../system-architecture-security.md#secret-delivery-boundary) and [per-service migration ownership](../../system-architecture-database-migrations.md#per-service-organization). + +Before enabling the ordinary-disabled Job, the trusted database operator must provision each role without `SUPERUSER`, `CREATEDB`, `CREATEROLE`, `REPLICATION`, or `BYPASSRLS`, ensure it is not `INHERIT` and has no inherited role memberships, and grant no application-object ownership or unrelated-schema access. Independently read back effective memberships, required grants and prohibited grants, and verify that each Secret-authenticated connection is the exact expected role. Retire the scoped role and Secret after the operation and its recovery window. A rendered Job, Helm check, or role-name assertion is not live grant, Secret-authentication, or PostgreSQL readback proof. + The chart's `previewStack.tenantAssociationMigration.gameDesign` values are disabled by default. A trusted operator supplies an immutable Game Design image digest, exact namespace, stable run ID, mode, signed-manifest Secret and trusted-key Secret. Explicitly issue and verify the stable `firemud-grpc-game-design-tenant-migrator` identity using `ensure-standalone-transport-certificates.sh --game-design-tenant-migrator` and `--verify-game-design-tenant-migrator` before enabling the Job; the ordinary Game Design certificate is not a fallback. This dedicated certificate is a workload attestation guard, not an outbound owner-read credential. The Job has no Kubernetes API token or ingress and only DNS/Postgres egress; no ordinary Helm release creates it. Disable the Job after use and retire its exact certificate and Secret through the trusted operator boundary. A rendered Job is not executed migration proof: the live certificate, trusted Secrets, actual manifest, PostgreSQL readback and Account import still require deployment proof. Do not describe this path as an applied data migration until those checks execute. ### Historical Entity digest baseline migration diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 68e3dd2e4e..ab338d4b7b 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -10,6 +10,8 @@ This tracker consolidates Game Design authoring, settings, publication, release The current Unit 1B child adds a Game Design owner-local tenant UUID source: V30.1 assigns each retained `game` row a unique UUID with immutable row/former-key provenance after the V30 baseline-lock migration, new game rows receive distinct issued UUIDs, and an Account-workload-only former-key read returns the exact persisted source tuple. The V31 addition defines a separate signed, owner-approved manifest operation for exact Account numeric-key associations. It verifies the former Game Design key, source row, and issued UUID, stores immutable one-to-one evidence, and exposes the exact approved tuple only to the dedicated Account tenant migrator, never ordinary Account or another service peer. Its opt-in chart Job uses a separate, explicitly issued and verified certificate rather than replacing Gameplay or service identities. Focused manifest, gRPC, certificate/admission, and Helm-render tests execute locally; the new PostgreSQL manifest case executed and passed in hosted CI on a preceding head. The Docker-free V30/V30.1/V31 uniqueness/order and startup-mode regressions pass, and the combined local Account/Game Design service checks and boot-JAR packaging pass with cached/up-to-date results disclosed. Local PostgreSQL tests skip without Docker, so the newly composed database sequence and live consumer boundary remain unproved. No actual manifest has been applied or read back in a deployed environment, and the Account bridge/consumer proof remains incomplete. This is not the stable `tenantSlug` catalog/selector or a completed Account/Game Session membership snapshot. Retained Account tenant rows remain non-admitting until the owner assertion, bridge readback, and consumer proof exist. +The opt-in migration Jobs require separately provisioned, mode-specific database Secrets and least-privilege PostgreSQL identities as described in [Account operations](../../architecture/microservices/account-service/operations.md#legacy-tenant-association-import) and [Game Design operations](../../architecture/microservices/game-design-service/operations.md#legacy-tenant-association-migration). Existing Helm, role-name, certificate, and focused startup proof does not establish live effective grants or the role authenticated through each Secret; operator readback and deployed operation evidence remain outstanding. + Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. diff --git a/dev-tools/tests/helm-tenant-association-migration-contract.sh b/dev-tools/tests/helm-tenant-association-migration-contract.sh index 5bc50fe26e..36bbac8f71 100644 --- a/dev-tools/tests/helm-tenant-association-migration-contract.sh +++ b/dev-tools/tests/helm-tenant-association-migration-contract.sh @@ -69,6 +69,46 @@ with tempfile.TemporaryDirectory() as directory: continue raise SystemExit(f"{workload} Flyway check accepted a missing or enabled property") + database_secrets = { + ("account", "evidence"): "firemud-account-tenant-evidence-db", + ("account", "import"): "firemud-account-tenant-import-db", + ("game-design", "preflight"): "firemud-game-design-tenant-preflight-db", + ("game-design", "apply"): "firemud-game-design-tenant-apply-db", + } + + def require_database_credentials(container, service, mode): + if container.get("envFrom"): + raise SystemExit("migration must not import an unrestricted credential bundle") + expected_secret = database_secrets[(service, mode)] + for key in ("FIREMUD_POSTGRES_USER", "FIREMUD_POSTGRES_PASSWORD"): + entries = [entry for entry in container["env"] if entry["name"] == key] + expected = { + "name": key, + "valueFrom": { + "secretKeyRef": {"name": expected_secret, "key": key, "optional": False}, + }, + } + if entries != [expected]: + raise SystemExit(f"{service}/{mode} must require its dedicated {key} Secret key") + + def require_database_guard_negative_proof(container, service, mode): + for replacement in ( + {"name": "firemud-secret", "key": "FIREMUD_POSTGRES_USER", "optional": False}, + {"name": "firemud-game-design-baseline-writer-db", "key": "FIREMUD_POSTGRES_USER", "optional": False}, + {"name": database_secrets[(service, mode)], "key": "PASSWORD", "optional": False}, + {"name": database_secrets[(service, mode)], "key": "FIREMUD_POSTGRES_USER", "optional": True}, + {"name": database_secrets[(service, mode)], "key": "FIREMUD_POSTGRES_USER"}, + None, + ): + invalid = copy.deepcopy(container) + credential = next(entry for entry in invalid["env"] if entry["name"] == "FIREMUD_POSTGRES_USER") + credential["valueFrom"]["secretKeyRef"] = replacement + try: + require_database_credentials(invalid, service, mode) + except SystemExit: + continue + raise SystemExit(f"{service}/{mode} credential guard accepted {replacement}") + disabled = render("tenant-migration-disabled") if disabled.returncode: raise SystemExit(disabled.stderr) @@ -126,6 +166,8 @@ with tempfile.TemporaryDirectory() as directory: raise SystemExit(f"{workload} reused an ordinary service certificate") require_flyway_disabled(pod["containers"][0]["args"], workload) require_flyway_guard_negative_proof(pod["containers"][0]["args"], workload) + require_database_credentials(pod["containers"][0], service, mode) + require_database_guard_negative_proof(pod["containers"][0], service, mode) policy = by_kind_name[("NetworkPolicy", workload)]["spec"] if policy["ingress"] != [] or set(policy["policyTypes"]) != {"Ingress", "Egress"}: raise SystemExit(f"{workload} has an unexpected ingress allowance") diff --git a/k8s/helm/firemud/templates/tenant-association-account-job.yaml b/k8s/helm/firemud/templates/tenant-association-account-job.yaml index c609397385..2d73326b7e 100644 --- a/k8s/helm/firemud/templates/tenant-association-account-job.yaml +++ b/k8s/helm/firemud/templates/tenant-association-account-job.yaml @@ -16,6 +16,10 @@ {{- if not (has $mode (list "evidence" "import")) -}} {{- fail "Account tenant association mode must be evidence or import" -}} {{- end -}} +{{- $postgresCredentialSecretName := "firemud-account-tenant-evidence-db" -}} +{{- if eq $mode "import" -}} +{{- $postgresCredentialSecretName = "firemud-account-tenant-import-db" -}} +{{- end -}} {{- $runId := required "Account tenant association import requires runId" $job.runId -}} {{- if or (gt (len $runId) 32) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $runId)) -}} {{- fail "Account tenant association runId must be a DNS label of at most 32 characters" -}} @@ -112,13 +116,15 @@ spec: - name: FIREMUD_POSTGRES_USER valueFrom: secretKeyRef: - name: firemud-secret + name: {{ $postgresCredentialSecretName | quote }} key: FIREMUD_POSTGRES_USER + optional: false - name: FIREMUD_POSTGRES_PASSWORD valueFrom: secretKeyRef: - name: firemud-secret + name: {{ $postgresCredentialSecretName | quote }} key: FIREMUD_POSTGRES_PASSWORD + optional: false - name: FIREMUD_REDIS_ENABLED value: "false" - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE diff --git a/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml b/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml index 7d58b2a9d3..f90e318826 100644 --- a/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml +++ b/k8s/helm/firemud/templates/tenant-association-game-design-job.yaml @@ -16,6 +16,10 @@ {{- if not (has $mode (list "preflight" "apply")) -}} {{- fail "Game Design tenant association mode must be preflight or apply" -}} {{- end -}} +{{- $postgresCredentialSecretName := "firemud-game-design-tenant-preflight-db" -}} +{{- if eq $mode "apply" -}} +{{- $postgresCredentialSecretName = "firemud-game-design-tenant-apply-db" -}} +{{- end -}} {{- $runId := required "Game Design tenant association migration requires runId" $job.runId -}} {{- if or (gt (len $runId) 32) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $runId)) -}} {{- fail "Game Design tenant association runId must be a DNS label of at most 32 characters" -}} @@ -113,13 +117,15 @@ spec: - name: FIREMUD_POSTGRES_USER valueFrom: secretKeyRef: - name: firemud-secret + name: {{ $postgresCredentialSecretName | quote }} key: FIREMUD_POSTGRES_USER + optional: false - name: FIREMUD_POSTGRES_PASSWORD valueFrom: secretKeyRef: - name: firemud-secret + name: {{ $postgresCredentialSecretName | quote }} key: FIREMUD_POSTGRES_PASSWORD + optional: false - name: FIREMUD_REDIS_ENABLED value: "false" - name: FIREMUD_TEMPORAL_ENABLED diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index 1413b18b7b..908707db87 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -24,6 +24,8 @@ previewStack: tenantAssociationMigration: # Operator-invoked Jobs only; ordinary chart releases never run them. # Evidence Secrets and immutable images are supplied by the operator. + # Each mode also requires its fixed, separately provisioned least-privilege + # database Secret; shared bootstrap/service credentials are never a fallback. gameDesign: enabled: false mode: "" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java index c366ad46ef..a75f1a085e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunner.java @@ -1,10 +1,15 @@ package net.firedevops.firemud.accountservice.maintenance; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.service.impl.LegacyTenantAssociationImportService; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.slf4j.Logger; @@ -30,14 +35,20 @@ public class LegacyTenantAssociationImportJobRunner implements ApplicationRunner private final Environment environment; private final LegacyTenantAssociationImportService importService; private final ObjectProvider schedulingPostProcessor; + private final DataSource dataSource; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring collaborators are internal to the migration Job.") public LegacyTenantAssociationImportJobRunner( Environment environment, LegacyTenantAssociationImportService importService, - ObjectProvider schedulingPostProcessor) { + ObjectProvider schedulingPostProcessor, + DataSource dataSource) { this.environment = environment; this.importService = importService; this.schedulingPostProcessor = schedulingPostProcessor; + this.dataSource = dataSource; } @Override @@ -51,6 +62,11 @@ public void run(ApplicationArguments args) throws Exception { || environment.getProperty("spring.grpc.server.enabled", Boolean.class, true)) { throw new IllegalStateException("Account tenant migration must not start listeners"); } + String mode = required("firemud.account-tenant-migration.mode"); + requireDatabaseAuthority( + mode, + connectedDatabaseUsername(), + environment.getProperty("spring.flyway.enabled", Boolean.class, true)); String podNamespace = required("firemud.account-tenant-migration.pod-namespace"); String targetNamespace = required("firemud.account-tenant-migration.target-namespace"); if (!podNamespace.equals(targetNamespace) @@ -65,7 +81,6 @@ public void run(ApplicationArguments args) throws Exception { if (legacyTenantId <= 0) { throw new IllegalArgumentException("legacy Account tenant key must be positive"); } - String mode = required("firemud.account-tenant-migration.mode"); if ("evidence".equals(mode)) { LOG.info( "Account tenant evidence legacyTenantId={} digest={} namespace={}", @@ -87,6 +102,42 @@ public void run(ApplicationArguments args) throws Exception { } } + static void requireDatabaseAuthority(String mode, String username, boolean flywayEnabled) { + if (flywayEnabled) { + throw new IllegalStateException("Account tenant migration requires Flyway to be disabled"); + } + String requiredUsername = + switch (mode) { + case "evidence" -> "firemud_account_tenant_evidence"; + case "import" -> "firemud_account_tenant_import"; + default -> + throw new IllegalArgumentException("unsupported Account tenant migration mode"); + }; + if (!requiredUsername.equals(username)) { + throw new IllegalStateException( + "Account tenant migration DB credential does not match the mode"); + } + } + + String connectedDatabaseUsername() { + try (Connection connection = dataSource.getConnection()) { + DatabaseMetaData metadata = connection == null ? null : connection.getMetaData(); + if (metadata == null) { + throw new IllegalStateException("Account tenant migration DB connection is unverifiable"); + } + String username = metadata.getUserName(); + if (username == null || username.isBlank()) { + throw new IllegalStateException( + "Account tenant migration DB connection did not identify its user"); + } + return username; + } catch (SQLException failure) { + // Avoid surfacing driver diagnostics that can echo the configured database username. + throw new IllegalStateException( + "Account tenant migration DB connection could not be verified"); + } + } + static void requireJobIdentity(String podNamespace, GrpcPeerIdentity identity) { if (identity == null || !identity.isService("account-tenant-migrator") diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java index e8bb72c3af..6f931abb5b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/LegacyTenantAssociationImportJobRunnerTest.java @@ -1,11 +1,17 @@ package net.firedevops.firemud.accountservice.maintenance; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.service.impl.LegacyTenantAssociationImportService; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.junit.jupiter.api.Test; @@ -15,6 +21,111 @@ import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; class LegacyTenantAssociationImportJobRunnerTest { + @Test + void requiresFlywayDisabledAndExactDatabaseUserForEachMode() { + assertThatCode( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + "evidence", "firemud_account_tenant_evidence", false)) + .doesNotThrowAnyException(); + assertThatCode( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + "import", "firemud_account_tenant_import", false)) + .doesNotThrowAnyException(); + + for (String[] wrongModeAndUser : + new String[][] { + {"evidence", "firemud_account_tenant_import"}, + {"import", "firemud_account_tenant_evidence"}, + {"evidence", "firemud"}, + {"import", "firemud_account_service"}, + {"evidence", null}, + {"import", ""}, + {"evidence", " "} + }) { + assertThatThrownBy( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + wrongModeAndUser[0], wrongModeAndUser[1], false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB credential does not match the mode"); + } + assertThatThrownBy( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + "unsupported", "firemud_account_tenant_evidence", false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("unsupported Account tenant migration mode"); + assertThatThrownBy( + () -> + LegacyTenantAssociationImportJobRunner.requireDatabaseAuthority( + "evidence", "firemud_account_tenant_evidence", true)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration requires Flyway to be disabled"); + } + + @Test + void readsAndClosesTheActualJdbcConnectionForDatabaseIdentity() throws Exception { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + DatabaseMetaData metadata = mock(DatabaseMetaData.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getUserName()).thenReturn("firemud_account_tenant_evidence"); + + assertThat(runner(dataSource).connectedDatabaseUsername()) + .isEqualTo("firemud_account_tenant_evidence"); + verify(connection).close(); + } + + @Test + void rejectsMissingOrUnverifiableJdbcIdentityWithoutLeakingDriverDetails() throws Exception { + for (String username : new String[] {null, "", " "}) { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + DatabaseMetaData metadata = mock(DatabaseMetaData.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getUserName()).thenReturn(username); + + assertThatThrownBy(() -> runner(dataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB connection did not identify its user"); + verify(connection).close(); + } + + DataSource unavailableDataSource = mock(DataSource.class); + when(unavailableDataSource.getConnection()) + .thenThrow(new SQLException("sensitive driver credential diagnostic")); + assertThatThrownBy(() -> runner(unavailableDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB connection could not be verified") + .hasNoCause() + .hasMessageNotContaining("sensitive driver credential diagnostic"); + + DataSource missingMetadataDataSource = mock(DataSource.class); + Connection missingMetadataConnection = mock(Connection.class); + when(missingMetadataDataSource.getConnection()).thenReturn(missingMetadataConnection); + when(missingMetadataConnection.getMetaData()).thenReturn(null); + assertThatThrownBy(() -> runner(missingMetadataDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB connection is unverifiable"); + verify(missingMetadataConnection).close(); + + DataSource unverifiableDataSource = mock(DataSource.class); + Connection unverifiableConnection = mock(Connection.class); + when(unverifiableDataSource.getConnection()).thenReturn(unverifiableConnection); + when(unverifiableConnection.getMetaData()) + .thenThrow(new SQLException("sensitive metadata credential diagnostic")); + assertThatThrownBy(() -> runner(unverifiableDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account tenant migration DB connection could not be verified") + .hasNoCause() + .hasMessageNotContaining("sensitive metadata credential diagnostic"); + verify(unverifiableConnection).close(); + } + @Test void failsBeforeOwnerEvidenceOrImportWhenSchedulingIsPresent() { Environment environment = mock(Environment.class); @@ -29,7 +140,7 @@ void failsBeforeOwnerEvidenceOrImportWhenSchedulingIsPresent() { LegacyTenantAssociationImportJobRunner runner = new LegacyTenantAssociationImportJobRunner( - environment, importService, schedulingPostProcessor); + environment, importService, schedulingPostProcessor, mock(DataSource.class)); assertThatThrownBy(() -> runner.run(new DefaultApplicationArguments())) .isInstanceOf(IllegalStateException.class) @@ -62,4 +173,13 @@ private static GrpcPeerIdentity peer(String namespace, String service) { return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) .orElseThrow(); } + + @SuppressWarnings("unchecked") + private static LegacyTenantAssociationImportJobRunner runner(DataSource dataSource) { + return new LegacyTenantAssociationImportJobRunner( + mock(Environment.class), + mock(LegacyTenantAssociationImportService.class), + mock(ObjectProvider.class), + dataSource); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java index fd67935402..e31dcca75b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunner.java @@ -4,12 +4,17 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; import java.util.Map; +import javax.sql.DataSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Signed; import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService; @@ -35,14 +40,20 @@ public class TenantAssociationManifestJobRunner implements ApplicationRunner { private final Environment environment; private final ObjectMapper objectMapper; private final TenantAssociationMigrationService migrationService; + private final DataSource dataSource; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring collaborators are internal to the migration Job.") public TenantAssociationManifestJobRunner( Environment environment, ObjectMapper objectMapper, - TenantAssociationMigrationService migrationService) { + TenantAssociationMigrationService migrationService, + DataSource dataSource) { this.environment = environment; this.objectMapper = objectMapper.copy(); this.migrationService = migrationService; + this.dataSource = dataSource; } @Override @@ -53,6 +64,11 @@ public void run(ApplicationArguments args) throws Exception { || environment.getProperty("firemud.temporal.enabled", Boolean.class, true)) { throw new IllegalStateException("tenant migration must not start listeners or workers"); } + String mode = required("firemud.tenant-association-migration.mode"); + requireDatabaseAuthority( + mode, + connectedDatabaseUsername(), + environment.getProperty("spring.flyway.enabled", Boolean.class, true)); String podNamespace = required("firemud.tenant-association-migration.pod-namespace"); String targetNamespace = required("firemud.tenant-association-migration.target-namespace"); if (!podNamespace.equals(targetNamespace) @@ -78,7 +94,6 @@ public void run(ApplicationArguments args) throws Exception { if (!targetNamespace.equals(verified.manifest().targetNamespace())) { throw new IllegalStateException("signed tenant manifest targets a different namespace"); } - String mode = required("firemud.tenant-association-migration.mode"); if ("preflight".equals(mode)) { LOG.info( "Tenant association preflight operationId={} manifestDigest={} entries={} namespace={}", @@ -99,6 +114,38 @@ public void run(ApplicationArguments args) throws Exception { } } + static void requireDatabaseAuthority(String mode, String username, boolean flywayEnabled) { + if (flywayEnabled) { + throw new IllegalStateException("tenant migration requires Flyway to be disabled"); + } + String requiredUsername = + switch (mode) { + case "preflight" -> "firemud_game_design_tenant_preflight"; + case "apply" -> "firemud_game_design_tenant_apply"; + default -> throw new IllegalArgumentException("unsupported tenant migration Job mode"); + }; + if (!requiredUsername.equals(username)) { + throw new IllegalStateException("tenant migration DB credential does not match the mode"); + } + } + + String connectedDatabaseUsername() { + try (Connection connection = dataSource.getConnection()) { + DatabaseMetaData metadata = connection == null ? null : connection.getMetaData(); + if (metadata == null) { + throw new IllegalStateException("tenant migration DB connection is unverifiable"); + } + String username = metadata.getUserName(); + if (username == null || username.isBlank()) { + throw new IllegalStateException("tenant migration DB connection did not identify its user"); + } + return username; + } catch (SQLException failure) { + // Avoid surfacing driver diagnostics that can echo the configured database username. + throw new IllegalStateException("tenant migration DB connection could not be verified"); + } + } + static void requireJobIdentity(String podNamespace, GrpcPeerIdentity identity) { if (identity == null || !identity.isService(MIGRATOR_SERVICE_ACCOUNT) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java index b944cf69ab..4febcae0b6 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/TenantAssociationManifestJobRunnerTest.java @@ -1,12 +1,128 @@ package net.firedevops.firemud.gamedesign.maintenance; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import javax.sql.DataSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService; import org.junit.jupiter.api.Test; +import org.springframework.core.env.Environment; class TenantAssociationManifestJobRunnerTest { + @Test + void requiresFlywayDisabledAndExactDatabaseUserForEachMode() { + assertThatCode( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + "preflight", "firemud_game_design_tenant_preflight", false)) + .doesNotThrowAnyException(); + assertThatCode( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + "apply", "firemud_game_design_tenant_apply", false)) + .doesNotThrowAnyException(); + + for (String[] wrongModeAndUser : + new String[][] { + {"preflight", "firemud_game_design_tenant_apply"}, + {"apply", "firemud_game_design_tenant_preflight"}, + {"preflight", "firemud"}, + {"apply", "firemud_game_design_service"}, + {"preflight", null}, + {"apply", ""}, + {"preflight", " "} + }) { + assertThatThrownBy( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + wrongModeAndUser[0], wrongModeAndUser[1], false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB credential does not match the mode"); + } + assertThatThrownBy( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + "unsupported", "firemud_game_design_tenant_preflight", false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("unsupported tenant migration Job mode"); + assertThatThrownBy( + () -> + TenantAssociationManifestJobRunner.requireDatabaseAuthority( + "preflight", "firemud_game_design_tenant_preflight", true)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration requires Flyway to be disabled"); + } + + @Test + void readsAndClosesTheActualJdbcConnectionForDatabaseIdentity() throws Exception { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + DatabaseMetaData metadata = mock(DatabaseMetaData.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getUserName()).thenReturn("firemud_game_design_tenant_preflight"); + + assertThat(runner(dataSource).connectedDatabaseUsername()) + .isEqualTo("firemud_game_design_tenant_preflight"); + verify(connection).close(); + } + + @Test + void rejectsMissingOrUnverifiableJdbcIdentityWithoutLeakingDriverDetails() throws Exception { + for (String username : new String[] {null, "", " "}) { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + DatabaseMetaData metadata = mock(DatabaseMetaData.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getUserName()).thenReturn(username); + + assertThatThrownBy(() -> runner(dataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB connection did not identify its user"); + verify(connection).close(); + } + + DataSource unavailableDataSource = mock(DataSource.class); + when(unavailableDataSource.getConnection()) + .thenThrow(new SQLException("sensitive driver credential diagnostic")); + assertThatThrownBy(() -> runner(unavailableDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB connection could not be verified") + .hasNoCause() + .hasMessageNotContaining("sensitive driver credential diagnostic"); + + DataSource missingMetadataDataSource = mock(DataSource.class); + Connection missingMetadataConnection = mock(Connection.class); + when(missingMetadataDataSource.getConnection()).thenReturn(missingMetadataConnection); + when(missingMetadataConnection.getMetaData()).thenReturn(null); + assertThatThrownBy(() -> runner(missingMetadataDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB connection is unverifiable"); + verify(missingMetadataConnection).close(); + + DataSource unverifiableDataSource = mock(DataSource.class); + Connection unverifiableConnection = mock(Connection.class); + when(unverifiableDataSource.getConnection()).thenReturn(unverifiableConnection); + when(unverifiableConnection.getMetaData()) + .thenThrow(new SQLException("sensitive metadata credential diagnostic")); + assertThatThrownBy(() -> runner(unverifiableDataSource).connectedDatabaseUsername()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("tenant migration DB connection could not be verified") + .hasNoCause() + .hasMessageNotContaining("sensitive metadata credential diagnostic"); + verify(unverifiableConnection).close(); + } + @Test void acceptsOnlyExactDedicatedMigratorCertificate() { assertThatCode( @@ -31,4 +147,12 @@ private static GrpcPeerIdentity peer(String namespace, String service) { return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) .orElseThrow(); } + + private static TenantAssociationManifestJobRunner runner(DataSource dataSource) { + return new TenantAssociationManifestJobRunner( + mock(Environment.class), + new ObjectMapper(), + mock(TenantAssociationMigrationService.class), + dataSource); + } } From b3149e7c8475a81a0c9cb8d232f3a7b3b5a458a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:23:26 +1300 Subject: [PATCH 27/28] Allow Validation for stacked pull requests --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e919d5382c..d8b3696fb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: From 2eb191b3cbdf9eaca75dcf094f9de50b250ce827 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:32:23 +1300 Subject: [PATCH 28/28] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d8b3696fb5..9b8ada9794 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1015,7 +1015,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) {