From 31fb1308139192242908b8184301da5abea48a87 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 10:45:58 +1200 Subject: [PATCH 01/55] Converge global registration and explicit public join with durable audit --- .../account-service/api-contracts.md | 15 +- .../account-service/operations.md | 2 +- .../account-service/runtime-and-data.md | 14 +- .../logging-admin-service/api-contracts.md | 2 +- .../system-architecture-authentication.md | 7 +- .../player-access-and-session.md | 14 +- protos/account/v1/account_service.proto | 48 +- .../v1/game_session_service.proto | 6 + .../v1/logging_admin_service.proto | 75 +- .../shared/v1/player_execution_context.proto | 20 + .../client/LoggingAdminClient.java | 95 ++- .../controller/AuthController.java | 16 + .../accountservice/data/TestDataSeeder.java | 4 + .../dto/AccountAuditDigest.java | 23 + .../dto/AccountAuditEnvelope.java | 17 + .../accountservice/dto/AccountDto.java | 2 +- .../accountservice/dto/AccountJoinDigest.java | 96 +++ .../dto/CreateAccountRequest.java | 2 - .../dto/DirectTextCallerContext.java | 12 + .../dto/DirectTextJoinScope.java | 6 + .../dto/DirectTextJoinTarget.java | 15 + .../dto/JoinPublicProductionRequest.java | 9 + .../dto/JoinPublicProductionResult.java | 12 + .../dto/RuntimeMembershipDto.java | 2 + .../accountservice/dto/VerifiedJoinScope.java | 18 + .../accountservice/entity/Account.java | 2 +- .../entity/AccountTenantMembership.java | 4 + .../accountservice/entity/Subscription.java | 1 + .../AccountAuditOutboxRepository.java | 100 +++ .../AccountConnectScopeRepository.java | 82 +++ .../AccountJoinOperationRepository.java | 173 +++++ .../AccountTenantMembershipRepository.java | 21 + .../repository/SubscriptionRepository.java | 21 +- .../service/AccountAuditDeliveryJob.java | 43 ++ .../service/AccountService.java | 14 + .../service/impl/AccountGrpcService.java | 152 +++- .../service/impl/AccountServiceImpl.java | 655 ++++++++++++++--- .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 2 + ...V26__global_registration_join_evidence.sql | 232 ++++++ .../src/main/resources/openapi.yaml | 72 +- .../AccountApplicationIntegrationTest.java | 48 ++ .../AccountRepositoryIntegrationTest.java | 100 +++ .../controller/AccountControllerTest.java | 26 +- .../PublicBootstrapRoutesProdProfileTest.java | 2 +- .../dto/AccountJoinDigestTest.java | 72 ++ .../service/AccountAuditDeliveryJobTest.java | 74 ++ .../service/impl/AccountGrpcServiceTest.java | 250 ++++++- .../service/impl/AccountServiceImplTest.java | 689 ++++++++++++++++-- .../gamesession/client/AccountClient.java | 131 ++++ .../client/DirectTextConnectScopeTarget.java | 32 + .../BuiltInTextCommandDefinitionProvider.java | 9 + .../command/text/GameplayWorldCatalog.java | 83 ++- .../command/text/HelpCommandHandler.java | 12 + .../command/text/LogoutCommandHandler.java | 31 +- .../gamesession/command/text/TextCommand.java | 6 + .../command/text/TextCommandParser.java | 10 + .../command/text/TextCommandPayload.java | 17 + .../command/text/TextCommandType.java | 2 + .../command/text/WorldsCommandHandler.java | 206 ++++++ .../WorldsTextCommandDispatchHandler.java | 96 ++- .../entity/GameplayAdmissionPointer.java | 4 + .../GameplayAdmissionPointerRepository.java | 52 ++ .../DirectTextConnectScopeSessionStore.java | 299 ++++++++ .../GameplayAdmissionPointerSnapshot.java | 70 +- ...eplayAdmissionPointerAuthorityService.java | 40 +- .../service/impl/GameSessionGrpcService.java | 56 +- ...V3__separate_gameplay_catalog_revision.sql | 4 + .../V4__persist_gameplay_realm_identity.sql | 74 ++ .../gamesession/client/AccountClientTest.java | 101 +++ .../command/text/HelpCommandHandlerTest.java | 14 + .../command/text/TextCommandParserTest.java | 33 + .../WorldsTextCommandDispatchHandlerTest.java | 130 ++++ ...ameplayAdmissionPointerRepositoryTest.java | 137 ++++ ...irectTextConnectScopeSessionStoreTest.java | 142 ++++ ...yAdmissionPointerAuthorityServiceTest.java | 1 + .../impl/GameSessionGrpcServiceTest.java | 300 +++++++- .../AccountAuditGrpcAuthConfiguration.java | 37 + .../dto/AccountAuditReceiptDto.java | 13 + .../dto/AccountAuditReceiptOutcome.java | 8 + .../dto/AccountAuditReceiptStatus.java | 7 + .../loggingadmin/dto/AccountAuditScope.java | 16 + .../dto/CreateLogEventRequest.java | 24 +- .../entity/AccountAuditReceipt.java | 30 + .../AccountAuditReceiptInsertResult.java | 3 + .../AccountAuditReceiptRepository.java | 89 +++ .../AuditReceiptNotFoundException.java | 7 + .../AuditStorageUnavailableException.java | 7 + .../loggingadmin/service/LogEventService.java | 6 +- .../service/impl/LogEventServiceImpl.java | 213 +++++- .../service/impl/LoggingAdminGrpcService.java | 278 ++++++- .../migration/V2__account_audit_receipts.sql | 47 ++ .../service/impl/LogEventServiceImplTest.java | 212 ++++++ .../impl/LoggingAdminGrpcServiceAuthTest.java | 368 ++++++++-- 94 files changed, 6350 insertions(+), 476 deletions(-) create mode 100644 protos/shared/v1/player_execution_context.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java create mode 100644 services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V3__separate_gameplay_catalog_revision.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V4__persist_gameplay_realm_identity.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b05d3d3a00..aab82440b9 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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. Explicit `JOIN` / `Join & Play` is not implemented. The current runtime membership response is the current four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with `membershipExists=false` may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. 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 sole target canonical operation is `JoinPublicProductionMembership`; the obsolete implicit membership-writer surface has been removed and is not a compatibility operation. Runtime convergence remains partial until explicit join is implemented with the target transaction, version, and durable audit/outbox evidence. `/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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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`, including scope/caller validation, fresh public-join policy checks, version-1 policy-bound operation digest, membership transition, durable operation outcome, and tenant audit outbox evidence in the Account transaction. An operation retained as `PENDING` after an unknown database commit outcome still lacks the durable recovery/reconciliation behavior required by ADR 0025, and PostgreSQL runtime and direct text end-to-end proof remain open. The current runtime membership response remains the four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. 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. ### Current vs Target Export Lifecycle @@ -75,9 +75,10 @@ For `security_locked` accounts, Account's successful recovery authorization issu `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. -- `CreateAccount` – registers a new user and returns its `accountId` so internal services can establish their own sessions using the authentication flows described below. +- `CreateAccount` – registers a global Account identity and returns its `accountId`; it does not select a tenant or create membership/profile state. Registration also appends a platform-scoped audit outbox record in the Account transaction. - `SendNotification` – deliver account notifications asynchronously. - `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. +- `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); a `PENDING` operation after an unknown database commit outcome still requires unresolved recovery/reconciliation work under ADR 0025. - `ResolveEffectiveSecurityPolicy` – **Target-state internal Account contract.** Resolve the effective policy for the exact account, optional tenant-scoped action, and action class from the versioned platform baseline, deployment policy, and applicable tenant policy using the tightening precedence in ADR 0045. Return the contributing policy versions, resolved values, and opaque `effectivePolicyVersion`/digest from one Account-owned resolution. Callers must not merge inputs or use cached/default policy; missing, invalid, contradictory, stale, or unavailable resolution fails the sensitive action closed. No other service is a policy authority. - `ApplyAccountSafetyRestriction` / `GetAccountSafetyRestrictions` – target Account-owned owner-command and safe projection contracts for `account_security_lock` and `platform_access_ban`. The command carries one exact category, global account scope, source case/security-event identity, a distinct `ownerEnforcementRequestId`, owner-enforcement digest, and owner authorization evidence; `controlPlaneRequestId` remains correlation-only and never carries or aliases the owner identity. Account validates and atomically commits its monotonic revision, account authority-generation effects, and idempotent result. The current proto/transport mapping does not yet expose the distinct owner request field; that is implementation drift, not proof that the target command is implemented. These contracts do not create a moderation appeal case, and current proto/implementation/proof do not yet provide the complete lifecycle. - `RefreshGameplayServiceToken` – Account-local RPC for the token refresh/replacement operation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). Account validates the declared receiver binding and current authority, while Game Session supplies the binding-refresh installation/reconciliation consequence; the current proto and implementation do not yet prove the target registry-backed operation. @@ -102,10 +103,10 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. - `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. -- `IssueDirectTextConnectScope` – target-only internal Account API called only by authenticated Game Session mTLS during authenticated `REALMS`. The request carries the authenticated caller context in a typed `PlayerExecutionContext` plus the exact server-resolved `{tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion}` target, with exact `playtestLifecycleId` and positive `playtestStateGeneration` for every non-public target and both fields absent for a non-grant public-production target. Account validates that authenticated caller context separately from scope validation; the response returns an opaque short-lived `connectScopeId` and `connectScopeExpiresAt` bound to that complete evaluated target and exact `catalogRevision`/`pointerVersion` snapshot. It is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the explicit membership mutation. An unavailable Account or routing authority fails closed as `AUTH_UNAVAILABLE`; reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid catalog/pointer evidence is `ADMISSION_POINTER_UNAVAILABLE` before a valid scope comparison, while a valid scope whose exact `catalogRevision`/`pointerVersion` pair differs from the fresh authoritative snapshot returns `CONNECT_SCOPE_MISMATCH`. Fresh Account membership checks remain required separately at the applicable join, connect-token, and admission gates. Detailed scope semantics remain delegated to [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) and [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). +- `IssueDirectTextConnectScope` – implemented local internal Account API called by authenticated Game Session during authenticated `REALMS`. The request carries authenticated caller context in typed `PlayerExecutionContext` plus the server-resolved target; Account validates caller context separately from the short-lived scope and returns an opaque `connectScopeId` bound to the evaluated routing snapshot. It is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the membership mutation. Reachable missing or invalid routing evidence fails as `ADMISSION_POINTER_UNAVAILABLE`; a changed exact routing pair fails as `CONNECT_SCOPE_MISMATCH`; unavailable authority fails as `AUTH_UNAVAILABLE`. Fresh Account membership checks remain required separately at applicable admission gates. The canonical scope and transport requirements remain owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); this local status does not claim direct text-client end-to-end proof. - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). -- `JoinPublicProductionMembership` – target-only internal Account API for explicit open-enrollment `JOIN`; its canonical membership lifecycle and freshness contract are owned by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). The local route remains unimplemented, accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. +- `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery for an operation left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision; PostgreSQL runtime and direct text-client end-to-end proof are not claimed. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the response is the four-field admission shape documented above and does not expose lifecycle state or `membershipAuthorityGeneration`. **Target-only:** the response adds `membershipLifecycleState` and opaque `membershipAuthorityGeneration`, with the independent `membershipVersion`, from one fresh atomic Account membership snapshot. @@ -161,7 +162,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `POST` | `/auth/request-email-verification` | Send an account-scoped verification email selected by normalized email with a neutral known/unknown response; the public route accepts no numeric account selector | | `POST` | `/auth/verify-email` | **Target public route; current bearer exception.** Verify an account-scoped email token. The current HTTP configurations allowlist only `GET /auth/verify-email` (which has no controller mapping), so the implemented `POST` route inherits bearer authentication until the public-route configuration is deliberately converged and proved. | | `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | -| `POST` | `/accounts` | Create a new user account | +| `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/export` | **Current legacy route.** Returns an Account/profile-local export and does not satisfy ADR 0050. | | `POST` | `/accounts/{accountId}/exports` | **Target-state only.** Initiate or idempotently replay one asynchronous portable-data export within the defined global account scope using the caller's `requestId`; Account computes and persists the canonical, versioned `requestDigest` and `exportId`, returns the existing operation on a matching retry, and returns an idempotency conflict on a digest mismatch. Active accounts use the authenticated account subject; `security_locked` accounts use only the distinct Account-issued, expiring `security-lock-export` credential after Account-owned recovery authorization; `deactivated_pending_delete` accounts use only `pending-deletion-access`. No state accepts a tenant selector or a support-only bypass. | | `GET` | `/accounts/{accountId}/exports/{exportId}` | **Target-state only.** Read durable portable-data export status, owner contribution state, and the versioned manifest using the same bounded subject/credential branch that initiated the job. | @@ -177,7 +178,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | | `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. | -| `POST` | `/internal/runtime/public-production-join` | Target Account-owned boundary for `JoinPublicProductionMembership`, used by explicit text-client `JOIN`; explicit JOIN behavior remains target-only and unimplemented, and no implicit membership-writer route is exposed | +| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** Explicit text-client JOIN uses the implemented internal `JoinPublicProductionMembership` RPC; no implicit membership-writer route is exposed. | | `GET` | `/internal/runtime/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}/{accountId}` | Internal-only authoritative lookup for one non-public realm-access grant; the lifecycle ID is part of the exact target | | `GET` | `/internal/runtime/accounts/{accountId}/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | Internal-only authoritative lookup/list for the account's exact non-public world/realm/lifecycle target used by discovery/admission filtering | | `POST` | `/tenant-admin/tenants/{tenantId}/realm-access-grants/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | **Target-state only; not currently routable.** Target duplicate-safe create-or-extend surface. The body carries the exact `accountId`, `operation`, requested `grantExpiresAt`, stable `requestId`, and conditional `expectedGrantRevision` (absent-grant precondition for `CREATE`, required current revision for `EXTEND`); exact `mutationDigest/v1` retries replay the stored outcome and changed intent or revision returns `IDEMPOTENCY_CONFLICT` or `GRANT_REVISION_CONFLICT` as defined above. | @@ -189,7 +190,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `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 four-field membership response, 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/bootstrap/join` | **Target-state only; not implemented at the current Account Service boundary.** Perform an explicit caller-bound `JoinPublicProductionMembership` / `Join & Play` operation for a discovery-selected public production realm using the exact `connectScopeId` and `requestId`. Account consumes the canonical JOIN digest contract defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative), verifies the scope's exact routing pair at membership commit, and retains only the local operation, membership, audit, and outbox consequences. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A stale pair or digest returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. | +| `POST` | `/auth/bootstrap/join` | **Target facade; not currently routable.** The local internal `JoinPublicProductionMembership` operation is implemented for explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. The canonical digest contract is defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); Account verifies the stored scope and current public policy before its membership transaction. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A stale pair or digest returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Durable recovery for an operation left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision. | | `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 | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 943f66281f..585438a383 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -11,7 +11,7 @@ This document collects the Account Service operational behavior, readiness model ## 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. Global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits likewise use platform scope and omit `tenantId`. 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 runtime:** Account persists the account, profile, and membership locally, then attempts the `CreateLogEvent` RPC post-commit on a best-effort basis. Logging failure is swallowed and does not roll back or compensate the committed creation. The owner-local outbox and corresponding proto/receiver implementation must be implemented and proved before mandatory audit delivery is claimed. 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). +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). The current `PurchaseWorkflowService` implementation for one-time payments and donations is non-exposed, unsupported provider-mutating drift, not a V1 product path or entitlement authority. It currently enters the shared runner to create a payment intent, record the transaction with the Logging & Admin Service, and refund through compensation if the log step fails. The target Account containment boundary requires every generic purchase or donation entry point to reject before entering that runner or making any Stripe call; no supported V1 flow may invoke it. Current V1 remains the hosting-billing boundary in [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md), while the future marketplace direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md) remains deferred and must be implemented and proved separately. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 29e42a0b70..26866b52de 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 live account-creation paths still require a caller-provided `tenantId` and create an admission-enabled `AccountTenantMembership` as part of account creation. Legacy Account migrations also default existing account/profile and billing rows to tenant `1` and backfill membership from that value. This conflicts with the canonical [global-registration and explicit `JoinPublicProductionMembership` flow](../../system-architecture-authentication.md#login-and-session-flow). This is 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 implemented locally as the only public-production membership writer: it validates an Account-issued connect scope and caller binding, rechecks current entitlement and `allowPublicJoin` policy at the commit gate, binds a version-1 digest to the verified caller/scope and policy evidence, then commits membership, operation outcome, and tenant-scoped audit outbox evidence in the Account transaction. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. The JOIN operation table persists `PENDING`, `COMMITTED`, and `FAILED`, but durable recovery/reconciliation of a `PENDING` operation after an unknown database commit outcome is unresolved under the Overseer decision and remains an open ADR 0025 obligation. The local focused tests and PostgreSQL integration test source do not establish PostgreSQL runtime proof; 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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the two admission fields are true; an eligible public-production request with missing or non-admitting membership may return non-actionable `JOIN_REQUIRED`, but the current response cannot distinguish `INACTIVE` from another existing non-admitting lifecycle state. These paths do not create or restore membership. 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. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision, so ADR 0025 is not complete. Focused local tests exist, but PostgreSQL runtime proof and direct text-to-Logging end-to-end proof are not claimed. `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` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. @@ -28,7 +28,7 @@ The target realm-grant mutation boundary remains the Account API's tenant-admin Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; atomic single-use consumption and concurrent-reuse proof remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -The direct-text `REALMS`-to-`JOIN` scope handoff is also target-only and unimplemented. Account-local remaining work is to validate the authenticated `PlayerExecutionContext` separately from the short-lived target-bound scope, issue that scope during authenticated realm resolution, and validate its exact routing snapshot at `JoinPublicProductionMembership`; Game Session transport retention and server-generated join-attempt identity are defined by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +The local direct-text `REALMS`-to-`JOIN` path issues a short-lived Account-owned scope for an authenticated caller and validates the retained target snapshot and caller binding at `JoinPublicProductionMembership`; Game Session supplies a server-generated join-attempt identity. This is local Account implementation status only: no direct text-client end-to-end proof is claimed, and the durable recovery/reconciliation behavior for an operation left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision and ADR 0025. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -41,8 +41,8 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after exact receipt/readback or reconciliation; unavailable, timeout, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current runtime:** local writes commit first; Account then attempts `CreateLogEvent` post-commit on a best-effort basis, and logging failure is swallowed without compensating or rolling back creation. The current proto and receiver do not yet carry or enforce the target identity, envelope, digest, deduplication, readback, or Account workload authorization contract, so the durable outbox and mandatory receiver implementation remain open. -- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current runtime:** Account attempts `CreateLogEvent` after its local commit on a best-effort basis and swallows logging failure; that attempt is not delivery proof. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after Logging & Admin returns matching receipt evidence; failures leave it `PENDING` for retry. Logging & Admin locally implements durable receipt deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipts. These are local implementation facts, not PostgreSQL runtime or direct text end-to-end proof. Durable reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025; a terminal-looking database exception is not sufficient evidence to replay or report a membership transition. +- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). - Provides a JWKS endpoint for other services to validate tokens. Account Service owns signing-key lifecycle authorization, token issuance/rotation, desired key-ring state, and JWKS publication. In target non-exportable-signer mode, Account delegates only explicitly authorized private-key operations to the approved signer boundary; signer custody does not transfer lifecycle or publication authority. In the interim Account-only mounted fallback, the materialization controller is the sole Kubernetes API reader, writer, and generator for the fixed `jwt-signing-keys` Secret and custodian of that interim private material, but it may act only on Account-authorized operations. Account consumes projected key files and has no signing-Secret API authority. Kubernetes Jobs or CronJobs only observe Account-owned rotation, convergence, and retained evidence; they do not request or own rotation, read or write private keys, or publish JWKS, as described in the [Security Architecture](../../system-architecture-security.md). @@ -50,7 +50,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi - Telnet and other non-WebSocket text transports authenticate through the credential-bearing `LOGIN` flow described in [Authentication & Authorization](../../system-architecture-authentication.md) and do not carry public JWTs or gameplay connect tokens. First-party browser/mobile/server clients use the short-lived `player-bootstrap` profile for HTTPS bootstrap and an HttpOnly-cookie connect token for the WebSocket handshake. Explicitly classified non-first-party/public generic WebSocket clients have no current supported connect-token carrier; the dedicated issuance route, secure-storage response, and `X-Firemud-Connect-Token` handshake header remain target-only until their authorization-matrix, replay, signed-context, response, and carrier proofs are complete. The Game Session Service calls the internal `Authenticate` gRPC method (mTLS-protected) to verify credential-bearing login and obtain `game-session-account-delegation` JWTs for Account, while `/auth/login` remains a browser/control-plane endpoint. - Admin and creator UI authentication is initiated via the `/auth/login` HTTP endpoint, which issues `control-ui` JWTs used only for the exact control-plane audience described in the authentication and frontend architecture designs. - Owns credential brute-force defense and login abuse handling for every password and verified-email-code path. It combines trusted canonical source context with normalized account-candidate and coarse pressure buckets, applies graduated temporary throttles, and emits stable retry outcomes. These buckets are policy signals, not durable authority; any Cache/Rate-Limit Redis use must preserve one-to-one opaque subject isolation or explicitly declare a coarse heuristic, bounded cardinality, eviction/reset behavior, and outage mode under [ADR 0087](../../decisions/adr-0087-isolated-subject-rate-limits-with-explicit-loss-semantics.md). Ordinary failed attempts never transition the account to `security_locked`; that durable state requires evidence supporting a verified or high-confidence compromise assessment, explicit security policy, or audited operator action. Account is also the sole canonical resolver and publisher of the effective versioned security policy; callers do not merge deployment or tenant overrides or fall back to cached/default values, and an unavailable or contradictory policy resolution fails sensitive actions closed. Suspicious activity triggers notification emails and audit events as described in [Security Architecture](../../system-architecture-security.md#brute-force-defense-and-abuse-handling) and [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md). -- No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker. The existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift and do not authorize future Saga use. Account creation's cross-service audit handoff is target-state owner-local outbox work, not a compensated Saga step; the current post-commit best-effort behavior and its failure semantics are described above. 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). +- No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker. The existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift and do not authorize future Saga use. Account registration and explicit JOIN audit handoffs use the owner-local outbox and are not compensated Saga steps. 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). - Leverages the [Shared Libraries](../../system-architecture-shared-libraries.md) for common DTOs, logging interceptors, and Micrometer metrics. ## Data Model @@ -206,7 +206,7 @@ Runtime caller contract: - `requestId` is the idempotency key for connect-token issuance. Retrying the same `(accountId, connectScopeId, requestId)` replays the same deterministic application failure directly while its retained failure envelope is available. A stored success returns the same token payload only after current authority and all applicable admission, registry, and issuance postconditions revalidate; failed revalidation returns the applicable canonical denial without reminting or mutating the committed issuance result. If the compact receipt still exists after its encrypted response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`, never remints or reconstructs a JWT, and is terminal for that original issuance attempt; callers must start a fresh authorized request under a new `requestId`. A changed digest remains `IDEMPOTENCY_CONFLICT`. The exact membership freshness baseline used for issuance is bound to that `connectScopeId` and `requestId`; it is immutable comparison evidence, not a duplicate request field. If Gateway may already have consumed the token, the caller must rediscover and use a new `requestId` rather than replaying the prior issuance key. - Existing caller-bound membership is mandatory for every target. For a selected publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED`, commits no membership row, successful gameplay-connect issuance record, token registry record, token, or cookie, and records the same deterministic failure under `(accountId, connectScopeId, requestId)`. An exact retry replays `JOIN_REQUIRED` even if membership is created later while its failure envelope remains retained; after response-envelope removal, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` rather than minting or changing the result. The caller must use a new request ID after the explicit join or recovery-expired terminal outcome. The target replay outcome is durable for the complete issuance-idempotency window. The current implementation provides only the bounded Session Service replay record, so durable database-backed failure replay remains an implementation gap. A private or playtest target additionally requires the current Account-owned realm-access grant; a grant never substitutes for membership or public onboarding. - - `JoinPublicProductionMembership` is the sole target canonical name for the authoritative explicit open-enrollment membership operation. Its target request preserves exactly `connectScopeId` and `requestId`; for direct text, Game Session supplies the retained scope and generates the high-entropy request ID server-side rather than accepting either value from the client. The internal boundary authenticates the exact Game Session mTLS workload and validates its typed caller-bound `PlayerExecutionContext`, including `accountId`, before using the scope. The scope binds the target and exact catalog/pointer pair, not the membership subject. Public player-bootstrap surfaces derive `accountId` from the authenticated caller and do not accept a caller-selected account ID. Account verifies the exact bound catalog/pointer pair at commit, separately from the fresh Account entitlement `allowPublicJoin` check. Connect-token issuance and public-production `PLAY` must require its result but never invoke it implicitly. Explicit `JOIN`/`Join & Play` remains target-only and unimplemented; no implicit membership writer is exposed by connect-token issuance or `PLAY`. + - The target membership-writer contract is `JoinPublicProductionMembership`; its canonical caller, scope, policy, and replay behavior is owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Connect-token issuance and public-production `PLAY` require existing membership and never invoke the writer implicitly. The local Account RPC, digest, transaction, and recovery status are recorded under [Implementation Status](#implementation-status). - It is valid only for the default public production realm and only when the caller satisfies the public-production admission policy. - `requestId` is the attempt idempotency key and `connectScopeId` remains a required request field. Account uses the canonical JOIN digest preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). It persists the resulting digest with the verified caller/scope inputs and operation record. Retrying the same `{connectScopeId, requestId}` and digest returns the same membership result or deterministic application failure; a changed digest returns `IDEMPOTENCY_CONFLICT`, while a changed request ID is a distinct operation. - The resulting membership must be immediately visible to `GetTenantMembershipForRuntime`. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 46c08e9f43..9860a6516d 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -8,7 +8,7 @@ The canonical Account-to-Logging & Admin audit ingress is the existing `logging_ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenantId` only for `tenant` scope and never for `platform` scope, stable `auditEventId` generated and persisted by Account, `producerService`, `eventType`, producer `occurredAt`, positive `schemaVersion`, exact UTF-8 `payload`, `payloadDigestVersion` exactly `1` until a later canonical digest-version registry is accepted, and `payloadDigest`. Global registration, `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity events use `platform` scope with no `tenantId`; tenant profile and JOIN events use `tenant` scope with the exact committed `tenantId`. Unsupported digest versions fail before deduplication or persistence. `producerService` is derived from the authenticated Account workload identity and a mismatching request value is rejected. An upstream producer domain-event digest, when present inside `payload`, remains opaque payload evidence and is distinct from the receiver's `payloadDigest`. `payloadDigest` is `sha256:` followed by 64 lowercase hexadecimal characters over the exact UTF-8 payload bytes under `payloadDigestVersion=1`; no JSON reserialization or alternate canonicalization is permitted. Retry equivalence is the complete immutable `(scope, tenantId-if-tenant, auditEventId, producerService, eventType, occurredAt, schemaVersion, payloadDigestVersion, payloadDigest, exact payload bytes)` tuple: while exact payload bytes remain retained, an exact match returns the original receipt, while any changed field or payload bytes fails closed as `IDEMPOTENCY_CONFLICT`. After the safe watermark permits payload minimization, the retained identity and metadata may still detect a changed non-payload field, but the receiver must not claim exact payload equality or replay; a matching late request is a terminal non-replayable result. Timeout, transport failure, or an ambiguous response is not success; the producer retries or reconciles with the same identity and digest and never mints a replacement event. -`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. The current proto and receiver instead expose only the legacy `CreateLogEvent` shape and `AdminRoleGuard`; this is explicitly current drift pending the target convergence. +`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. **Current local implementation:** the Account audit request/response schema, Account workload check, exact payload digest validation, durable receipt insert/deduplication, bounded receipt readback, and accepted/duplicate/conflict/minimized outcomes are implemented locally. Account registration and JOIN now produce owner-local outbox entries; Account's delivery client checks returned receipt evidence before marking delivery complete. Focused local unit coverage exists, but PostgreSQL runtime proof and direct text-client-to-Logging end-to-end proof are not claimed. The target contract remains authoritative for full retention/readback horizons and any unresolved runtime edge cases. The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index c956fb822e..230e954ca1 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -274,6 +274,7 @@ These modes are complementary: public browse remains available before authentica - The canonical `JOIN` idempotency digest is `SHA-256` over the UTF-8 bytes of this exact newline-delimited preimage, including the final newline and preserving this field order: ```text + joinDigestVersion=v1 operationKind=JOIN accountId= callerBinding= @@ -282,12 +283,16 @@ These modes are complementary: public browse remains available before authentica realmSlug= playableStateNamespaceId= playableStateScope= + gameInstanceId= connectScopeId= catalogRevision= pointerVersion= + entitlementAuthorityAvailability= + [allowPublicJoin=] + [entitlementVersion=] ``` - Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. Account stores the resulting `requestDigest` with the `requestId`; an exact retry replays the stored outcome and a different digest returns `IDEMPOTENCY_CONFLICT`. + Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. Account calculates this unpublished pre-v1 `v1` digest only after establishing entitlement authority availability; when `AVAILABLE`, both policy lines are required and `allowPublicJoin` is lowercase `true` or `false` with a positive canonical decimal `entitlementVersion`. When authority is `UNAVAILABLE` or routing failed before policy evaluation (`NOT_EVALUATED`), both policy lines are omitted entirely, not filled with synthetic values. Account stores the digest version and exact availability/policy evidence with the `requestId`; an exact retry replays the stored outcome and a different digest returns `IDEMPOTENCY_CONFLICT`. No earlier JOIN digest was persisted, so no version-compatibility path is required. - Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. Normative semantic split: 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 73e6ee8dcd..4308aaf9de 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Explicit `JOIN`/`Join & Play`, the membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision; PostgreSQL runtime proof and direct text-client end-to-end proof are not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. 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. @@ -29,16 +29,16 @@ 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) | [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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Account identity and tenant-scoped profile CRUD and exports are live, but registration still requires a caller-selected tenant and creates an admission-enabled membership and profile before explicit JOIN; the ADR 0042 global-only registration target is not proved. The current profile GET/PUT routes now 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it, but the current public registration writer creates an admitting membership from a caller-selected tenant before explicit JOIN. That row lets later issuance bypass `allowPublicJoin=false` on the existing-membership path; global-only registration and the separate explicit JOIN writer remain required. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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.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. 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. The durable recovery/reconciliation seam for JOIN left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision and ADR 0025; do not mark ADR 0025 complete. PostgreSQL runtime proof 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.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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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 payment scaffolds still retain provider-mutating drift. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | +| `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. Explicit JOIN exists locally through Account's public-production writer, but this does not prove the direct text-client path; the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains 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, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. 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 first-party post-logout replay cleanup are absent. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account's player-bootstrap character discovery now requires an existing caller-bound membership that permits gameplay admission and returns `JOIN_REQUIRED` without an Entity read otherwise; pre-membership world and realm discovery remains available. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit JOIN, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission and returns `JOIN_REQUIRED` without an Entity read otherwise; pre-membership world and realm discovery remains available. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, while the durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under ADR 0025; PostgreSQL runtime and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. @@ -61,7 +61,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `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). -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` and the membership-authority-generation reread at connect-token issuance remain unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [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 `PENDING`/unknown-database-outcome recovery seam 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). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -173,7 +173,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and target explicit public-production join/leave | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; target join/leave APIs remain unimplemented | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; local JOIN RPC is implemented, while leave and the public bootstrap join REST facade remain target-only | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted proxy/first-party handshake validation, signed connect context, stable edge socket/session id, upstream gameplay bridge and rebind | `/ws/game/**`; `TrustedTcpProxyIdentity`; connect-token and first-party context headers | diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index c16a7e416b..3ade2a26c0 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -3,6 +3,7 @@ syntax = "proto3"; package account.v1; import "shared/v1/errors.proto"; +import "shared/v1/player_execution_context.proto"; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; @@ -16,6 +17,8 @@ service AccountService { rpc GetTenantMembershipForRuntime(GetTenantMembershipForRuntimeRequest) returns (GetTenantMembershipForRuntimeResponse); rpc GetRealmAccessGrantForRuntime(GetRealmAccessGrantForRuntimeRequest) returns (GetRealmAccessGrantForRuntimeResponse); rpc GetTenantEntitlementsForRuntime(GetTenantEntitlementsForRuntimeRequest) returns (GetTenantEntitlementsForRuntimeResponse); + rpc IssueDirectTextConnectScope(IssueDirectTextConnectScopeRequest) returns (IssueDirectTextConnectScopeResponse); + rpc JoinPublicProductionMembership(JoinPublicProductionMembershipRequest) returns (JoinPublicProductionMembershipResponse); rpc GetProfile(GetProfileRequest) returns (GetProfileResponse); rpc ListPresenceVisibilityPolicies(ListPresenceVisibilityPoliciesRequest) returns (ListPresenceVisibilityPoliciesResponse); @@ -30,6 +33,45 @@ service AccountService { rpc VerifyEmail(VerifyEmailRequest) returns (VerifyEmailResponse); } +// Game Session supplies its authenticated, transport-local player context and +// exact catalog/pointer evidence. Account re-resolves the target before issuance. +message IssueDirectTextConnectScopeRequest { + shared.v1.PlayerExecutionContext player_context = 1; + string tenant_id = 2; + string world_slug = 3; + string realm_slug = 4; + string realm_id = 5; + string playable_state_namespace_id = 6; + string playable_state_scope = 7; + string game_instance_id = 8; + int64 catalog_revision = 9; + int64 pointer_version = 10; +} + +message IssueDirectTextConnectScopeResponse { + string connect_scope_id = 1; + string connect_scope_expires_at = 2; + shared.v1.ErrorDetail error = 3; +} + +message JoinPublicProductionMembershipRequest { + shared.v1.PlayerExecutionContext player_context = 1; + string connect_scope_id = 2; + string request_id = 3; +} + +message JoinPublicProductionMembershipResponse { + bool success = 1; + string outcome_code = 2; + string account_id = 3; + string tenant_id = 4; + string membership_id = 5; + int64 membership_version = 6; + int64 membership_authority_generation = 7; + bool replayed = 8; + shared.v1.ErrorDetail error = 9; +} + // Empty request used to verify that the service is reachable. message PingRequest {} @@ -43,8 +85,8 @@ message PingResponse { // Parameters required to register a new account. message CreateAccountRequest { - // Tenant that owns the new account. - string tenant_id = 1; + reserved 1; + reserved "tenant_id"; // Desired username for login and display. string username = 2; // Email address used for notifications and password recovery. @@ -108,6 +150,8 @@ message GetTenantMembershipForRuntimeResponse { string evaluated_at = 5; shared.v1.ErrorDetail error = 6; bool membership_exists = 7; + string membership_lifecycle_state = 8; + uint64 membership_authority_generation = 9; } message GetRealmAccessGrantForRuntimeRequest { diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 7124096a5e..a1fb346880 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -206,6 +206,9 @@ message GameplayRealm { string state_scope = 9; string character_creation_policy = 10; bool public_production_realm = 11; + int64 catalog_revision = 12; + string realm_id = 13; + string playable_state_namespace_id = 14; } message ListGameplayRealmsResponse { @@ -232,6 +235,9 @@ message GameplayAdmissionPointer { string state_scope = 10; string character_creation_policy = 11; bool public_production_realm = 12; + int64 catalog_revision = 13; + string realm_id = 14; + string playable_state_namespace_id = 15; } message GetAdmissionPointerResponse { diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index 2902aad35b..bb9c6e2c3a 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -3,6 +3,7 @@ syntax = "proto3"; package logging_admin.v1; import "shared/v1/errors.proto"; +import "google/protobuf/timestamp.proto"; option java_package = "net.firedevops.firemud.loggingadmin.v1"; option java_multiple_files = true; @@ -11,6 +12,7 @@ service LoggingAdminService { rpc Ping(PingRequest) returns (PingResponse); rpc QueryLogs(QueryLogsRequest) returns (QueryLogsResponse); rpc CreateLogEvent(CreateLogEventRequest) returns (CreateLogEventResponse); + rpc ReadLogEventReceipt(ReadLogEventReceiptRequest) returns (ReadLogEventReceiptResponse); rpc ApplyModerationAction(ApplyModerationActionRequest) returns (ApplyModerationActionResponse); rpc EvaluateModerationPolicy(EvaluateModerationPolicyRequest) returns (EvaluateModerationPolicyResponse); @@ -35,15 +37,76 @@ message QueryLogsResponse { } message CreateLogEventRequest { - string tenant_id = 1; - string account_id = 2; - string type = 3; - string message = 4; + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string producer_service = 4; + string event_type = 5; + google.protobuf.Timestamp occurred_at = 6; + int32 schema_version = 7; + bytes payload = 8; + int32 payload_digest_version = 9; + string payload_digest = 10; } message CreateLogEventResponse { - string log_event_id = 1; - shared.v1.ErrorDetail error = 2; + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string receipt_id = 4; + string log_event_id = 5; + int32 schema_version = 6; + int32 payload_digest_version = 7; + string payload_digest = 8; + AccountAuditReceiptStatus status = 9; + AccountAuditReceiptOutcome outcome = 10; +} + +message ReadLogEventReceiptRequest { + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string producer_service = 4; + string event_type = 5; + google.protobuf.Timestamp occurred_at = 6; + int32 schema_version = 7; + bytes payload = 8; + int32 payload_digest_version = 9; + string payload_digest = 10; +} + +message ReadLogEventReceiptResponse { + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string receipt_id = 4; + string log_event_id = 5; + int32 schema_version = 6; + int32 payload_digest_version = 7; + string payload_digest = 8; + AccountAuditReceiptStatus status = 9; + AccountAuditReceiptOutcome outcome = 10; +} + +enum AccountAuditScope { + ACCOUNT_AUDIT_SCOPE_UNSPECIFIED = 0; + ACCOUNT_AUDIT_SCOPE_PLATFORM = 1; + ACCOUNT_AUDIT_SCOPE_TENANT = 2; +} + +enum AccountAuditReceiptStatus { + ACCOUNT_AUDIT_RECEIPT_STATUS_UNSPECIFIED = 0; + ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED = 1; + ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED = 2; + ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT = 3; +} + +enum AccountAuditReceiptOutcome { + ACCOUNT_AUDIT_RECEIPT_OUTCOME_UNSPECIFIED = 0; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED = 1; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE = 2; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE = 3; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT = 4; } message ApplyModerationActionRequest { diff --git a/protos/shared/v1/player_execution_context.proto b/protos/shared/v1/player_execution_context.proto new file mode 100644 index 0000000000..7dfbf61210 --- /dev/null +++ b/protos/shared/v1/player_execution_context.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +package shared.v1; + +option java_package = "net.firedevops.firemud.shared.v1"; +option java_multiple_files = true; + +// Unsigned player scope carried only by an authenticated, allowlisted gameplay workload. +// Receivers validate the required subset and equality with their own authoritative target. +message PlayerExecutionContext { + string account_id = 1; + string tenant_id = 2; + string playable_state_namespace_id = 3; + string game_instance_id = 4; + string character_id = 5; + string session_id = 6; + string realm_id = 7; + string request_id = 8; + string playable_state_scope = 9; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java index 44e168eac5..da1fb6e9eb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java @@ -1,14 +1,26 @@ package net.firedevops.firemud.accountservice.client; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; 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.loggingadmin.v1.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; import org.springframework.stereotype.Component; @@ -47,27 +59,74 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( LoggingAdminServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - /** Log that a new account was created. */ - public void logAccountCreation(long tenantId, long accountId) { - CreateLogEventRequest request = + /** Send one unchanged owner-local outbox envelope and verify the exact receiver receipt. */ + public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { + CreateLogEventRequest.Builder builder = CreateLogEventRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(); - stub().createLogEvent(request); + .setScope( + "platform".equals(envelope.scope()) + ? AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM + : AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setAuditEventId(envelope.auditEventId().toString()) + .setProducerService(envelope.producerService()) + .setEventType(envelope.eventType()) + .setOccurredAt( + Timestamp.newBuilder() + .setSeconds(envelope.occurredAt().getEpochSecond()) + .setNanos(envelope.occurredAt().getNano()) + .build()) + .setSchemaVersion(envelope.schemaVersion()) + .setPayload(ByteString.copyFrom(envelope.payload(), StandardCharsets.UTF_8)) + .setPayloadDigestVersion(envelope.payloadDigestVersion()) + .setPayloadDigest(envelope.payloadDigest()); + if (envelope.tenantId() != null) { + builder.setTenantId(envelope.tenantId().toString()); + } + CreateLogEventResponse response = + stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(builder.build()); + if (!response.getAuditEventId().equals(envelope.auditEventId().toString()) + || !response.getPayloadDigest().equals(envelope.payloadDigest()) + || response.getSchemaVersion() != envelope.schemaVersion() + || response.getPayloadDigestVersion() != envelope.payloadDigestVersion() + || response.getScope() != builder.getScope() + || !response.getTenantId().equals(builder.getTenantId())) { + throw new IllegalStateException( + "Account audit receiver returned mismatched receipt evidence"); + } + boolean minimized = + response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED + && response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; + boolean committed = + response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED + && (response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED + || response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); + if ((!committed && !minimized) + || response.getReceiptId().isBlank() + || response.getLogEventId().isBlank()) { + throw new IllegalStateException("Account audit receiver did not prove a terminal receipt"); + } + return new AuditDeliveryResult(response.getReceiptId(), response.getLogEventId(), minimized); } - /** Log that a payment transaction occurred. */ + /** Existing deferred-commerce path remains best effort until its own outbox convergence. */ public void logPayment(long tenantId, long accountId, long transactionId) { - CreateLogEventRequest request = - CreateLogEventRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setType("PAYMENT_TXN") - .setMessage("txId=" + transactionId) - .build(); - stub().createLogEvent(request); + String payload = "{\"accountId\":" + accountId + ",\"transactionId\":" + transactionId + "}"; + deliver( + new AccountAuditEnvelope( + UUID.randomUUID(), + "tenant", + tenantId, + "account-service", + "PAYMENT_TXN", + Instant.now(), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload)); } + + public record AuditDeliveryResult(String receiptId, String logEventId, boolean minimized) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java index afc1eec45a..e51178229b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java @@ -12,6 +12,8 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenResponse; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.EmailVerificationRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.LoginRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapRequest; @@ -19,6 +21,7 @@ import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.ApiResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseCookie; @@ -89,6 +92,19 @@ public ResponseEntity>> listBootstrapCha bootstrapToken, worldSlug, realmSlug, connectScopeId))); } + @PostMapping("/bootstrap/join") + public ResponseEntity> joinPublicProduction( + @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, + @Valid @RequestBody JoinPublicProductionRequest request) { + JoinPublicProductionResult result = + accountService.joinPublicProduction(extractBearerToken(authorization), request); + if (!result.success()) { + throw new AuthenticationException( + result.outcomeCode(), "JOIN was denied for the selected realm"); + } + return ResponseEntity.ok(ApiResponse.success(result)); + } + @PostMapping("/connect-token") public ResponseEntity> connectToken( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index a3499696e7..a520d8ce5e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -60,6 +60,10 @@ public void run(ApplicationArguments args) { membership.setAccount(account); membership.setTenantId(DEMO_TENANT_ID); membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1); + membership.setMembershipAuthorityGeneration(1); + membership.setAuthorityProvenance("SEEDED_DEMO"); accountTenantMembershipRepository.save(membership); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java new file mode 100644 index 0000000000..ff5e2700d3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Receiver-version-1 digest over exact persisted UTF-8 payload bytes. */ +public final class AccountAuditDigest { + private AccountAuditDigest() {} + + public static String ofPayload(String payload) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(payload.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java new file mode 100644 index 0000000000..a99ebc70cb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java @@ -0,0 +1,17 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.time.Instant; +import java.util.UUID; + +/** The immutable Account-owned delivery envelope; the SQL outbox is its authority. */ +public record AccountAuditEnvelope( + UUID auditEventId, + String scope, + Long tenantId, + String producerService, + String eventType, + Instant occurredAt, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + String payload) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java index d025e43865..ed43a78720 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java @@ -8,5 +8,5 @@ public record AccountDto( Long id, @NotNull @Size(max = 50) String username, @NotNull @Email @Size(max = 100) String email, - @NotNull @Size(max = 20) String role, + @Size(max = 20) String role, boolean emailVerified) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java new file mode 100644 index 0000000000..2e92c0105f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Canonical exact-byte digests for retained public-production scope and JOIN attempts. */ +public final class AccountJoinDigest { + private AccountJoinDigest() {} + + public static String scope(VerifiedJoinScope scope) { + return hash( + "scopeDigestVersion=v1\n" + + field("accountId", scope.accountId()) + + "targetClass=PUBLIC_PRODUCTION\n" + + field("connectScopeId", scope.connectScopeId()) + + field("tenantId", scope.tenantId()) + + field("realmId", scope.realmId()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion()) + + field("evaluatedAt", scope.evaluatedAt()) + + field("connectScopeExpiresAt", scope.connectScopeExpiresAt())); + } + + public static String request( + VerifiedJoinScope scope, + String callerBinding, + String entitlementAuthorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion) { + if (!"AVAILABLE".equals(entitlementAuthorityAvailability) + && !"UNAVAILABLE".equals(entitlementAuthorityAvailability) + && !"NOT_EVALUATED".equals(entitlementAuthorityAvailability)) { + throw new IllegalArgumentException("Entitlement authority availability is invalid"); + } + if ("AVAILABLE".equals(entitlementAuthorityAvailability) + != (allowPublicJoin != null && entitlementVersion != null && entitlementVersion > 0L)) { + throw new IllegalArgumentException("Policy evidence must match authority availability"); + } + return hash( + "joinDigestVersion=v1\n" + + "operationKind=JOIN\n" + + field("accountId", scope.accountId()) + + field("callerBinding", callerBinding) + + field("tenantId", scope.tenantId()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("connectScopeId", scope.connectScopeId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion()) + + field("entitlementAuthorityAvailability", entitlementAuthorityAvailability) + + ("AVAILABLE".equals(entitlementAuthorityAvailability) + ? field("allowPublicJoin", allowPublicJoin) + + field("entitlementVersion", entitlementVersion) + : "")); + } + + public static String tokenHash(String connectScopeId) { + return hash(connectScopeId); + } + + private static String field(String name, Object value) { + if (value == null) { + throw new IllegalArgumentException(name + " is required"); + } + String wire = value.toString(); + if (wire.isEmpty() + || wire.indexOf('=') >= 0 + || wire.indexOf('\n') >= 0 + || wire.indexOf('\r') >= 0) { + throw new IllegalArgumentException(name + " has an invalid canonical wire value"); + } + return name + "=" + wire + "\n"; + } + + private static String hash(String preimage) { + 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); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java index 37bdfe1ea7..9cf32940dd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java @@ -2,11 +2,9 @@ import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.Size; public record CreateAccountRequest( - @NotNull @Positive Long tenantId, @NotNull @Size(max = 50) String username, @NotNull @Email @Size(max = 100) String email, @NotNull @Size(min = 6, max = 100) String password) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java new file mode 100644 index 0000000000..6978876722 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.accountservice.dto; + +/** Parsed scope data from a verified Game Session mTLS call, never an independent capability. */ +public record DirectTextCallerContext( + long accountId, + long tenantId, + long realmId, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + String sessionId, + String requestId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java new file mode 100644 index 0000000000..0f1a2a90ca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.accountservice.dto; + +/** + * Opaque, short-lived Account-issued target scope retained only by Game Session transport state. + */ +public record DirectTextJoinScope(String connectScopeId, String connectScopeExpiresAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java new file mode 100644 index 0000000000..ad036ab1cb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.accountservice.dto; + +/** + * Game Session's complete selected-target evidence, re-resolved by Account before scope issuance. + */ +public record DirectTextJoinTarget( + long tenantId, + long realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java new file mode 100644 index 0000000000..f184617738 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.accountservice.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** Only the Account-issued target scope and caller-stable attempt ID cross the public API. */ +public record JoinPublicProductionRequest( + @NotBlank @Size(max = 2048) String connectScopeId, + @NotBlank @Size(max = 128) String requestId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java new file mode 100644 index 0000000000..a5696c235d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.accountservice.dto; + +/** Durable explicit-JOIN outcome; a failure is returned so its receipt can commit first. */ +public record JoinPublicProductionResult( + boolean success, + String outcomeCode, + long accountId, + long tenantId, + long membershipId, + long membershipVersion, + long membershipAuthorityGeneration, + boolean replayed) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java index 50901a2b28..41ed6a0fd3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java @@ -6,4 +6,6 @@ public record RuntimeMembershipDto( boolean membershipExists, boolean gameplayAdmissionAllowed, long membershipVersion, + String membershipLifecycleState, + long membershipAuthorityGeneration, String evaluatedAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java new file mode 100644 index 0000000000..84fd71c5fe --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.accountservice.dto; + +/** Immutable Account-owned target snapshot retained for an explicit public-production JOIN. */ +public record VerifiedJoinScope( + String connectScopeId, + long accountId, + long tenantId, + long realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion, + String evaluatedAt, + String connectScopeExpiresAt, + String snapshotDigest) {} 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 95038fd526..2fb0e62afe 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 @@ -8,7 +8,7 @@ public class Account { private String username; private String email; private String passwordHash; - private String role = "player"; + private String role; private boolean emailVerified = false; private String loginAuthModes = AccountLoginAuthModes.DEFAULT_SERIALIZED; private AccountLifecycleState lifecycleState = AccountLifecycleState.ACTIVE; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java index 2e1f4a1a38..737251b618 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java @@ -16,6 +16,10 @@ public class AccountTenantMembership { private Long tenantId; private boolean gameplayAdmissionAllowed = true; + private String lifecycleState; + private long membershipVersion; + private long membershipAuthorityGeneration; + private String authorityProvenance; @SuppressFBWarnings( value = "EI_EXPOSE_REP", diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java index db6345c66a..2d4daa7a85 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java @@ -27,4 +27,5 @@ public class Subscription { private LocalDateTime startedAt; private LocalDateTime endedAt; private Long tenantId; + private long entitlementVersion = 1L; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java new file mode 100644 index 0000000000..c1386b48f8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.tables.AccountAuditOutbox.ACCOUNT_AUDIT_OUTBOX; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; +import org.jooq.DSLContext; +import org.springframework.stereotype.Repository; + +/** Owner-local audit identity, immutable envelope, and durable delivery state. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountAuditOutboxRepository { + private final DSLContext dsl; + + public AccountAuditOutboxRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AccountAuditEnvelope append( + UUID auditEventId, String scope, Long tenantId, String eventType, String payload) { + if (!("platform".equals(scope) && tenantId == null) + && !("tenant".equals(scope) && tenantId != null && tenantId > 0)) { + throw new IllegalArgumentException("Audit scope and tenant ID must match"); + } + Instant occurredAt = Instant.now(); + String digest = AccountAuditDigest.ofPayload(payload); + AccountAuditOutboxRecord row = dsl.newRecord(ACCOUNT_AUDIT_OUTBOX); + row.setAuditEventId(auditEventId); + row.setScope(scope); + row.setTenantId(tenantId); + row.setProducerService("account-service"); + row.setEventType(eventType); + row.setOccurredAt(toLocalDateTime(occurredAt)); + row.setSchemaVersion(1); + row.setPayloadDigestVersion(1); + row.setPayloadDigest(digest); + row.setPayload(payload); + row.setDeliveryStatus("PENDING"); + row.store(); + return toEnvelope(row); + } + + public List pending(int limit) { + return dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS.eq("PENDING")) + .orderBy(ACCOUNT_AUDIT_OUTBOX.CREATED_AT.asc(), ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.asc()) + .limit(limit) + .fetch(this::toEnvelope); + } + + public void markDelivered( + UUID auditEventId, String receiptId, String logEventId, boolean minimized) { + int changed = + dsl.update(ACCOUNT_AUDIT_OUTBOX) + .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_RECEIPT_ID, receiptId) + .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_LOG_EVENT_ID, logEventId) + .set(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS, minimized ? "MINIMIZED" : "COMMITTED") + .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())) + .where( + ACCOUNT_AUDIT_OUTBOX + .AUDIT_EVENT_ID + .eq(auditEventId) + .and(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS.eq("PENDING"))) + .execute(); + if (changed != 1) { + throw new IllegalStateException("Audit delivery state changed concurrently"); + } + } + + public void recordAttempt(UUID auditEventId) { + dsl.update(ACCOUNT_AUDIT_OUTBOX) + .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())) + .where(ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.eq(auditEventId)) + .execute(); + } + + private AccountAuditEnvelope toEnvelope(AccountAuditOutboxRecord row) { + return new AccountAuditEnvelope( + row.getAuditEventId(), + row.getScope(), + row.getTenantId(), + row.getProducerService(), + row.getEventType(), + toInstant(row.getOccurredAt()), + row.getSchemaVersion(), + row.getPayloadDigestVersion(), + row.getPayloadDigest(), + row.getPayload()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java new file mode 100644 index 0000000000..79de6c47e6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_CONNECT_SCOPE_RECORDS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** Durable, exact-byte scope evidence; its token hash is only a lookup key, never authority. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountConnectScopeRepository { + private final DSLContext dsl; + + public AccountConnectScopeRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public void insert(VerifiedJoinScope scope) { + dsl.insertInto(ACCOUNT_CONNECT_SCOPE_RECORDS) + .set( + ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH, + AccountJoinDigest.tokenHash(scope.connectScopeId())) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.ACCOUNT_ID, scope.accountId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS, "PUBLIC_PRODUCTION") + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.TENANT_ID, scope.tenantId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_ID, scope.realmId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.WORLD_SLUG, scope.worldSlug()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_SLUG, scope.realmSlug()) + .set( + ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_NAMESPACE_ID, + scope.playableStateNamespaceId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_SCOPE, scope.playableStateScope()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.GAME_INSTANCE_ID, scope.gameInstanceId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.CATALOG_REVISION, scope.catalogRevision()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.POINTER_VERSION, scope.pointerVersion()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.EVALUATED_AT, scope.evaluatedAt()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.CONNECT_SCOPE_EXPIRES_AT, scope.connectScopeExpiresAt()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.SNAPSHOT_DIGEST, scope.snapshotDigest()) + .execute(); + } + + public Optional find(String connectScopeId) { + return dsl.selectFrom(ACCOUNT_CONNECT_SCOPE_RECORDS) + .where( + ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH.eq( + AccountJoinDigest.tokenHash(connectScopeId))) + .fetchOptional(record -> toScope(record, connectScopeId)); + } + + private VerifiedJoinScope toScope(Record record, String connectScopeId) { + if (!"PUBLIC_PRODUCTION".equals(record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS))) { + throw new IllegalStateException("JOIN scope is not public production"); + } + VerifiedJoinScope scope = + new VerifiedJoinScope( + connectScopeId, + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.ACCOUNT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TENANT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.WORLD_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_NAMESPACE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_SCOPE), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.GAME_INSTANCE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CATALOG_REVISION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.POINTER_VERSION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.EVALUATED_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CONNECT_SCOPE_EXPIRES_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.SNAPSHOT_DIGEST)); + if (!scope.snapshotDigest().equals(AccountJoinDigest.scope(scope))) { + throw new IllegalStateException("JOIN scope digest mismatch"); + } + return scope; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java new file mode 100644 index 0000000000..22fee20296 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_JOIN_OPERATIONS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import org.jooq.DSLContext; +import org.springframework.stereotype.Repository; + +/** Serializes explicit JOIN on the global account row and retains exact operation outcomes. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountJoinOperationRepository { + private final DSLContext dsl; + + public AccountJoinOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public void lockAccount(long accountId) { + Long locked = + dsl.select(ACCOUNTS.ID) + .from(ACCOUNTS) + .where(ACCOUNTS.ID.eq(accountId)) + .forUpdate() + .fetchOne(ACCOUNTS.ID); + if (locked == null) { + throw new IllegalArgumentException("JOIN account does not exist"); + } + } + + public Optional find(String requestId) { + return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) + .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) + .fetchOptional( + row -> + new JoinOperation( + row.getAccountId(), + row.getTenantId(), + row.getVerifiedCallerBinding(), + row.getScopeTokenHash(), + row.getConnectScopeDigest(), + row.getEntitlementAuthorityAvailability(), + row.getAllowPublicJoin(), + row.getEntitlementVersion(), + row.getRequestDigestVersion(), + row.getRequestDigest(), + row.getStatus(), + row.getOutcome(), + row.getMembershipId(), + row.getOutcomeMembershipVersion(), + row.getOutcomeMembershipAuthorityGeneration())); + } + + public boolean hasRetainedOperation(long accountId) { + return dsl.fetchExists( + ACCOUNT_JOIN_OPERATIONS, ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID.eq(accountId)); + } + + public boolean insertPending( + String requestId, + VerifiedJoinScope scope, + String callerBinding, + String requestDigest, + String entitlementAuthorityAvailability, + Long entitlementVersion, + Boolean allowPublicJoin, + boolean callerBoundAuthorityInvalidated) { + int inserted = + dsl.insertInto(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID, requestId) + .set(ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID, scope.accountId()) + .set(ACCOUNT_JOIN_OPERATIONS.TENANT_ID, scope.tenantId()) + .set(ACCOUNT_JOIN_OPERATIONS.VERIFIED_CALLER_BINDING, callerBinding) + .set( + ACCOUNT_JOIN_OPERATIONS.SCOPE_TOKEN_HASH, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId())) + .set(ACCOUNT_JOIN_OPERATIONS.CONNECT_SCOPE_DIGEST, scope.snapshotDigest()) + .set(ACCOUNT_JOIN_OPERATIONS.WORLD_SLUG, scope.worldSlug()) + .set(ACCOUNT_JOIN_OPERATIONS.REALM_SLUG, scope.realmSlug()) + .set(ACCOUNT_JOIN_OPERATIONS.REALM_ID, scope.realmId()) + .set( + ACCOUNT_JOIN_OPERATIONS.PLAYABLE_STATE_NAMESPACE_ID, + scope.playableStateNamespaceId()) + .set(ACCOUNT_JOIN_OPERATIONS.PLAYABLE_STATE_SCOPE, scope.playableStateScope()) + .set(ACCOUNT_JOIN_OPERATIONS.GAME_INSTANCE_ID, scope.gameInstanceId()) + .set(ACCOUNT_JOIN_OPERATIONS.CATALOG_REVISION, scope.catalogRevision()) + .set(ACCOUNT_JOIN_OPERATIONS.POINTER_VERSION, scope.pointerVersion()) + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_VERSION, entitlementVersion) + .set(ACCOUNT_JOIN_OPERATIONS.ALLOW_PUBLIC_JOIN, allowPublicJoin) + .set( + ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, + entitlementAuthorityAvailability) + .set( + ACCOUNT_JOIN_OPERATIONS.CALLER_BOUND_AUTHORITY_INVALIDATED, + callerBoundAuthorityInvalidated) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST_VERSION, 1) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST, requestDigest) + .set(ACCOUNT_JOIN_OPERATIONS.STATUS, "PENDING") + .onConflict(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID) + .doNothing() + .execute(); + return inserted == 1; + } + + public void finish( + String requestId, + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration) { + if (!"COMMITTED".equals(status) && !"FAILED".equals(status)) { + throw new IllegalArgumentException("JOIN terminal status is invalid"); + } + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.STATUS, status) + .set(ACCOUNT_JOIN_OPERATIONS.OUTCOME, outcome) + .set(ACCOUNT_JOIN_OPERATIONS.MEMBERSHIP_ID, membershipId) + .set(ACCOUNT_JOIN_OPERATIONS.OUTCOME_MEMBERSHIP_VERSION, membershipVersion) + .set( + ACCOUNT_JOIN_OPERATIONS.OUTCOME_MEMBERSHIP_AUTHORITY_GENERATION, + membershipAuthorityGeneration) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed concurrently"); + } + } + + public void recordCallerBoundAuthorityInvalidation(String requestId) { + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.CALLER_BOUND_AUTHORITY_INVALIDATED, true) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed concurrently"); + } + } + + public record JoinOperation( + long accountId, + long tenantId, + String callerBinding, + String scopeTokenHash, + String connectScopeDigest, + String entitlementAuthorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion, + int requestDigestVersion, + String requestDigest, + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 086e84468c..1a4b5e3e10 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -65,6 +65,12 @@ public AccountTenantMembership save(AccountTenantMembership entity) { .set( ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, entity.isGameplayAdmissionAllowed()) + .set(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, entity.getLifecycleState()) + .set(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, entity.getMembershipVersion()) + .set( + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + entity.getMembershipAuthorityGeneration()) + .set(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, entity.getAuthorityProvenance()) .returningResult(ACCOUNT_TENANT_MEMBERSHIP.ID) .fetchOne(ACCOUNT_TENANT_MEMBERSHIP.ID); entity.setId(id); @@ -77,6 +83,12 @@ public AccountTenantMembership save(AccountTenantMembership entity) { .set( ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, entity.isGameplayAdmissionAllowed()) + .set(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, entity.getLifecycleState()) + .set(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, entity.getMembershipVersion()) + .set( + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + entity.getMembershipAuthorityGeneration()) + .set(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, entity.getAuthorityProvenance()) .where(ACCOUNT_TENANT_MEMBERSHIP.ID.eq(entity.getId())) .execute(); if (updated != 1) { @@ -119,6 +131,10 @@ private org.jooq.SelectOnConditionStep baseSelect() { ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID, ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID, ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, + ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, ACCOUNTS.ID, ACCOUNTS.USERNAME, ACCOUNTS.EMAIL, @@ -146,6 +162,11 @@ private AccountTenantMembership toEntity(Record record) { membership.setTenantId(record.get(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID)); membership.setGameplayAdmissionAllowed( Boolean.TRUE.equals(record.get(ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED))); + membership.setLifecycleState(record.get(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE)); + membership.setMembershipVersion(record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION)); + membership.setMembershipAuthorityGeneration( + record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION)); + membership.setAuthorityProvenance(record.get(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE)); return membership; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java index 1954a5e2e5..1b5084e019 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java @@ -28,6 +28,15 @@ public List findByTenantId(Long tenantId) { .fetch(this::toEntity); } + /** Shares the row lock with subscription writers through the JOIN commit boundary. */ + public List findByTenantIdForUpdate(Long tenantId) { + return baseSelect() + .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) + .orderBy(SUBSCRIPTION.ID.asc()) + .forUpdate() + .fetch(this::toEntity); + } + public List findByAccountId(Long accountId) { return baseSelect() .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)) @@ -46,9 +55,11 @@ public Subscription save(Subscription entity) { .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) + .set(SUBSCRIPTION.ENTITLEMENT_VERSION, 1L) .returningResult(SUBSCRIPTION.ID) .fetchOne(SUBSCRIPTION.ID); entity.setId(id); + entity.setEntitlementVersion(1L); return entity; } int updated = @@ -59,11 +70,17 @@ public Subscription save(Subscription entity) { .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) - .where(SUBSCRIPTION.ID.eq(entity.getId())) + .set(SUBSCRIPTION.ENTITLEMENT_VERSION, SUBSCRIPTION.ENTITLEMENT_VERSION.add(1L)) + .where( + SUBSCRIPTION + .ID + .eq(entity.getId()) + .and(SUBSCRIPTION.ENTITLEMENT_VERSION.eq(entity.getEntitlementVersion()))) .execute(); if (updated != 1) { throw JooqAccountRepositorySupport.staleWrite("subscription", entity.getId()); } + entity.setEntitlementVersion(entity.getEntitlementVersion() + 1L); return entity; } @@ -86,6 +103,7 @@ private org.jooq.SelectOnConditionStep baseSelect() { SUBSCRIPTION.STARTED_AT, SUBSCRIPTION.ENDED_AT, SUBSCRIPTION.TENANT_ID, + SUBSCRIPTION.ENTITLEMENT_VERSION, ACCOUNTS.ID, ACCOUNTS.USERNAME, ACCOUNTS.EMAIL, @@ -115,6 +133,7 @@ private Subscription toEntity(Record record) { entity.setStartedAt(record.get(SUBSCRIPTION.STARTED_AT)); entity.setEndedAt(record.get(SUBSCRIPTION.ENDED_AT)); entity.setTenantId(record.get(SUBSCRIPTION.TENANT_ID)); + entity.setEntitlementVersion(record.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); return entity; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java new file mode 100644 index 0000000000..c57c6b8ec9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** At-least-once delivery of Account's immutable audit outbox envelopes. */ +@Component +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected collaborators are internal Spring singletons.") +public class AccountAuditDeliveryJob { + private static final Logger logger = LoggerFactory.getLogger(AccountAuditDeliveryJob.class); + private final AccountAuditOutboxRepository outbox; + private final LoggingAdminClient loggingAdminClient; + + public AccountAuditDeliveryJob( + AccountAuditOutboxRepository outbox, LoggingAdminClient loggingAdminClient) { + this.outbox = outbox; + this.loggingAdminClient = loggingAdminClient; + } + + @Scheduled(fixedDelayString = "${firemud.account.audit-delivery-delay-ms:5000}") + public void deliverPending() { + for (var envelope : outbox.pending(50)) { + try { + var receipt = loggingAdminClient.deliver(envelope); + outbox.markDelivered( + envelope.auditEventId(), + receipt.receiptId(), + receipt.logEventId(), + receipt.minimized()); + } catch (RuntimeException ex) { + outbox.recordAttempt(envelope.auditEventId()); + logger.warn("Account audit delivery remains pending for event {}", envelope.auditEventId()); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index 83f8fe3f7a..c3d2909abc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -10,6 +10,11 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +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.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.ProfileDto; @@ -47,6 +52,15 @@ java.util.List listBootstrapCharacters( ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenRequest request); + JoinPublicProductionResult joinPublicProduction( + String bootstrapToken, JoinPublicProductionRequest request); + + DirectTextJoinScope issueDirectTextConnectScope( + DirectTextCallerContext caller, DirectTextJoinTarget target); + + JoinPublicProductionResult joinPublicProductionFromGameSession( + DirectTextCallerContext caller, JoinPublicProductionRequest request); + RuntimeMembershipDto getTenantMembershipForRuntime( Long accountId, Long tenantId, String requestId); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index b6b026287e..903585fbca 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -24,6 +24,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.PingRequest; import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; @@ -32,6 +36,9 @@ import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; @@ -40,12 +47,14 @@ import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; @@ -57,9 +66,15 @@ public class AccountGrpcService extends AccountServiceGrpc.AccountServiceImplBas private final PingService pingService; private final AccountService accountService; private final MeterRegistry meterRegistry; + private final String workloadNamespace; public AccountGrpcService(PingService pingService, AccountService accountService) { - this(pingService, accountService, null); + this(pingService, accountService, null, null); + } + + public AccountGrpcService( + PingService pingService, AccountService accountService, MeterRegistry meterRegistry) { + this(pingService, accountService, meterRegistry, null); } @Autowired @@ -67,10 +82,136 @@ public AccountGrpcService(PingService pingService, AccountService accountService value = "EI_EXPOSE_REP2", justification = "Injected services and registry remain internal collaborators.") public AccountGrpcService( - PingService pingService, AccountService accountService, MeterRegistry meterRegistry) { + PingService pingService, + AccountService accountService, + MeterRegistry meterRegistry, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.pingService = pingService; this.accountService = accountService; this.meterRegistry = meterRegistry; + this.workloadNamespace = workloadNamespace; + } + + @Override + @Timed(value = "accountGrpc.issueDirectTextConnectScope") + public void issueDirectTextConnectScope( + IssueDirectTextConnectScopeRequest request, + StreamObserver responseObserver) { + IssueDirectTextConnectScopeResponse.Builder response = + IssueDirectTextConnectScopeResponse.newBuilder(); + try { + requireGameSessionPeer(); + DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + long realmId = requirePositiveRequestId(request.getRealmId(), "realmId"); + long gameInstanceId = requirePositiveRequestId(request.getGameInstanceId(), "gameInstanceId"); + if (caller.tenantId() != tenantId + || caller.realmId() != realmId + || caller.gameInstanceId() != gameInstanceId + || !caller.playableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) + || !caller.playableStateScope().equals(request.getPlayableStateScope())) { + throw new InvalidRequestException("Player context and selected realm disagree", null); + } + var scope = + accountService.issueDirectTextConnectScope( + caller, + new DirectTextJoinTarget( + tenantId, + realmId, + requireText(request.getWorldSlug(), "worldSlug"), + requireText(request.getRealmSlug(), "realmSlug"), + requireText(request.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + requireText(request.getPlayableStateScope(), "playableStateScope"), + gameInstanceId, + request.getCatalogRevision(), + request.getPointerVersion())); + response + .setConnectScopeId(scope.connectScopeId()) + .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()); + } catch (AdminAuthorizationException ex) { + response.setError( + appError("IssueDirectTextConnectScope", "PERMISSION_DENIED", ex.getMessage())); + } catch (AuthenticationException ex) { + response.setError(appError("IssueDirectTextConnectScope", ex.getCode(), ex.getMessage())); + } catch (InvalidRequestException | IllegalArgumentException ex) { + response.setError( + appError("IssueDirectTextConnectScope", "INVALID_ARGUMENT", ex.getMessage())); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "accountGrpc.joinPublicProductionMembership") + public void joinPublicProductionMembership( + JoinPublicProductionMembershipRequest request, + StreamObserver responseObserver) { + JoinPublicProductionMembershipResponse.Builder response = + JoinPublicProductionMembershipResponse.newBuilder(); + try { + requireGameSessionPeer(); + DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); + String requestId = requireText(request.getRequestId(), "requestId"); + if (!requestId.equals(caller.requestId())) { + throw new InvalidRequestException("Player context and JOIN request ID disagree", null); + } + var result = + accountService.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest( + requireText(request.getConnectScopeId(), "connectScopeId"), requestId)); + response + .setSuccess(result.success()) + .setOutcomeCode(result.outcomeCode()) + .setAccountId(Long.toString(result.accountId())) + .setTenantId(Long.toString(result.tenantId())) + .setMembershipId(Long.toString(result.membershipId())) + .setMembershipVersion(result.membershipVersion()) + .setMembershipAuthorityGeneration(result.membershipAuthorityGeneration()) + .setReplayed(result.replayed()); + } catch (AdminAuthorizationException ex) { + response.setError( + appError("JoinPublicProductionMembership", "PERMISSION_DENIED", ex.getMessage())); + } catch (AuthenticationException ex) { + response.setError(appError("JoinPublicProductionMembership", ex.getCode(), ex.getMessage())); + } catch (InvalidRequestException | IllegalArgumentException ex) { + response.setError( + appError("JoinPublicProductionMembership", "INVALID_ARGUMENT", ex.getMessage())); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + + private void requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || workloadNamespace == null + || workloadNamespace.isBlank() + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service")) { + throw new AdminAuthorizationException("Verified Game Session workload identity is required"); + } + } + + private DirectTextCallerContext directTextCaller( + net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { + return new DirectTextCallerContext( + requirePositiveRequestId(context.getAccountId(), "accountId"), + requirePositiveRequestId(context.getTenantId(), "tenantId"), + requirePositiveRequestId(context.getRealmId(), "realmId"), + requireText(context.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + requireText(context.getPlayableStateScope(), "playableStateScope"), + requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"), + requireText(context.getSessionId(), "sessionId"), + context.getRequestId()); + } + + private String requireText(String value, String fieldName) { + int maxLength = "connectScopeId".equals(fieldName) ? 2048 : 128; + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new InvalidRequestException(fieldName + " is required and bounded", null); + } + return value; } @Override @@ -89,10 +230,7 @@ public void createAccount( try { net.firedevops.firemud.accountservice.dto.CreateAccountRequest dto = new net.firedevops.firemud.accountservice.dto.CreateAccountRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getUsername(), - request.getEmail(), - request.getPassword()); + request.getUsername(), request.getEmail(), request.getPassword()); var account = accountService.createAccount(dto); CreateAccountResponse response = CreateAccountResponse.newBuilder().setAccountId(account.id().toString()).build(); @@ -221,6 +359,8 @@ public void getTenantMembershipForRuntime( .setMembershipExists(dto.membershipExists()) .setGameplayAdmissionAllowed(dto.gameplayAdmissionAllowed()) .setMembershipVersion(dto.membershipVersion()) + .setMembershipLifecycleState(dto.membershipLifecycleState()) + .setMembershipAuthorityGeneration(dto.membershipAuthorityGeneration()) .setEvaluatedAt(dto.evaluatedAt()) .build(); responseObserver.onNext(response); 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 7e75f6f6d8..618989a4c0 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 @@ -20,11 +20,11 @@ import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; -import net.firedevops.firemud.accountservice.client.LoggingAdminClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -33,6 +33,11 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +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.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.ProfileDto; @@ -44,6 +49,7 @@ import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; @@ -57,7 +63,10 @@ import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +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.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -75,9 +84,6 @@ import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.saga.SagaBuilder; -import net.firedevops.firemud.common.saga.SagaException; -import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; @@ -92,6 +98,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.StringUtils; import org.springframework.web.server.ResponseStatusException; +import tools.jackson.databind.json.JsonMapper; @Service public class AccountServiceImpl implements AccountService { @@ -105,8 +112,12 @@ public class AccountServiceImpl implements AccountService { private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service"; private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); + private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); private final AccountRepository accountRepository; + private final AccountAuditOutboxRepository accountAuditOutboxRepository; + private final AccountConnectScopeRepository accountConnectScopeRepository; + private final AccountJoinOperationRepository accountJoinOperationRepository; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -123,18 +134,19 @@ public class AccountServiceImpl implements AccountService { private final MailProperties mailProperties; private final AccountTokenProperties tokenProperties; private final JwtAuthProperties jwtAuthProperties; - private final LoggingAdminClient loggingAdminClient; private final GameSessionClient gameSessionClient; private final EntityManagementClient entityManagementClient; private final JwtUtil jwtUtil; private final net.firedevops.firemud.accountservice.service.session.SessionService sessionService; - private final SagaRunner sagaRunner; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Dependencies are injected and kept internal") public AccountServiceImpl( AccountRepository accountRepository, + AccountAuditOutboxRepository accountAuditOutboxRepository, + AccountConnectScopeRepository accountConnectScopeRepository, + AccountJoinOperationRepository accountJoinOperationRepository, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, AccountTenantMembershipRepository accountTenantMembershipRepository, @@ -151,13 +163,14 @@ public AccountServiceImpl( MailProperties mailProperties, AccountTokenProperties tokenProperties, JwtAuthProperties jwtAuthProperties, - LoggingAdminClient loggingAdminClient, GameSessionClient gameSessionClient, EntityManagementClient entityManagementClient, JwtUtil jwtUtil, - net.firedevops.firemud.accountservice.service.session.SessionService sessionService, - SagaRunner sagaRunner) { + net.firedevops.firemud.accountservice.service.session.SessionService sessionService) { this.accountRepository = accountRepository; + this.accountAuditOutboxRepository = accountAuditOutboxRepository; + this.accountConnectScopeRepository = accountConnectScopeRepository; + this.accountJoinOperationRepository = accountJoinOperationRepository; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; this.accountTenantMembershipRepository = accountTenantMembershipRepository; @@ -174,65 +187,34 @@ public AccountServiceImpl( this.mailProperties = mailProperties; this.tokenProperties = tokenProperties; this.jwtAuthProperties = jwtAuthProperties; - this.loggingAdminClient = loggingAdminClient; this.gameSessionClient = gameSessionClient; this.entityManagementClient = entityManagementClient; this.jwtUtil = jwtUtil; this.sessionService = sessionService; - this.sagaRunner = sagaRunner; } @Override @Transactional @Timed(value = "account.create") public AccountDto createAccount(CreateAccountRequest request) { - logger.info("Creating account {} for tenant {}", request.username(), request.tenantId()); + logger.info("Creating global account {}", request.username()); Account account = new Account(); account.setUsername(request.username()); account.setEmail(EmailCanonicalization.normalize(request.email())); account.setPasswordHash(hashPassword(request.password())); - account.setRole("player"); - Profile profile = new Profile(); - profile.setTenantId(request.tenantId()); - profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setTenantId(request.tenantId()); - membership.setGameplayAdmissionAllowed(true); - - SagaBuilder builder = new SagaBuilder("accountCreation"); - builder.step( - "persistAccount", - () -> { - Account saved; - try { - saved = accountRepository.save(account); - } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { - throw new AccountAlreadyExistsException(ex); - } - account.setId(saved.getId()); - membership.setAccount(saved); - accountTenantMembershipRepository.save(membership); - profile.setAccount(saved); - profileRepository.save(profile); - }, - () -> { - profileRepository.delete(profile); - accountTenantMembershipRepository.delete(membership); - accountRepository.delete(account); - }); - var saga = builder.build(); + Account saved; try { - sagaRunner.run(saga); - } catch (SagaException e) { - if (e.getCause() instanceof AccountAlreadyExistsException alreadyExists) { - throw alreadyExists; - } - logger.warn("Account creation saga failed", e); - throw new IllegalStateException("Account creation failed", e); + saved = accountRepository.save(account); + } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { + throw new AccountAlreadyExistsException(ex); } - runAfterCommit(() -> safeLogAccountCreation(request.tenantId(), account.getId())); - - return accountMapper.toDto(account); + accountAuditOutboxRepository.append( + UUID.randomUUID(), + "platform", + null, + "ACCOUNT_REGISTERED", + "{\"accountId\":" + saved.getId() + "}"); + return accountMapper.toDto(saved); } @Override @@ -390,7 +372,7 @@ public List listBootstrapWorlds(String bootstrapToken) { } @Override - @Transactional(readOnly = true) + @Transactional @Timed(value = "account.bootstrap_realms") public List listBootstrapRealms(String bootstrapToken, String worldSlug) { BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); @@ -398,6 +380,7 @@ public List listBootstrapRealms(String bootstrapToken, String Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); return gameSessionClient.listGameplayRealms(worldSlug).stream() .map(this::readRuntimeRealmTarget) + .map(realm -> requireRealmTarget(realm.tenantId(), realm.worldSlug(), realm.realmSlug())) .filter(realm -> isRealmAdmissible(bootstrapContext, realm)) .map( realm -> @@ -413,7 +396,7 @@ public List listBootstrapRealms(String bootstrapToken, String realm.characterCreationPolicy(), evaluatedAt.toString(), expiresAt.toString(), - mintConnectScopeId(bootstrapContext, realm, evaluatedAt, expiresAt))) + mintAndRetainConnectScope(bootstrapContext, realm, evaluatedAt, expiresAt))) .toList(); } @@ -447,6 +430,391 @@ public List listBootstrapCharacters( .toList(); } + @Override + @Transactional + @Timed(value = "account.public_production_join") + public JoinPublicProductionResult joinPublicProduction( + String bootstrapToken, JoinPublicProductionRequest request) { + BootstrapContext caller = requireBootstrapContext(bootstrapToken); + Claims callerClaims = + requireSignedTokenClaims( + bootstrapToken, + "player-bootstrap", + "CONNECT_CONTEXT_INVALID", + "Missing bootstrap token", + "Invalid bootstrap token"); + String callerBinding; + try { + callerBinding = JwtClaims.requireText(callerClaims.get("jti"), "jti"); + } catch (IllegalArgumentException ex) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Bootstrap caller binding is missing", ex); + } + return joinPublicProductionForTrustedCaller(caller.accountId(), callerBinding, null, request); + } + + @Override + @Transactional + @Timed(value = "account.direct_text_connect_scope") + public DirectTextJoinScope issueDirectTextConnectScope( + DirectTextCallerContext caller, DirectTextJoinTarget target) { + if (caller == null + || target == null + || caller.accountId() <= 0L + || caller.tenantId() != target.tenantId() + || caller.realmId() != target.realmId() + || caller.gameInstanceId() != target.gameInstanceId() + || !caller.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !caller.playableStateScope().equals(target.playableStateScope())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + RuntimeRealmTarget current = + requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); + if (!isPublicProductionRealm(current)) { + throw new AuthenticationException( + "REALM_UNAVAILABLE", "Selected public realm is unavailable"); + } + if (current.realmId() != target.realmId() + || !current.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !current.stateScope().equals(target.playableStateScope()) + || current.gameInstanceId() != target.gameInstanceId() + || current.catalogRevision() != target.catalogRevision() + || current.pointerVersion() != target.pointerVersion()) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + Instant evaluatedAt = Instant.now(); + Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + String scopeId = + mintAndRetainConnectScope( + new BootstrapContext(caller.accountId()), current, evaluatedAt, expiresAt); + return new DirectTextJoinScope(scopeId, expiresAt.toString()); + } + + @Override + @Transactional + @Timed(value = "account.public_production_join_internal") + public JoinPublicProductionResult joinPublicProductionFromGameSession( + DirectTextCallerContext caller, JoinPublicProductionRequest request) { + if (caller == null + || caller.accountId() <= 0L + || !StringUtils.hasText(caller.sessionId()) + || request == null + || !caller.requestId().equals(request.requestId())) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "JOIN caller context is missing"); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + return joinPublicProductionForTrustedCaller( + caller.accountId(), caller.sessionId(), caller, request); + } + + private JoinPublicProductionResult joinPublicProductionForTrustedCaller( + long accountId, + String callerBinding, + DirectTextCallerContext directTextCaller, + JoinPublicProductionRequest request) { + if (request == null + || !StringUtils.hasText(request.connectScopeId()) + || !StringUtils.hasText(request.requestId())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + accountJoinOperationRepository.lockAccount(accountId); + Optional existing = + accountJoinOperationRepository.find(request.requestId()); + if (existing.isPresent()) { + var operation = existing.orElseThrow(); + if (operation.accountId() != accountId + || !operation.callerBinding().equals(callerBinding) + || !operation + .scopeTokenHash() + .equals(AccountJoinDigest.tokenHash(request.connectScopeId()))) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + VerifiedJoinScope retained = + accountConnectScopeRepository + .find(request.connectScopeId()) + .orElseThrow( + () -> + new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); + validateDirectTextJoinScope(directTextCaller, retained); + JoinEvaluation evaluation = evaluateJoin(retained); + if ("NOT_EVALUATED".equals(evaluation.authorityAvailability()) + && !"NOT_EVALUATED".equals(operation.entitlementAuthorityAvailability())) { + throw new AuthenticationException( + evaluation.failureCode(), "Current JOIN authority could not be revalidated"); + } + if ("UNAVAILABLE".equals(evaluation.authorityAvailability()) + && "AVAILABLE".equals(operation.entitlementAuthorityAvailability())) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Current policy cannot be compared with retained JOIN evidence"); + } + String requestDigest = + AccountJoinDigest.request( + retained, + callerBinding, + evaluation.authorityAvailability(), + evaluation.allowPublicJoin(), + evaluation.entitlementVersion()); + if (!operation.connectScopeDigest().equals(retained.snapshotDigest()) + || operation.requestDigestVersion() != 1 + || !operation.requestDigest().equals(requestDigest)) { + throw new AuthenticationException("IDEMPOTENCY_CONFLICT", "JOIN request digest changed"); + } + if ("PENDING".equals(operation.status())) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN outcome is pending reconciliation"); + } + return new JoinPublicProductionResult( + "COMMITTED".equals(operation.status()), + operation.outcome(), + operation.accountId(), + operation.tenantId(), + operation.membershipId() == null ? 0L : operation.membershipId(), + operation.membershipVersion() == null ? 0L : operation.membershipVersion(), + operation.membershipAuthorityGeneration() == null + ? 0L + : operation.membershipAuthorityGeneration(), + true); + } + ConnectScopeContext signedScope = requireConnectScopeContext(request.connectScopeId()); + VerifiedJoinScope retained = + accountConnectScopeRepository + .find(request.connectScopeId()) + .orElseThrow( + () -> + new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); + validateDirectTextJoinScope(directTextCaller, retained); + if (retained.accountId() != accountId + || signedScope.accountId() != accountId + || signedScope.tenantId() != retained.tenantId() + || signedScope.realmId() != retained.realmId() + || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) + || !signedScope.playableStateScope().equals(retained.playableStateScope()) + || signedScope.gameInstanceId() != retained.gameInstanceId() + || signedScope.catalogRevision() != retained.catalogRevision() + || signedScope.pointerVersion() != retained.pointerVersion() + || !signedScope.worldSlug().equals(retained.worldSlug()) + || !signedScope.realmSlug().equals(retained.realmSlug()) + || !signedScope.evaluatedAt().toString().equals(retained.evaluatedAt()) + || !signedScope + .connectScopeExpiresAt() + .toString() + .equals(retained.connectScopeExpiresAt())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + JoinEvaluation evaluation = evaluateJoin(signedScope); + String requestDigest = + AccountJoinDigest.request( + retained, + callerBinding, + evaluation.authorityAvailability(), + evaluation.allowPublicJoin(), + evaluation.entitlementVersion()); + boolean operationClaimed = + accountJoinOperationRepository.insertPending( + request.requestId(), + retained, + callerBinding, + requestDigest, + evaluation.authorityAvailability(), + evaluation.entitlementVersion(), + evaluation.allowPublicJoin(), + false); + if (!operationClaimed) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + if (evaluation.failureCode() != null) { + return failedJoin(request.requestId(), retained, evaluation.failureCode()); + } + if (!evaluation.gameplayAvailable()) { + return failedJoin(request.requestId(), retained, "TENANT_BILLING_BLOCKED"); + } + if (!evaluation.allowPublicJoin()) { + return failedJoin(request.requestId(), retained, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + JoinEvaluation commitEvaluation = evaluateJoin(signedScope); + if (commitEvaluation.failureCode() != null) { + return failedJoin(request.requestId(), retained, commitEvaluation.failureCode()); + } + if (!"AVAILABLE".equals(commitEvaluation.authorityAvailability()) + || !java.util.Objects.equals( + evaluation.entitlementVersion(), commitEvaluation.entitlementVersion()) + || !java.util.Objects.equals( + evaluation.allowPublicJoin(), commitEvaluation.allowPublicJoin())) { + return failedJoin(request.requestId(), retained, "ENTITLEMENT_UNAVAILABLE"); + } + if (!commitEvaluation.gameplayAvailable()) { + return failedJoin(request.requestId(), retained, "TENANT_BILLING_BLOCKED"); + } + if (!commitEvaluation.allowPublicJoin()) { + return failedJoin(request.requestId(), retained, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + AccountTenantMembership membership = + accountTenantMembershipRepository + .findByAccountIdAndTenantId(accountId, retained.tenantId()) + .orElse(null); + boolean transitioned = false; + if (membership == null) { + membership = new AccountTenantMembership(); + membership.setAccount(requireAccount(accountId)); + membership.setTenantId(retained.tenantId()); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + accountTenantMembershipRepository.save(membership); + transitioned = true; + } else if ("INACTIVE".equals(membership.getLifecycleState())) { + accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(request.requestId()); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(membership.getMembershipVersion() + 1L); + membership.setMembershipAuthorityGeneration( + membership.getMembershipAuthorityGeneration() + 1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + accountTenantMembershipRepository.save(membership); + transitioned = true; + } else if (!"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed()) { + return failedJoin(request.requestId(), retained, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + } + if (transitioned) { + String payload = + AUDIT_JSON.writeValueAsString( + new JoinAuditPayload( + accountId, + retained.tenantId(), + retained.worldSlug(), + retained.realmSlug(), + membership.getMembershipVersion(), + request.requestId())); + UUID auditEventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + request.requestId()).getBytes(StandardCharsets.UTF_8)); + accountAuditOutboxRepository.append( + auditEventId, "tenant", retained.tenantId(), "ACCOUNT_JOINED_PUBLIC_PRODUCTION", payload); + } + accountJoinOperationRepository.finish( + request.requestId(), + "COMMITTED", + transitioned ? "JOINED" : "ALREADY_ACTIVE", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + return new JoinPublicProductionResult( + true, + transitioned ? "JOINED" : "ALREADY_ACTIVE", + accountId, + retained.tenantId(), + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + false); + } + + private JoinPublicProductionResult failedJoin( + String requestId, VerifiedJoinScope scope, String outcomeCode) { + accountJoinOperationRepository.finish(requestId, "FAILED", outcomeCode, null, null, null); + return new JoinPublicProductionResult( + false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); + } + + private void validateDirectTextJoinScope( + DirectTextCallerContext caller, VerifiedJoinScope scope) { + if (caller != null + && (caller.accountId() != scope.accountId() + || caller.tenantId() != scope.tenantId() + || caller.realmId() != scope.realmId() + || caller.gameInstanceId() != scope.gameInstanceId() + || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) + || !caller.playableStateScope().equals(scope.playableStateScope()))) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private JoinEvaluation evaluateJoin(VerifiedJoinScope scope) { + return evaluateJoin( + new ConnectScopeContext( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + Instant.parse(scope.evaluatedAt()), + Instant.parse(scope.connectScopeExpiresAt()))); + } + + private JoinEvaluation evaluateJoin(ConnectScopeContext scope) { + RuntimeRealmTarget target; + try { + target = requireCurrentConnectScopeTarget(scope); + } catch (AuthenticationException ex) { + if ("CONNECT_SCOPE_MISMATCH".equals(ex.getCode()) + || "ADMISSION_POINTER_UNAVAILABLE".equals(ex.getCode())) { + return new JoinEvaluation("NOT_EVALUATED", null, null, false, ex.getCode()); + } + throw ex; + } + if (!isPublicProductionRealm(target)) { + return new JoinEvaluation( + "NOT_EVALUATED", null, null, false, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + try { + RuntimeEntitlementsDto entitlement = lockedJoinEntitlement(scope.tenantId()); + return new JoinEvaluation( + "AVAILABLE", + entitlement.allowPublicJoin(), + entitlement.entitlementVersion(), + entitlement.gameplayAvailable(), + null); + } catch (AuthenticationException ex) { + if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { + return new JoinEvaluation("UNAVAILABLE", null, null, false, ex.getCode()); + } + throw ex; + } + } + + private record JoinEvaluation( + String authorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion, + boolean gameplayAvailable, + String failureCode) {} + + private RuntimeEntitlementsDto lockedJoinEntitlement(long tenantId) { + List rows = + subscriptionRepository.findByTenantIdForUpdate(tenantId); + if (rows.size() != 1) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); + } + var subscription = rows.getFirst(); + if (subscription.getEntitlementVersion() <= 0L) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Entitlement version is missing"); + } + return new RuntimeEntitlementsDto( + tenantId, + isGameplayAvailableStatus(subscription.getStatus()), + isPublicJoinAllowedStatus(subscription.getStatus()), + subscription.getEntitlementVersion(), + subscription.getEntitlementVersion(), + Instant.now().toString()); + } + @Override @Transactional(readOnly = true) @Timed(value = "account.connect_token") @@ -517,6 +885,12 @@ private ConnectTokenResult issueConnectTokenFresh( 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() || !membership.gameplayAdmissionAllowed()) { if (!isPublicProductionRealm(realm)) { if (membership.membershipExists()) { @@ -624,7 +998,9 @@ public RuntimeMembershipDto getTenantMembershipForRuntime( tenantId, membership.isPresent(), membership.map(AccountTenantMembership::isGameplayAdmissionAllowed).orElse(false), - membership.map(AccountTenantMembership::getId).orElse(0L), + membership.map(AccountTenantMembership::getMembershipVersion).orElse(0L), + membership.map(AccountTenantMembership::getLifecycleState).orElse("MISSING"), + membership.map(AccountTenantMembership::getMembershipAuthorityGeneration).orElse(0L), Instant.now().toString()); } @@ -713,7 +1089,7 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str subscriptions.getFirst(); boolean gameplayAvailable = isGameplayAvailableStatus(subscription.getStatus()); boolean allowPublicJoin = isPublicJoinAllowedStatus(subscription.getStatus()); - long version = subscription.getId() == null ? 0L : subscription.getId(); + long version = subscription.getEntitlementVersion(); return new RuntimeEntitlementsDto( tenantId, gameplayAvailable, allowPublicJoin, version, version, Instant.now().toString()); } @@ -769,6 +1145,14 @@ private RuntimeRealmTarget requireRealmTarget( readRuntimeRealmTarget( gameSessionClient.getAdmissionPointer(candidate.tenantId(), worldSlug, realmSlug)); if (realm.tenantId() != candidate.tenantId() + || realm.realmId() != candidate.realmId() + || !realm.playableStateNamespaceId().equals(candidate.playableStateNamespaceId()) + || !realm.stateScope().equals(candidate.stateScope()) + || realm.gameInstanceId() != candidate.gameInstanceId() + || realm.visible() != candidate.visible() + || realm.publicProductionRealm() != candidate.publicProductionRealm() + || realm.catalogRevision() != candidate.catalogRevision() + || realm.pointerVersion() != candidate.pointerVersion() || !java.util.Objects.equals(worldSlug, realm.worldSlug()) || !java.util.Objects.equals(realmSlug, realm.realmSlug())) { throw new AuthenticationException( @@ -826,34 +1210,70 @@ private String mintConnectScopeId( return mintToken( String.valueOf(bootstrapContext.accountId()), expirationMs, - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - bootstrapContext.accountId(), - "tenantId", - realm.tenantId(), - "worldSlug", - realm.worldSlug(), - "realmSlug", - realm.realmSlug(), - "gameInstanceId", - realm.gameInstanceId(), - "pointerVersion", - realm.pointerVersion(), - "evaluatedAt", - evaluatedAt.toString(), - "connectScopeExpiresAt", - expiresAt.toString(), - "jti", - stableId( - "connect-scope", - bootstrapContext.accountId(), - Long.toString(realm.tenantId()), - realm.worldSlug(), - realm.realmSlug(), - realm.pointerVersion(), - evaluatedAt.toString()))); + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", bootstrapContext.accountId()), + Map.entry("tenantId", realm.tenantId()), + Map.entry("realmId", realm.realmId()), + Map.entry("worldSlug", realm.worldSlug()), + Map.entry("realmSlug", realm.realmSlug()), + Map.entry("playableStateNamespaceId", realm.playableStateNamespaceId()), + Map.entry("playableStateScope", realm.stateScope()), + Map.entry("gameInstanceId", realm.gameInstanceId()), + Map.entry("catalogRevision", realm.catalogRevision()), + Map.entry("pointerVersion", realm.pointerVersion()), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", expiresAt.toString()), + Map.entry( + "jti", + stableId( + "connect-scope", + bootstrapContext.accountId(), + Long.toString(realm.tenantId()), + realm.worldSlug(), + realm.realmSlug(), + realm.pointerVersion(), + evaluatedAt.toString())))); + } + + private String mintAndRetainConnectScope( + BootstrapContext caller, RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { + String connectScopeId = mintConnectScopeId(caller, realm, evaluatedAt, expiresAt); + if (isPublicProductionRealm(realm)) { + VerifiedJoinScope pending = + new VerifiedJoinScope( + connectScopeId, + caller.accountId(), + realm.tenantId(), + realm.realmId(), + realm.worldSlug(), + realm.realmSlug(), + realm.playableStateNamespaceId(), + realm.stateScope(), + realm.gameInstanceId(), + realm.catalogRevision(), + realm.pointerVersion(), + evaluatedAt.toString(), + expiresAt.toString(), + ""); + accountConnectScopeRepository.insert( + new VerifiedJoinScope( + pending.connectScopeId(), + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), + pending.evaluatedAt(), + pending.connectScopeExpiresAt(), + AccountJoinDigest.scope(pending))); + } + return connectScopeId; } private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { @@ -869,16 +1289,25 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { JwtClaims.requireSignedGameplayRoutingClaims( claims, "signed token account subject mismatch"); Instant connectScopeExpiresAt = parseInstant(claims.get("connectScopeExpiresAt")); + Instant evaluatedAt = parseInstant(claims.get("evaluatedAt")); if (connectScopeExpiresAt == null) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } + if (evaluatedAt == null) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } return new ConnectScopeContext( routingClaims.accountId(), routingClaims.tenantId(), + requirePositiveLong(claims.get("realmId"), "realmId"), routingClaims.worldSlug(), routingClaims.realmSlug(), + JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"), + JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"), routingClaims.gameInstanceId(), + requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"), routingClaims.pointerVersion(), + evaluatedAt, connectScopeExpiresAt); } catch (IllegalArgumentException ex) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); @@ -934,7 +1363,11 @@ private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext requireRealmTarget( scopeContext.tenantId(), scopeContext.worldSlug(), scopeContext.realmSlug()); if (currentRealm.tenantId() != scopeContext.tenantId() + || currentRealm.realmId() != scopeContext.realmId() + || !currentRealm.playableStateNamespaceId().equals(scopeContext.playableStateNamespaceId()) + || !currentRealm.stateScope().equals(scopeContext.playableStateScope()) || currentRealm.gameInstanceId() != scopeContext.gameInstanceId() + || currentRealm.catalogRevision() != scopeContext.catalogRevision() || currentRealm.pointerVersion() != scopeContext.pointerVersion()) { throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } @@ -1073,13 +1506,17 @@ private String mintToken(String subject, long expirationMs, Map } private Map authenticationTokenClaims(String audience, Account account) { + List globalRoles = + account.getRole() == null || account.getRole().isBlank() + ? List.of() + : List.of(account.getRole()); return Map.of( "aud", audience, "accountId", account.getId(), "globalRoles", - List.of(account.getRole()), + globalRoles, "jti", UUID.randomUUID().toString()); } @@ -1134,14 +1571,6 @@ private boolean isPublicJoinAllowedStatus(String status) { }; } - private void safeLogAccountCreation(Long tenantId, Long accountId) { - try { - loggingAdminClient.logAccountCreation(tenantId, accountId); - } catch (RuntimeException ex) { - logger.warn("Account creation logging failed for account {}", accountId, ex); - } - } - @Override @Transactional(readOnly = true) @Timed(value = "account.get_profile") @@ -1252,6 +1681,11 @@ public TenantDataExportDto exportTenantData(Long tenantId, Long accountId) { @Timed(value = "account.delete") public void deleteAccount(Long accountId) { Account account = requireAccount(accountId); + if (accountJoinOperationRepository.hasRetainedOperation(accountId)) { + throw new AccountLifecycleException( + "ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED", + "Account JOIN receipts require retention and deletion reconciliation"); + } List subscriptions = subscriptionRepository.findByAccountId(accountId); Optional blockingSubscription = @@ -1494,6 +1928,14 @@ public void afterCommit() { private record BootstrapContext(long accountId) {} + private record JoinAuditPayload( + long accountId, + long tenantId, + String worldSlug, + String realmSlug, + long membershipVersion, + String requestId) {} + private ConnectTokenResult replayedConnectTokenResult(ConnectTokenResult result) { return new ConnectTokenResult( result.accountId(), @@ -1513,7 +1955,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { return buildRuntimeRealmTarget( realm.getTenantId(), + realm.getRealmId(), + realm.getPlayableStateNamespaceId(), realm.getGameInstanceId(), + realm.getCatalogRevision(), realm.getPointerVersion(), realm.getWorldSlug(), realm.getRealmSlug(), @@ -1529,7 +1974,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer realm) { return buildRuntimeRealmTarget( realm.getTenantId(), + realm.getRealmId(), + realm.getPlayableStateNamespaceId(), realm.getGameInstanceId(), + realm.getCatalogRevision(), realm.getPointerVersion(), realm.getWorldSlug(), realm.getRealmSlug(), @@ -1543,7 +1991,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( private RuntimeRealmTarget buildRuntimeRealmTarget( String tenantIdText, + String realmIdText, + String playableStateNamespaceId, String gameInstanceIdText, + long catalogRevision, long pointerVersion, String worldSlug, String realmSlug, @@ -1554,7 +2005,14 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( boolean requiresCharacterSelection, String displayName) { long tenantId = requirePositiveLong(tenantIdText, "tenantId"); + long realmId = requirePositiveLong(realmIdText, "realmId"); long gameInstanceId = requirePositiveLong(gameInstanceIdText, "gameInstanceId"); + if (!StringUtils.hasText(playableStateNamespaceId)) { + throw new IllegalArgumentException("playableStateNamespaceId is required"); + } + if (catalogRevision <= 0) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } if (pointerVersion <= 0) { throw new IllegalArgumentException("pointerVersion must be positive"); } @@ -1569,10 +2027,13 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( } return new RuntimeRealmTarget( tenantId, + realmId, + playableStateNamespaceId, gameInstanceId, worldSlug, realmSlug, pointerVersion, + catalogRevision, visible, publicProductionRealm, stateScope, @@ -1598,18 +2059,26 @@ private long requirePositiveLong(Object value, String field) { private record ConnectScopeContext( long accountId, long tenantId, + long realmId, String worldSlug, String realmSlug, + String playableStateNamespaceId, + String playableStateScope, long gameInstanceId, + long catalogRevision, long pointerVersion, + Instant evaluatedAt, Instant connectScopeExpiresAt) {} private record RuntimeRealmTarget( long tenantId, + long realmId, + String playableStateNamespaceId, long gameInstanceId, String worldSlug, String realmSlug, long pointerVersion, + long catalogRevision, boolean visible, boolean publicProductionRealm, String stateScope, diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 8ff9882a2d..9ac4dcca75 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -74,6 +74,8 @@ firemud: - account.v1.AccountService/Ping - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime + - account.v1.AccountService/IssueDirectTextConnectScope + - account.v1.AccountService/JoinPublicProductionMembership grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 14e509c126..320f48b2c5 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -96,6 +96,8 @@ firemud: - account.v1.AccountService/Ping - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime + - account.v1.AccountService/IssueDirectTextConnectScope + - account.v1.AccountService/JoinPublicProductionMembership management: endpoints: diff --git a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql new file mode 100644 index 0000000000..277dc970b7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql @@ -0,0 +1,232 @@ +-- The legacy tenant column is retained as source evidence. New global accounts +-- must not silently acquire tenant 1 through the V3 default. +CREATE TABLE account_legacy_tenant_sources ( + account_id BIGINT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE, + legacy_tenant_id BIGINT NOT NULL, + matching_membership_id BIGINT, + matching_membership_admission_allowed BOOLEAN, + profile_tenant_count BIGINT NOT NULL, + matching_profile_count BIGINT NOT NULL, + disposition VARCHAR(32) NOT NULL, + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_tenant_sources_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'TENANT_MISMATCH', 'CONFLICT')) +); + +INSERT INTO account_legacy_tenant_sources ( + account_id, + legacy_tenant_id, + matching_membership_id, + matching_membership_admission_allowed, + profile_tenant_count, + matching_profile_count, + disposition +) +SELECT a.id, + a.tenant_id, + m.id, + m.gameplay_admission_allowed, + (SELECT COUNT(*) FROM profiles p WHERE p.account_id = a.id), + (SELECT COUNT(*) FROM profiles p WHERE p.account_id = a.id AND p.tenant_id = a.tenant_id), + CASE + WHEN EXISTS ( + SELECT 1 FROM account_tenant_membership other + WHERE other.account_id = a.id AND other.tenant_id <> a.tenant_id + ) OR EXISTS ( + SELECT 1 FROM profiles p + WHERE p.account_id = a.id AND p.tenant_id <> a.tenant_id + ) THEN 'TENANT_MISMATCH' + WHEN m.id IS NULL THEN 'CONFLICT' + ELSE 'UNVERIFIED' + END +FROM accounts a +LEFT JOIN account_tenant_membership m + ON m.account_id = a.id AND m.tenant_id = a.tenant_id; + +CREATE TABLE account_legacy_membership_sources ( + membership_id BIGINT PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + tenant_id BIGINT NOT NULL, + original_gameplay_admission_allowed BOOLEAN NOT NULL, + matches_account_legacy_tenant BOOLEAN NOT NULL, + disposition VARCHAR(32) NOT NULL DEFAULT 'UNVERIFIED', + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_membership_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'VERIFIED', 'QUARANTINED')) +); + +INSERT INTO account_legacy_membership_sources ( + membership_id, account_id, tenant_id, original_gameplay_admission_allowed, + matches_account_legacy_tenant +) +SELECT m.id, m.account_id, m.tenant_id, m.gameplay_admission_allowed, + m.tenant_id = a.tenant_id +FROM account_tenant_membership m +JOIN accounts a ON a.id = m.account_id; + +CREATE TABLE account_legacy_profile_sources ( + profile_id BIGINT PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + tenant_id BIGINT NOT NULL, + matches_account_legacy_tenant BOOLEAN NOT NULL, + disposition VARCHAR(32) NOT NULL DEFAULT 'UNVERIFIED', + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_profile_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'VERIFIED', 'QUARANTINED')) +); + +INSERT INTO account_legacy_profile_sources ( + profile_id, account_id, tenant_id, matches_account_legacy_tenant +) +SELECT p.id, p.account_id, p.tenant_id, p.tenant_id = a.tenant_id +FROM profiles p +JOIN accounts a ON a.id = p.account_id; + +ALTER TABLE accounts ALTER COLUMN tenant_id DROP DEFAULT; +ALTER TABLE accounts ALTER COLUMN tenant_id DROP NOT NULL; +ALTER TABLE accounts ALTER COLUMN role DROP DEFAULT; +ALTER TABLE accounts ALTER COLUMN role DROP NOT NULL; + +-- A subscription row ID is not a policy revision. Retained policy begins at +-- version one and supported writers advance the monotonic value. +ALTER TABLE subscription ADD COLUMN entitlement_version BIGINT NOT NULL DEFAULT 1; +ALTER TABLE subscription ADD CONSTRAINT subscription_entitlement_version_positive + CHECK (entitlement_version > 0); + +-- No pre-JOIN writer proves player intent. Retain every old membership row, +-- but quarantine its authority until an explicit reconciliation disposition. +ALTER TABLE account_tenant_membership + ADD COLUMN lifecycle_state VARCHAR(32), + ADD COLUMN membership_version BIGINT, + ADD COLUMN membership_authority_generation BIGINT, + ADD COLUMN authority_provenance VARCHAR(32); + +UPDATE account_tenant_membership +SET lifecycle_state = 'LEGACY_UNVERIFIED', + membership_version = 1, + membership_authority_generation = 1, + authority_provenance = 'LEGACY_UNVERIFIED', + gameplay_admission_allowed = FALSE; + +ALTER TABLE account_tenant_membership ALTER COLUMN lifecycle_state SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN membership_version SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN membership_authority_generation SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN authority_provenance SET NOT NULL; +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_lifecycle_check + CHECK (lifecycle_state IN ('ACTIVE', 'INACTIVE', 'LEGACY_UNVERIFIED')); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_provenance_check + CHECK (authority_provenance IN ('EXPLICIT_JOIN', 'LEGACY_UNVERIFIED', 'SEEDED_DEMO')); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_versions_positive_check + CHECK (membership_version > 0 AND membership_authority_generation > 0); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_unverified_not_admitting_check + CHECK (lifecycle_state <> 'LEGACY_UNVERIFIED' OR gameplay_admission_allowed = FALSE); + +CREATE TABLE account_connect_scope_records ( + scope_token_hash VARCHAR(71) PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + target_class VARCHAR(20) NOT NULL, + tenant_id BIGINT NOT NULL, + realm_id BIGINT NOT NULL, + world_slug VARCHAR(128) NOT NULL, + realm_slug VARCHAR(128) NOT NULL, + playable_state_namespace_id VARCHAR(128) NOT NULL, + playable_state_scope VARCHAR(32) NOT NULL, + game_instance_id BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + evaluated_at VARCHAR(40) NOT NULL, + connect_scope_expires_at VARCHAR(40) NOT NULL, + playtest_lifecycle_id VARCHAR(128), + playtest_state_generation BIGINT, + snapshot_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_connect_scope_target_check + CHECK ((target_class = 'PUBLIC_PRODUCTION' + AND playtest_lifecycle_id IS NULL AND playtest_state_generation IS NULL) + OR (target_class = 'NON_PUBLIC' + AND playtest_lifecycle_id IS NOT NULL AND playtest_state_generation > 0)), + CONSTRAINT account_connect_scope_positive_check + CHECK (tenant_id > 0 AND realm_id > 0 AND game_instance_id > 0 + AND catalog_revision > 0 AND pointer_version > 0) +); + +CREATE INDEX idx_account_connect_scope_account_expiry + ON account_connect_scope_records(account_id, connect_scope_expires_at); + +CREATE TABLE account_join_operations ( + request_id VARCHAR(128) PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id), + tenant_id BIGINT NOT NULL, + verified_caller_binding VARCHAR(128) NOT NULL, + scope_token_hash VARCHAR(71) NOT NULL, + connect_scope_digest VARCHAR(71) NOT NULL, + world_slug VARCHAR(128) NOT NULL, + realm_slug VARCHAR(128) NOT NULL, + realm_id BIGINT NOT NULL, + playable_state_namespace_id VARCHAR(128) NOT NULL, + playable_state_scope VARCHAR(32) NOT NULL, + game_instance_id BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + entitlement_version BIGINT, + allow_public_join BOOLEAN, + entitlement_authority_availability VARCHAR(16) NOT NULL, + caller_bound_authority_invalidated BOOLEAN NOT NULL, + request_digest_version INTEGER NOT NULL, + request_digest VARCHAR(71) NOT NULL, + status VARCHAR(16) NOT NULL, + outcome VARCHAR(64), + membership_id BIGINT REFERENCES account_tenant_membership(id), + outcome_membership_version BIGINT, + outcome_membership_authority_generation BIGINT, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_join_operation_status_check + CHECK (status IN ('PENDING', 'COMMITTED', 'FAILED')), + CONSTRAINT account_join_operation_positive_versions_check + CHECK (tenant_id > 0 AND realm_id > 0 AND game_instance_id > 0 AND catalog_revision > 0 + AND pointer_version > 0 + AND (entitlement_version IS NULL OR entitlement_version > 0)), + CONSTRAINT account_join_operation_policy_evidence_check + CHECK ((entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL AND allow_public_join IS NOT NULL) + OR (entitlement_authority_availability IN ('UNAVAILABLE', 'NOT_EVALUATED') + AND entitlement_version IS NULL AND allow_public_join IS NULL)), + CONSTRAINT account_join_digest_version_check CHECK (request_digest_version = 1), + CONSTRAINT account_join_committed_policy_check + CHECK (status <> 'COMMITTED' OR (entitlement_version > 0 AND allow_public_join = TRUE + AND membership_id IS NOT NULL AND outcome_membership_version > 0 + AND outcome_membership_authority_generation > 0)) +); + +CREATE INDEX idx_account_join_operations_account_tenant + ON account_join_operations(account_id, tenant_id); + +CREATE TABLE account_audit_outbox ( + audit_event_id UUID PRIMARY KEY, + scope VARCHAR(8) NOT NULL, + tenant_id BIGINT, + producer_service VARCHAR(64) NOT NULL, + event_type VARCHAR(64) NOT NULL, + occurred_at TIMESTAMP NOT NULL, + schema_version INTEGER NOT NULL, + payload_digest_version INTEGER NOT NULL, + payload_digest VARCHAR(71) NOT NULL, + payload TEXT NOT NULL, + receiver_receipt_id VARCHAR(128), + receiver_log_event_id VARCHAR(128), + delivery_status VARCHAR(32) NOT NULL DEFAULT 'PENDING', + last_attempt_at TIMESTAMP, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_audit_outbox_scope_check + CHECK ((scope = 'platform' AND tenant_id IS NULL) + OR (scope = 'tenant' AND tenant_id > 0)), + CONSTRAINT account_audit_outbox_version_check + CHECK (schema_version > 0 AND payload_digest_version = 1), + CONSTRAINT account_audit_outbox_delivery_check + CHECK (delivery_status IN ('PENDING', 'COMMITTED', 'MINIMIZED')) +); + +CREATE INDEX idx_account_audit_outbox_pending + ON account_audit_outbox(created_at, audit_event_id) + WHERE delivery_status = 'PENDING'; diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 1f698b908f..996a80163b 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -23,26 +23,20 @@ components: schemas: CreateAccountRequest: type: object - description: Current API shape requires tenantId; target global registration with explicit JOIN remains unimplemented. + description: Creates a global account. Tenant membership and profiles are established separately. properties: - tenantId: - type: integer - format: int64 - minimum: 1 username: type: string email: type: string password: type: string - required: [tenantId, username, email, password] + required: [username, email, password] AccountDto: type: object properties: id: type: integer - tenantId: - type: string username: type: string email: @@ -122,6 +116,35 @@ components: requestId: type: string required: [connectScopeId, requestId] + JoinPublicProductionRequest: + type: object + properties: + connectScopeId: + type: string + description: Account-issued, caller-bound realm discovery scope + requestId: + type: string + description: Stable ID for this explicit join attempt; use a new ID for a new attempt + required: [connectScopeId, requestId] + JoinPublicProductionResult: + type: object + properties: + success: + type: boolean + outcomeCode: + type: string + accountId: + type: integer + tenantId: + type: integer + membershipId: + type: integer + membershipVersion: + type: integer + membershipAuthorityGeneration: + type: integer + replayed: + type: boolean ConnectTokenResponse: type: object properties: @@ -421,6 +444,36 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token + /auth/bootstrap/join: + post: + summary: Explicitly join the selected public-production realm from a player-bootstrap scope + operationId: joinPublicProduction + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/JoinPublicProductionRequest' + responses: + '200': + description: Durable membership snapshot after a successful join or exact replay + content: + application/json: + schema: + type: object + properties: + status: + $ref: '#/components/schemas/ResultStatus' + data: + $ref: '#/components/schemas/JoinPublicProductionResult' + error: + $ref: '#/components/schemas/ErrorDetail' + '401': + description: Scope, policy, or membership state denied the join + '503': + description: Required authority is unavailable; retry with the same attempt ID /auth/connect-token: post: summary: Mint a short-lived gameplay connect token from a valid player-bootstrap token @@ -538,8 +591,9 @@ paths: description: Invalid request /accounts: post: - summary: Create a new account + summary: Create a new global account operationId: createAccount + description: Registration creates global account and security state only; it does not join a tenant or create a profile. security: [] requestBody: required: true diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index d7f8f2e8c9..7348a5ed68 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -6,6 +6,7 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.util.UUID; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; @@ -13,6 +14,7 @@ import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -57,6 +59,7 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; @Autowired private JwtUtil jwtUtil; + @Autowired private DSLContext dsl; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -69,6 +72,51 @@ void pingEndpointReturnsPong() { assertThat(body).contains("pong"); } + @Test + void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String username = "global-" + suffix; + String email = username + "@example.com"; + HttpRequest request = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/accounts")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + "{\"username\":\"" + + username + + "\",\"email\":\"" + + email + + "\",\"password\":\"password123\",\"tenantId\":999}")) + .build(); + + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode()).isEqualTo(200); + Number accountId = + dsl.resultQuery("SELECT id FROM accounts WHERE email = ?", email).fetchOne(0, Number.class); + assertThat(accountId).isNotNull(); + assertThat(dsl.fetchValue("SELECT tenant_id FROM accounts WHERE id = ?", accountId.longValue())) + .isNull(); + assertThat(dsl.fetchValue("SELECT role FROM accounts WHERE id = ?", accountId.longValue())) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", + accountId.longValue())) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM profiles WHERE account_id = ?", accountId.longValue())) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox " + + "WHERE scope = 'platform' AND tenant_id IS NULL " + + "AND event_type = 'ACCOUNT_REGISTERED' AND payload = ?", + "{\"accountId\":" + accountId.longValue() + "}")) + .isEqualTo(1L); + } + @Test void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { String token = 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 96242142ea..e158886d5b 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 @@ -37,6 +37,8 @@ class AccountRepositoryIntegrationTest { "account_migration_collision_proof"; private static final String PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA = "account_profile_identity_migration_proof"; + private static final String GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA = + "account_global_registration_migration_proof"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -286,6 +288,104 @@ void flywayRejectsRetainedDuplicateProfileTenantIdentityBeforeAddingConstraint() .isEqualTo(2L); } + @Test + void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { + String schema = GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA; + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("25") + .load() + .migrate(); + + long legacyAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('legacy-global', 'legacy-global@example.com', 'hash', 1) RETURNING id")) + .longValue(); + dsl.execute( + "INSERT INTO " + schema + ".profiles (account_id, tenant_id) VALUES (?, ?)", + legacyAccountId, + 7L); + dsl.execute( + "INSERT INTO " + + schema + + ".account_tenant_membership (account_id, tenant_id, gameplay_admission_allowed) " + + "VALUES (?, ?, TRUE)", + legacyAccountId, + 7L); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); + + assertThat( + dsl.fetchValue( + "SELECT tenant_id FROM " + schema + ".accounts WHERE id = ?", legacyAccountId)) + .isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT disposition FROM " + + schema + + ".account_legacy_tenant_sources " + + "WHERE account_id = ?", + legacyAccountId)) + .isEqualTo("TENANT_MISMATCH"); + assertThat( + dsl.fetchValue( + "SELECT original_gameplay_admission_allowed FROM " + + schema + + ".account_legacy_membership_sources WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(true); + assertThat( + dsl.fetchValue( + "SELECT gameplay_admission_allowed FROM " + + schema + + ".account_tenant_membership WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(false); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + schema + ".profiles WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(1L); + + long newAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash) " + + "VALUES ('new-global', 'new-global@example.com', 'hash') RETURNING id")) + .longValue(); + assertThat( + dsl.fetchValue( + "SELECT tenant_id FROM " + schema + ".accounts WHERE id = ?", newAccountId)) + .isNull(); + assertThat( + dsl.fetchValue("SELECT role FROM " + schema + ".accounts WHERE id = ?", newAccountId)) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + + schema + + ".account_tenant_membership WHERE account_id = ?", + newAccountId)) + .isEqualTo(0L); + } + private Account account(String username, String email, AccountLifecycleState lifecycleState) { Account account = new Account(); account.setUsername(username); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 8427a1ce49..a666f1fdad 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -64,8 +64,7 @@ void clear() { @Test void createAccountReturnsDto() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); AccountDto response = new AccountDto(1L, "demo", "demo@example.com", "player", true); when(accountService.createAccount(request)).thenReturn(response); @@ -81,8 +80,7 @@ void createAccountReturnsDto() throws Exception { @Test void createAccountConflictUsesCanonicalEnvelope() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); when(accountService.createAccount(request)) .thenThrow(new AccountAlreadyExistsException(new RuntimeException("duplicate"))); @@ -97,27 +95,9 @@ void createAccountConflictUsesCanonicalEnvelope() throws Exception { .andExpect(jsonPath("$.error.message").value("Account already exists")); } - @Test - void createAccountRejectsZeroTenantIdBeforeDispatch() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(0L, "demo", "demo@example.com", "password"); - - mockMvc - .perform( - post("/accounts") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(request))) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("tenantId must be positive")); - - verifyNoInteractions(accountService); - } - @Test void createAccountRetainsMinimumPasswordLength() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "12345"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "12345"); mockMvc .perform( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java index acd3e499da..fda8d4325e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java @@ -56,7 +56,7 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { @Test void accountCreationRemainsPublicInProdProfile() throws Exception { CreateAccountRequest request = - new CreateAccountRequest(1L, "demo", "demo@example.com", "swordfish"); + new CreateAccountRequest("demo", "demo@example.com", "swordfish"); when(accountService.createAccount(request)) .thenReturn(new AccountDto(1L, "demo", "demo@example.com", "player", true)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java new file mode 100644 index 0000000000..4e47d83b37 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class AccountJoinDigestTest { + @Test + void scopeAndRequestDigestsMatchUtf8CanonicalVectors() { + VerifiedJoinScope scope = scope("scope-token-α", "production"); + + assertEquals( + "sha256:3ecdb49d051fb18e9e925031da8245504af61d956993b5b44fc7b4f0781b0da6", + AccountJoinDigest.scope(scope)); + assertEquals( + "sha256:764b03cbe948293517acb4ce201dbd24fc4d2a0a2306e853f2ab0a6c3775a768", + AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 5L), + AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", false, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 5L), + AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 6L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 5L), + AccountJoinDigest.request( + scope("scope-token-α", "preview"), "bootstrap-jti-α", "AVAILABLE", true, 5L)); + assertEquals( + "sha256:3450f964af0d11503e93a34d5178697de8c07c0eb7fe7e215d70de61a93f5a38", + AccountJoinDigest.request(scope, "bootstrap-jti-α", "UNAVAILABLE", null, null)); + } + + @Test + void canonicalSerializationRejectsAmbiguousValues() { + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.scope(scope("scope=token", "production"))); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.scope(scope("scope-token", "production\nJOIN"))); + assertThrows( + IllegalArgumentException.class, + () -> + AccountJoinDigest.request( + scope("scope-token", "production"), "bad=binding", "AVAILABLE", true, 1L)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountJoinDigest.request( + scope("scope-token", "production"), "caller", "AVAILABLE", true, null)); + } + + private static VerifiedJoinScope scope(String connectScopeId, String realmSlug) { + return new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + 31L, + "demo", + realmSlug, + "namespace-44", + "SHARED", + 44L, + 23L, + 17L, + "2026-09-24T10:00:00Z", + "2026-09-24T10:02:00Z", + "unused-by-preimage"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java new file mode 100644 index 0000000000..cf681c7b3d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class AccountAuditDeliveryJobTest { + private final AccountAuditOutboxRepository outbox = + Mockito.mock(AccountAuditOutboxRepository.class); + private final LoggingAdminClient client = Mockito.mock(LoggingAdminClient.class); + private final AccountAuditDeliveryJob job = new AccountAuditDeliveryJob(outbox, client); + + @Test + void marksOnlyAnExactReceiverReceiptDelivered() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(50)).thenReturn(List.of(envelope)); + when(client.deliver(envelope)) + .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-1", "log-1", false)); + + job.deliverPending(); + + verify(outbox).markDelivered(envelope.auditEventId(), "receipt-1", "log-1", false); + verify(outbox, never()).recordAttempt(envelope.auditEventId()); + } + + @Test + void unavailableReceiverKeepsSameEnvelopePending() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(50)).thenReturn(List.of(envelope)); + when(client.deliver(envelope)).thenThrow(new IllegalStateException("unavailable")); + + job.deliverPending(); + + verify(outbox).recordAttempt(envelope.auditEventId()); + verify(outbox, never()).markDelivered(envelope.auditEventId(), "receipt-1", "log-1", false); + } + + @Test + void digestBindsExactUtf8PayloadBytes() { + assertEquals( + "sha256:eee0f882a1fae6d1435a03d9e9508a3972f0c1f10495b4e3d5e388cebced63ef", + AccountAuditDigest.ofPayload("{\"accountId\":1}")); + assertNotEquals( + AccountAuditDigest.ofPayload("{\"accountId\":1}"), + AccountAuditDigest.ofPayload("{\"accountId\": 1}")); + } + + private static AccountAuditEnvelope platformRegistration() { + String payload = "{\"accountId\":1}"; + return new AccountAuditEnvelope( + UUID.fromString("e9659715-e257-4f88-847e-700653e101d1"), + "platform", + null, + "account-service", + "ACCOUNT_REGISTERED", + Instant.parse("2026-09-24T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 5f5c69804a..4ee72fda64 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.Map; @@ -28,6 +29,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesRequest; import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse; import net.firedevops.firemud.account.v1.PingRequest; @@ -38,17 +43,80 @@ import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +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.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.PingService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class AccountGrpcServiceTest { + private static final String WORKLOAD_NAMESPACE = "test"; + private static final GrpcPeerIdentity GAME_SESSION_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", + WORKLOAD_NAMESPACE, + "game-session-service"); + + private static PlayerExecutionContext validPlayerContext() { + return PlayerExecutionContext.newBuilder() + .setAccountId("10") + .setTenantId("20") + .setRealmId("30") + .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateScope("realm:30") + .setGameInstanceId("40") + .setSessionId("session-1") + .setRequestId("request-1") + .build(); + } + + private static IssueDirectTextConnectScopeRequest validScopeRequest() { + return IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(validPlayerContext()) + .setTenantId("20") + .setRealmId("30") + .setWorldSlug("world") + .setRealmSlug("public") + .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateScope("realm:30") + .setGameInstanceId("40") + .setCatalogRevision(5) + .setPointerVersion(8) + .build(); + } + + private static JoinPublicProductionMembershipRequest validJoinRequest() { + return JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(validPlayerContext()) + .setConnectScopeId("scope-1") + .setRequestId("request-1") + .build(); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.ROOT; + if (peer != null) { + context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + } + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + @AfterEach void tearDown() { SessionContext.clear(); @@ -80,6 +148,143 @@ public void onCompleted() {} assertEquals("pong", ref.get().getMessage()); } + @Test + void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when( + accountService.issueDirectTextConnectScope( + Mockito.any(DirectTextCallerContext.class), + Mockito.any(DirectTextJoinTarget.class))) + .thenReturn(new DirectTextJoinScope("scope-1", "2026-09-24T12:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.issueDirectTextConnectScope(validScopeRequest(), observer)); + + assertTrue(observer.completed()); + assertEquals("scope-1", observer.response().getConnectScopeId()); + assertEquals("2026-09-24T12:00:00Z", observer.response().getConnectScopeExpiresAt()); + Mockito.verify(accountService) + .issueDirectTextConnectScope( + new DirectTextCallerContext( + 10L, 20L, 30L, "realm-state-30", "realm:30", 40L, "session-1", "request-1"), + new DirectTextJoinTarget( + 20L, 30L, "world", "public", "realm-state-30", "realm:30", 40L, 5L, 8L)); + } + + @Test + void joinPublicProductionMembershipPreservesStoredFailureOutcome() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when( + accountService.joinPublicProductionFromGameSession( + Mockito.any(DirectTextCallerContext.class), + Mockito.any(JoinPublicProductionRequest.class))) + .thenReturn( + new JoinPublicProductionResult( + false, "ENTITLEMENT_UNAVAILABLE", 10L, 20L, 0L, 0L, 0L, true)); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(validJoinRequest(), observer)); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("ENTITLEMENT_UNAVAILABLE", observer.response().getOutcomeCode()); + assertEquals("10", observer.response().getAccountId()); + assertEquals("20", observer.response().getTenantId()); + assertEquals("0", observer.response().getMembershipId()); + assertTrue(observer.response().getReplayed()); + assertFalse(observer.response().hasError()); + Mockito.verify(accountService) + .joinPublicProductionFromGameSession( + new DirectTextCallerContext( + 10L, 20L, 30L, "realm-state-30", "realm:30", 40L, "session-1", "request-1"), + new JoinPublicProductionRequest("scope-1", "request-1")); + } + + @Test + void protectedDirectTextMethodsRejectAbsentWrongSharedAndCrossNamespacePeers() { + List rejectedPeers = + java.util.Arrays.asList( + null, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/world-management-service", + "test", + "world-management-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/account-service", "test", "account-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); + + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver issueObserver = + new RecordingObserver<>(); + RecordingObserver joinObserver = + new RecordingObserver<>(); + + withPeer(peer, () -> service.issueDirectTextConnectScope(validScopeRequest(), issueObserver)); + withPeer( + peer, () -> service.joinPublicProductionMembership(validJoinRequest(), joinObserver)); + + assertEquals("PERMISSION_DENIED", issueObserver.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", joinObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } + + @Test + void directTextMethodsRejectMalformedOrMismatchedTypedContextBeforeServiceCall() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + + IssueDirectTextConnectScopeRequest mismatchedTarget = + validScopeRequest().toBuilder().setRealmId("31").build(); + PlayerExecutionContext malformedContext = + validPlayerContext().toBuilder().setAccountId("NaN").build(); + JoinPublicProductionMembershipRequest mismatchedJoin = + validJoinRequest().toBuilder().setRequestId("request-2").build(); + RecordingObserver targetObserver = + new RecordingObserver<>(); + RecordingObserver malformedObserver = + new RecordingObserver<>(); + RecordingObserver requestIdObserver = + new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.issueDirectTextConnectScope(mismatchedTarget, targetObserver)); + withPeer( + GAME_SESSION_PEER, + () -> + service.joinPublicProductionMembership( + validJoinRequest().toBuilder().setPlayerContext(malformedContext).build(), + malformedObserver)); + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(mismatchedJoin, requestIdObserver)); + + assertEquals("INVALID_ARGUMENT", targetObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", malformedObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", requestIdObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void authenticateFailureReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -208,7 +413,6 @@ void createAccountValidationErrorReturnsErrorDetail() { AtomicReference ref = new AtomicReference<>(); service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("e@example.com") .setPassword("pass") @@ -241,7 +445,6 @@ void createAccountConflictReturnsApplicationError() { service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("demo@example.com") .setPassword("pass") @@ -256,7 +459,7 @@ void createAccountConflictReturnsApplicationError() { } @Test - void createAccountReturnsAccountIdAndTenant() { + void createAccountReturnsAccountIdForGlobalRequest() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.createAccount(Mockito.any())) @@ -266,7 +469,6 @@ void createAccountReturnsAccountIdAndTenant() { AtomicReference ref = new AtomicReference<>(); service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("e@example.com") .setPassword("pass") @@ -291,40 +493,8 @@ public void onCompleted() {} org.mockito.ArgumentCaptor.forClass( net.firedevops.firemud.accountservice.dto.CreateAccountRequest.class); Mockito.verify(accountService).createAccount(captor.capture()); - assertEquals(7L, captor.getValue().tenantId()); - } - - @Test - void createAccountRejectsZeroTenantIdBeforeCreate() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.createAccount( - CreateAccountRequest.newBuilder() - .setTenantId("0") - .setUsername("demo") - .setEmail("e@example.com") - .setPassword("pass") - .build(), - new StreamObserver() { - @Override - public void onNext(CreateAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + assertEquals("demo", captor.getValue().username()); + assertEquals("e@example.com", captor.getValue().email()); } @Test @@ -501,7 +671,7 @@ void getTenantMembershipForRuntimeReturnsResponse() { Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, true, true, 44L, "2026-03-30T00:00:00Z")); + 2L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -538,7 +708,7 @@ void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed( Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, false, true, 44L, "2026-03-30T00:00:00Z")); + 2L, 1L, false, true, 44L, "MISSING", 0L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); RecordingObserver observer = new RecordingObserver<>(); 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 71b119abd0..c2a90471ca 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 @@ -10,16 +10,14 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; import java.util.Map; import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; -import net.firedevops.firemud.accountservice.client.LoggingAdminClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDto; @@ -27,10 +25,13 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; @@ -42,7 +43,10 @@ import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +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.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -57,7 +61,6 @@ import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.session.SessionService; -import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; @@ -74,6 +77,9 @@ class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; @Mock private AccountRepository accountRepository; + @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; + @Mock private AccountConnectScopeRepository accountConnectScopeRepository; + @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @Mock private AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -84,11 +90,9 @@ class AccountServiceImplTest { @Mock private MailProperties mailProperties; private final AccountTokenProperties tokenProperties = new AccountTokenProperties(); private final JwtAuthProperties jwtAuthProperties = new JwtAuthProperties(); - @Mock private LoggingAdminClient loggingAdminClient; @Mock private GameSessionClient gameSessionClient; @Mock private EntityManagementClient entityManagementClient; @Mock private SessionService sessionService; - @Mock private SagaRunner sagaRunner; @Mock private PaymentTransactionRepository paymentTransactionRepository; @Mock private SubscriptionRepository subscriptionRepository; @Mock private ExternalAccountRepository externalAccountRepository; @@ -102,7 +106,7 @@ class AccountServiceImplTest { private AccountServiceImpl service; @BeforeEach - void setup() throws net.firedevops.firemud.common.saga.SagaException { + void setup() { MockitoAnnotations.openMocks(this); Subscription explicitActiveEntitlement = new Subscription(); explicitActiveEntitlement.setId(1L); @@ -139,6 +143,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -155,6 +162,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -173,6 +183,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { service = new AccountServiceImpl( accountRepository, + accountAuditOutboxRepository, + accountConnectScopeRepository, + accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -189,28 +202,23 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { mailProperties, tokenProperties, jwtAuthProperties, - loggingAdminClient, gameSessionClient, entityManagementClient, jwtUtil, - sessionService, - sagaRunner); - org.mockito.Mockito.doAnswer( - inv -> { - ((net.firedevops.firemud.common.saga.Saga) inv.getArgument(0)).run(); - return null; - }) - .when(sagaRunner) - .run(org.mockito.ArgumentMatchers.any()); + sessionService); } @Test - void createAccountPersistsEntity() throws net.firedevops.firemud.common.saga.SagaException { + void createAccountPersistsOnlyGlobalIdentity() { CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", " DEMO@example.com ", "password"); - Account saved = new Account(); - saved.setId(1L); - when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))).thenReturn(saved); + new CreateAccountRequest("demo", " DEMO@example.com ", "password"); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + return saved; + }); AccountDto dto = service.createAccount(request); @@ -220,13 +228,21 @@ void createAccountPersistsEntity() throws net.firedevops.firemud.common.saga.Sag org.mockito.ArgumentCaptor.forClass(Account.class); org.mockito.Mockito.verify(accountRepository).save(accountCaptor.capture()); assertEquals("demo@example.com", accountCaptor.getValue().getEmail()); - org.mockito.Mockito.verify(sagaRunner).run(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountAuditOutboxRepository) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("platform"), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.eq("ACCOUNT_REGISTERED"), + org.mockito.ArgumentMatchers.eq("{\"accountId\":1}")); + assertEquals(null, accountCaptor.getValue().getRole()); + verifyNoInteractions(profileRepository, accountTenantMembershipRepository); } @Test void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", " DEMO@EXAMPLE.COM ", "password"); + new CreateAccountRequest("demo", " DEMO@EXAMPLE.COM ", "password"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) .thenThrow(new org.jooq.exception.IntegrityConstraintViolationException("duplicate")); @@ -238,8 +254,7 @@ void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { @Test void createAccountMapsSpringDataIntegrityConflict() { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) .thenThrow(new org.springframework.dao.DataIntegrityViolationException("duplicate")); @@ -249,6 +264,422 @@ void createAccountMapsSpringDataIntegrityConflict() { assertEquals("Account already exists", exception.getMessage()); } + @Test + void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; + }); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-attempt-1"); + + JoinPublicProductionResult first = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult retried = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + ConnectTokenResult onboardingToken = + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "first-play-after-join")); + + assertTrue(first.success()); + assertEquals("JOINED", first.outcomeCode()); + assertEquals(701L, first.membershipId()); + assertEquals(1L, first.membershipVersion()); + assertTrue(retried.success()); + assertTrue(retried.replayed()); + assertNotNull(onboardingToken.connectToken()); + assertEquals( + first, + new JoinPublicProductionResult( + retried.success(), + retried.outcomeCode(), + retried.accountId(), + retried.tenantId(), + retried.membershipId(), + retried.membershipVersion(), + retried.membershipAuthorityGeneration(), + false)); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-attempt-1")); + assertEquals("COMMITTED", retainedOperation.get().status()); + + AuthenticationException changedDigest = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest("different-scope", "join-attempt-1"))); + assertEquals("IDEMPOTENCY_CONFLICT", changedDigest.getCode()); + } + + @Test + void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription grace = new Subscription(); + grace.setId(22L); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(grace)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-closed-1"); + + JoinPublicProductionResult denied = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(denied.success()); + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", denied.outcomeCode()); + assertFalse(retry.success()); + assertTrue(retry.replayed()); + assertEquals(denied.outcomeCode(), retry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + grace.setStatus("active"); + grace.setEntitlementVersion(2L); + AuthenticationException changedPolicy = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + assertEquals("IDEMPOTENCY_CONFLICT", changedPolicy.getCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + } + + @ParameterizedTest + @CsvSource({"false", "true"}) + void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn( + ambiguous + ? java.util.List.of(new Subscription(), new Subscription()) + : java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-unavailable-1"); + + JoinPublicProductionResult first = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(first.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", first.outcomeCode()); + assertFalse(retry.success()); + assertTrue(retry.replayed()); + assertEquals(first.outcomeCode(), retry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("UNAVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + assertEquals(null, retainedOperation.get().allowPublicJoin()); + assertEquals(null, retainedOperation.get().entitlementVersion()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantIdForUpdate(7L); + } + + @Test + void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription initialPolicy = new Subscription(); + initialPolicy.setId(22L); + initialPolicy.setTenantId(7L); + initialPolicy.setStatus("active"); + initialPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn(java.util.List.of(initialPolicy), java.util.List.of(changedPolicy)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-race-1")); + + assertFalse(result.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", result.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantIdForUpdate(7L); + } + + @Test + void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + org.mockito.Mockito.when( + accountJoinOperationRepository.insertPending( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Boolean.class), + org.mockito.ArgumentMatchers.anyBoolean())) + .thenReturn(false); + + AuthenticationException conflict = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-global-collision-1"))); + + assertEquals("IDEMPOTENCY_CONFLICT", conflict.getCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + @Test + void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AccountTenantMembership quarantined = membership(account, 7L); + quarantined.setLifecycleState("LEGACY_UNVERIFIED"); + quarantined.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(quarantined)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-legacy-1")); + + assertFalse(result.success()); + assertEquals("MEMBERSHIP_RECONCILIATION_REQUIRED", result.outcomeCode()); + assertEquals("LEGACY_UNVERIFIED", quarantined.getLifecycleState()); + assertFalse(quarantined.isGameplayAdmissionAllowed()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + private void retainJoinEvidence( + AtomicReference retainedScope, + AtomicReference retainedOperation) { + org.mockito.Mockito.doAnswer( + invocation -> { + retainedScope.set(invocation.getArgument(0)); + return null; + }) + .when(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + when(accountConnectScopeRepository.find(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedScope.get())); + when(accountJoinOperationRepository.find(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + org.mockito.Mockito.doAnswer( + invocation -> { + String requestId = invocation.getArgument(0); + VerifiedJoinScope scope = invocation.getArgument(1); + String callerBinding = invocation.getArgument(2); + String requestDigest = invocation.getArgument(3); + String authorityAvailability = invocation.getArgument(4); + Long entitlementVersion = invocation.getArgument(5); + Boolean allowPublicJoin = invocation.getArgument(6); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + scope.accountId(), + scope.tenantId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId()), + scope.snapshotDigest(), + authorityAvailability, + allowPublicJoin, + entitlementVersion, + 1, + requestDigest, + "PENDING", + null, + null, + null, + null)); + return true; + }) + .when(accountJoinOperationRepository) + .insertPending( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Boolean.class), + org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + invocation.getArgument(4), + invocation.getArgument(5))); + return null; + }) + .when(accountJoinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + } + @Test void emailLoginOtpRequestIsNeutralForUnknownEmail() { when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); @@ -497,25 +928,6 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); } - @Test - void createAccountContinuesWhenAuditLoggingFails() - throws net.firedevops.firemud.common.saga.SagaException { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); - Account saved = new Account(); - saved.setId(1L); - when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))).thenReturn(saved); - org.mockito.Mockito.doThrow(new StatusRuntimeException(Status.UNAVAILABLE)) - .when(loggingAdminClient) - .logAccountCreation(7L, 1L); - - AccountDto dto = service.createAccount(request); - - assertEquals(1L, dto.id()); - assertEquals("demo", dto.username()); - org.mockito.Mockito.verify(sagaRunner).run(org.mockito.ArgumentMatchers.any()); - } - @Test void authenticateReturnsControlUiTokenWithoutGameplayMembership() { Account account = new Account(); @@ -531,7 +943,7 @@ void authenticateReturnsControlUiTokenWithoutGameplayMembership() { var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("control-ui", claims.getAudience().iterator().next()); assertEquals(1L, claims.get("accountId", Long.class)); - assertEquals(java.util.List.of("player"), claims.get("globalRoles")); + assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); assertFalse(claims.containsKey("tenantId")); org.mockito.Mockito.verify(sessionService) @@ -577,7 +989,7 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); assertEquals(1L, claims.get("accountId", Long.class)); - assertEquals(java.util.List.of("player"), claims.get("globalRoles")); + assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); org.mockito.Mockito.verify(sessionService) .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -734,6 +1146,9 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { service = new AccountServiceImpl( accountRepository, + accountAuditOutboxRepository, + accountConnectScopeRepository, + accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -750,12 +1165,10 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { mailProperties, tokenProperties, jwtAuthProperties, - loggingAdminClient, gameSessionClient, entityManagementClient, jwtUtil, - sessionService, - sagaRunner); + sessionService); IllegalStateException ex = assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("boom-token")); @@ -779,6 +1192,9 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { .setDisplayName("Broken Realm") .setTenantId("bad") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1195,7 +1611,9 @@ void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { assertEquals(7L, dto.tenantId()); assertTrue(dto.membershipExists()); assertTrue(dto.gameplayAdmissionAllowed()); - assertEquals(711L, dto.membershipVersion()); + assertEquals(1L, dto.membershipVersion()); + assertEquals("ACTIVE", dto.membershipLifecycleState()); + assertEquals(1L, dto.membershipAuthorityGeneration()); assertNotNull(dto.evaluatedAt()); } @@ -1238,8 +1656,8 @@ void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions() { assertEquals(7L, dto.tenantId()); assertTrue(dto.gameplayAvailable()); assertTrue(dto.allowPublicJoin()); - assertEquals(31L, dto.entitlementVersion()); - assertEquals(31L, dto.tenantBillingSequence()); + assertEquals(1L, dto.entitlementVersion()); + assertEquals(1L, dto.tenantBillingSequence()); assertNotNull(dto.evaluatedAt()); } @@ -1407,6 +1825,9 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1422,9 +1843,10 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { service.issueConnectToken( bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-4"))); - assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + // The catalog and pointer disagree before Account has a valid current pair to compare. + assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); assertEquals( - "Selected gameplay target is no longer admissible; rerun bootstrap discovery and request a fresh connect scope", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", ex.getMessage()); } @@ -1457,6 +1879,9 @@ void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1512,6 +1937,9 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { .setDisplayName("Live Realm") .setTenantId("") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1571,6 +1999,9 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1761,6 +2192,9 @@ void issueConnectTokenKeepsGenericMembershipRejectionDistinctFromBillingDenial() .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(true) .setPublicProductionRealm(false) @@ -1777,6 +2211,9 @@ void issueConnectTokenKeepsGenericMembershipRejectionDistinctFromBillingDenial() .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(true) .setPublicProductionRealm(false) @@ -1848,6 +2285,9 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1863,13 +2303,14 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { service.issueConnectToken( bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-fail-1"))); - assertEquals("CONNECT_SCOPE_MISMATCH", firstFailure.getCode()); + // The catalog and pointer disagree before Account has a valid current pair to compare. + assertEquals("ADMISSION_POINTER_UNAVAILABLE", firstFailure.getCode()); when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-fail-1")) .thenReturn( Optional.of( new SessionService.ConnectTokenReplay( - false, null, "CONNECT_SCOPE_MISMATCH", firstFailure.getMessage()))); + false, null, "ADMISSION_POINTER_UNAVAILABLE", firstFailure.getMessage()))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() @@ -1879,6 +2320,9 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1895,10 +2339,10 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-fail-1"))); - assertEquals("CONNECT_SCOPE_MISMATCH", replayedFailure.getCode()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", replayedFailure.getCode()); assertEquals(firstFailure.getMessage(), replayedFailure.getMessage()); assertEquals( - "Selected gameplay target is no longer admissible; rerun bootstrap discovery and request a fresh connect scope", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", replayedFailure.getMessage()); } @@ -2013,6 +2457,9 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2063,6 +2510,9 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2122,6 +2572,9 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setDisplayName("Broken Realm") .setTenantId("bad") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2135,6 +2588,9 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2171,6 +2627,9 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2187,6 +2646,9 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2232,6 +2694,8 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() .thenReturn(Optional.of(membership(account, 7L))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() .setWorldSlug("demo") .setWorldDisplayName("Demo World") @@ -2239,6 +2703,9 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("bad") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2275,6 +2742,8 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { .thenReturn(Optional.of(membership(account, 7L))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() .setWorldSlug("demo") .setWorldDisplayName("Demo World") @@ -2282,6 +2751,9 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2326,6 +2798,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2342,6 +2817,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2358,6 +2836,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2391,7 +2872,8 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat assertEquals("char-sandbox-1", characters.getFirst().characterId()); assertEquals("BuilderMara", characters.getFirst().characterName()); assertEquals("ISOLATED", characters.getFirst().stateScope()); - org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(7L, "sandbox", "production"); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) + .getAdmissionPointer(7L, "sandbox", "production"); } @Test @@ -2414,6 +2896,9 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setDisplayName("Tenant Seven") .setTenantId("7") .setGameInstanceId("44") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2426,12 +2911,23 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setDisplayName("Tenant Eight") .setTenantId("8") .setGameInstanceId("45") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-8") + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW")); + when(gameSessionClient.getAdmissionPointer(8L, "demo", "production")) + .thenReturn( + admissionPointer( + 8L, "demo", "production", "45", 18L, true, true, "SHARED", "ALLOW_NEW")); when(entityManagementClient.listCharactersByAccount( 7L, 11L, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(java.util.List.of()); @@ -2450,9 +2946,9 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { bootstrap.bootstrapToken(), "demo", "production", connectScopeId); assertTrue(characters.isEmpty()); - org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) - .getAdmissionPointer(8L, "demo", "production"); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) + .getAdmissionPointer(7L, "demo", "production"); + org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(8L, "demo", "production"); } @Test @@ -2506,12 +3002,19 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(false) .setRequiresCharacterSelection(false) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer( + 7L, "demo", "preview", "55", 19L, false, false, "SHARED", "ALLOW_NEW")); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); @@ -2547,6 +3050,9 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -2563,6 +3069,9 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -2604,6 +3113,9 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -2611,6 +3123,18 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer( + 7L, + "demo", + "preview", + "55", + 19L, + visible, + publicProductionRealm, + "SHARED", + "ALLOW_NEW")); when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( 11L, 7L, "demo", "preview")) .thenReturn(true); @@ -2651,6 +3175,9 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -2667,6 +3194,9 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -3102,12 +3632,45 @@ private static String hash(String password) { } } + private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( + long tenantId, + String worldSlug, + String realmSlug, + String gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + String stateScope, + String characterCreationPolicy) { + return net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug(worldSlug) + .setWorldDisplayName("demo".equals(worldSlug) ? "Demo World" : "Builder Sandbox") + .setRealmSlug(realmSlug) + .setRealmDisplayName("production".equals(realmSlug) ? "Live Realm" : "Preview Realm") + .setTenantId(Long.toString(tenantId)) + .setGameInstanceId(gameInstanceId) + .setRealmId("101") + .setPlayableStateNamespaceId("production-namespace-" + tenantId) + .setCatalogRevision(23L) + .setPointerVersion(pointerVersion) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope(stateScope) + .setCharacterCreationPolicy(characterCreationPolicy) + .build(); + } + private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); membership.setAccount(account); membership.setTenantId(tenantId); membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("SEEDED_DEMO"); return membership; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index bd417a98ea..10bb5ebc71 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -3,6 +3,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; +import java.util.Objects; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -14,6 +15,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.PingRequest; import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; @@ -25,6 +30,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.slf4j.Logger; import org.springframework.stereotype.Component; @@ -159,6 +165,131 @@ public PingResponse ping() { return callStub().ping(PingRequest.getDefaultInstance()); } + /** Requests one Account-owned direct-text scope for a server-resolved REALMS target. */ + public IssueDirectTextConnectScopeResponse issueDirectTextConnectScope( + PlayerExecutionContext playerContext, DirectTextConnectScopeTarget target) { + Objects.requireNonNull(playerContext, "playerContext must not be null"); + Objects.requireNonNull(target, "target must not be null"); + if (!hasDirectTextCallerIdentity(playerContext) + || !playerContext.getTenantId().equals(target.tenantId()) + || !playerContext.getRealmId().equals(target.realmId()) + || !playerContext.getPlayableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !playerContext.getPlayableStateScope().equals(target.playableStateScope()) + || !playerContext.getGameInstanceId().equals(target.gameInstanceId())) { + return scopeIssueError("INVALID_ARGUMENT", "Direct-text scope context did not match target"); + } + if (stub() == null) { + return scopeIssueError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + IssueDirectTextConnectScopeRequest request = + IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(playerContext) + .setTenantId(target.tenantId()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setRealmId(target.realmId()) + .setPlayableStateNamespaceId(target.playableStateNamespaceId()) + .setPlayableStateScope(target.playableStateScope()) + .setGameInstanceId(target.gameInstanceId()) + .setCatalogRevision(target.catalogRevision()) + .setPointerVersion(target.pointerVersion()) + .build(); + try { + return callStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .issueDirectTextConnectScope(request); + } catch (StatusRuntimeException ex) { + logger.warn("Account direct-text scope issuance failed", ex); + return scopeIssueError(accountAuthorityErrorCode(ex), "Account authority unavailable"); + } catch (Exception ex) { + logger.warn("Account direct-text scope issuance did not complete", ex); + return scopeIssueError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + } + + /** Applies explicit direct-text JOIN with a caller-bound, immutable request identity. */ + public JoinPublicProductionMembershipResponse joinPublicProductionMembership( + PlayerExecutionContext playerContext, String connectScopeId, String requestId) { + Objects.requireNonNull(playerContext, "playerContext must not be null"); + if (!hasDirectTextCallerIdentity(playerContext) + || connectScopeId == null + || connectScopeId.isBlank() + || requestId == null + || requestId.isBlank() + || !playerContext.getRequestId().equals(requestId)) { + return joinError("INVALID_ARGUMENT", "Direct-text JOIN request was incomplete"); + } + if (stub() == null) { + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + JoinPublicProductionMembershipRequest request = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(playerContext) + .setConnectScopeId(connectScopeId) + .setRequestId(requestId) + .build(); + try { + return callStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .joinPublicProductionMembership(request); + } catch (StatusRuntimeException ex) { + if (ex.getStatus().getCode() == Status.Code.UNAVAILABLE + || ex.getStatus().getCode() == Status.Code.DEADLINE_EXCEEDED) { + logger.warn( + "Account direct-text JOIN response was unavailable; retrying same request id", ex); + try { + initClient(); + return callStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .joinPublicProductionMembership(request); + } catch (Exception retryEx) { + logger.warn("Account direct-text JOIN retry did not complete", retryEx); + } + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + logger.warn("Account direct-text JOIN returned a terminal transport status", ex); + return joinError(ex.getStatus().getCode().name(), "Account JOIN request failed"); + } catch (Exception ex) { + logger.warn("Account direct-text JOIN did not complete", ex); + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + } + + private boolean hasDirectTextCallerIdentity(PlayerExecutionContext context) { + return isPositiveLong(context.getAccountId()) && isPositiveLong(context.getSessionId()); + } + + private boolean isPositiveLong(String value) { + if (value == null || value.isBlank()) { + return false; + } + try { + return Long.parseLong(value) > 0; + } catch (NumberFormatException ignored) { + return false; + } + } + + private String accountAuthorityErrorCode(StatusRuntimeException exception) { + Status.Code statusCode = exception.getStatus().getCode(); + return statusCode == Status.Code.UNAVAILABLE || statusCode == Status.Code.DEADLINE_EXCEEDED + ? "AUTH_UNAVAILABLE" + : statusCode.name(); + } + + private IssueDirectTextConnectScopeResponse scopeIssueError(String code, String message) { + return IssueDirectTextConnectScopeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode(code).setMessage(message)) + .build(); + } + + private JoinPublicProductionMembershipResponse joinError(String code, String message) { + return JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode(code) + .setError(ErrorDetail.newBuilder().setCode(code).setMessage(message)) + .build(); + } + public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( String accountId, String tenantId, String requestId) { if (stub() == null) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java new file mode 100644 index 0000000000..dfeca7a8e8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.gamesession.client; + +/** Server-resolved realm routing evidence sent to Account before a direct-text scope is issued. */ +public record DirectTextConnectScopeTarget( + String tenantId, + String worldSlug, + String realmSlug, + String realmId, + String playableStateNamespaceId, + String playableStateScope, + String gameInstanceId, + long catalogRevision, + long pointerVersion) { + public DirectTextConnectScopeTarget { + requireText(tenantId, "tenantId"); + requireText(worldSlug, "worldSlug"); + requireText(realmSlug, "realmSlug"); + requireText(realmId, "realmId"); + requireText(playableStateNamespaceId, "playableStateNamespaceId"); + requireText(playableStateScope, "playableStateScope"); + requireText(gameInstanceId, "gameInstanceId"); + if (catalogRevision < 1 || pointerVersion < 1) { + throw new IllegalArgumentException("routing revisions must be positive"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(name + " must not be blank"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/BuiltInTextCommandDefinitionProvider.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/BuiltInTextCommandDefinitionProvider.java index 8e6d594561..1f3eee1a37 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/BuiltInTextCommandDefinitionProvider.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/BuiltInTextCommandDefinitionProvider.java @@ -30,6 +30,15 @@ final class BuiltInTextCommandDefinitionProvider implements TextCommandDefinitio TextCommandPromptPolicy.NEVER, TextCommandActionCategory.META, List.of(TextCommandActionTag.WORLD_BROWSE, TextCommandActionTag.UI)); + register( + definitions, + TextCommandType.JOIN, + List.of("join"), + TextCommandDispatchGroup.WORLDS, + TextCommandStageRequirement.LOGIN, + TextCommandPromptPolicy.NEVER, + TextCommandActionCategory.META, + List.of(TextCommandActionTag.WORLD_BROWSE, TextCommandActionTag.UI)); register( definitions, TextCommandType.CHARS, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index b24f5862c0..f030d4af76 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; @@ -223,7 +224,17 @@ private RealmView defaultRealm(WorldView world) { .orElseGet( () -> { return new RealmView( - "production", "Live Realm", 0L, 0L, 1L, true, true, false, "SHARED", "ALLOW_NEW"); + "production", + "Live Realm", + 0L, + 0L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 0L); }); } @@ -285,7 +296,10 @@ private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { pointer.publicProductionRealm(), pointer.requiresCharacterSelection(), pointer.stateScope(), - pointer.characterCreationPolicy()); + pointer.characterCreationPolicy(), + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId()); } private static WorldView copyWorldView(WorldView input) { @@ -312,7 +326,10 @@ private static RealmView copyRealmView(RealmView input) { input.publicProductionRealm(), input.requiresCharacterSelection(), input.stateScope(), - input.characterCreationPolicy()); + input.characterCreationPolicy(), + input.catalogRevision(), + input.realmId(), + input.playableStateNamespaceId()); } public record WorldView(String slug, String displayName, List realms) { @@ -331,7 +348,65 @@ public record RealmView( boolean publicProductionRealm, boolean requiresCharacterSelection, String stateScope, - String characterCreationPolicy) {} + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + /** Creates a synthetic realm view without authoritative identity evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + null, + null); + } + + /** Creates a synthetic realm view without authoritative catalog revision evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 0L); + } + } public record RuntimeRealmTarget( String worldSlug, String worldDisplayName, String realmSlug, String realmDisplayName) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index 747ef90542..ee8e3b095e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -83,6 +83,11 @@ public TextCommandInterpretationResult handle( success( "PLAY [realm] [character]\n" + "Select the world to enter, optionally name a visible realm, and optionally choose a character."); + case "JOIN" -> + success( + "JOIN \n" + + "Join the public-production membership for a world after LOGIN.\n" + + "Use REALMS first, then JOIN before CHARS and PLAY."); case "REALMS" -> success( "REALMS \n" @@ -226,6 +231,9 @@ private ResolvedHelpTopic canonicalTopic(String topic, Optional case "HELP" -> "HELP"; case "LOGIN", "LOGON" -> "LOGIN"; case "PLAY" -> "PLAY"; + case "JOIN" -> "JOIN"; + case "REALMS" -> "REALMS"; + case "CHARS" -> "CHARS"; case "WHO" -> "WHO"; case "STATUS", "STAT" -> "STATUS"; case "FRIENDS" -> "FRIENDS"; @@ -271,6 +279,9 @@ private String topicIndex(Optional maybeContext) { "Help topics:", "- HELP LOGIN", "- HELP PLAY", + "- HELP REALMS", + "- HELP JOIN", + "- HELP CHARS", "- HELP WHO", "- HELP STATUS", "- HELP FRIENDS", @@ -336,6 +347,7 @@ private boolean isEnabled( private PlayerCommandCapability capabilityForTopic(String topic) { return switch (topic) { + case "JOIN", "REALMS", "CHARS" -> PlayerCommandCapability.MANDATORY; case "SAY", "WHISPER", "TELL", "FRIENDS" -> PlayerCommandCapability.SOCIAL; case "WHO" -> PlayerCommandCapability.PRESENCE; case "INVENTORY", "EQUIPMENT", "CONTAINER", "PUT", "TAKE", "WEAR", "REMOVE", "GET", "DROP" -> diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java index 1aeafbe85a..6c425dd50a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -17,6 +18,7 @@ import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** Handles deliberate player logout distinct from reconnect-loss recovery. */ @@ -29,7 +31,9 @@ public final class LogoutCommandHandler { private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService; private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry; private final ScriptEventPublisher scriptEventPublisher; + private final DirectTextConnectScopeSessionStore directTextConnectScopeSessionStore; + @Autowired public LogoutCommandHandler( SessionAuthenticationService sessionAuthenticationService, SessionContextService sessionContextService, @@ -37,7 +41,8 @@ public LogoutCommandHandler( GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, GameplayPresenceLifecycleService gameplayPresenceLifecycleService, FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, - ScriptEventPublisher scriptEventPublisher) { + ScriptEventPublisher scriptEventPublisher, + DirectTextConnectScopeSessionStore directTextConnectScopeSessionStore) { this.sessionAuthenticationService = Objects.requireNonNull( sessionAuthenticationService, "sessionAuthenticationService must not be null"); @@ -57,6 +62,29 @@ public LogoutCommandHandler( firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); this.scriptEventPublisher = Objects.requireNonNull(scriptEventPublisher, "scriptEventPublisher must not be null"); + this.directTextConnectScopeSessionStore = + Objects.requireNonNull( + directTextConnectScopeSessionStore, + "directTextConnectScopeSessionStore must not be null"); + } + + public LogoutCommandHandler( + SessionAuthenticationService sessionAuthenticationService, + SessionContextService sessionContextService, + GameInstanceService gameInstanceService, + GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, + GameplayPresenceLifecycleService gameplayPresenceLifecycleService, + FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, + ScriptEventPublisher scriptEventPublisher) { + this( + sessionAuthenticationService, + sessionContextService, + gameInstanceService, + gameplayAdmissionPointerAuthorityService, + gameplayPresenceLifecycleService, + firstPartyConnectContextRegistry, + scriptEventPublisher, + new DirectTextConnectScopeSessionStore()); } public LogoutCommandHandlingResult handle(String sessionId, TextCommand command) { @@ -83,6 +111,7 @@ public LogoutCommandHandlingResult handle(String sessionId, TextCommand command) context.sessionId(), AccountRecentPresenceDisposition.LOGOUT); firstPartyConnectContextRegistry.unregister(context.sessionId()); sessionContextService.deleteBySessionId(context.tenantId(), context.sessionId()); + directTextConnectScopeSessionStore.clearSession(context.sessionId()); return new LogoutCommandHandlingResult( CommandEnqueueResult.success(), List.of(PlayerOutput.notice("Logged out.", "notice.logout.success", Map.of()))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommand.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommand.java index 20181dc6b7..4cd2cfcc84 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommand.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommand.java @@ -59,6 +59,12 @@ public Optional realmBrowsePayload() { : Optional.empty(); } + public Optional joinRequestPayload() { + return payload instanceof TextCommandPayload.JoinRequest joinRequest + ? Optional.of(joinRequest) + : Optional.empty(); + } + public Optional characterBrowsePayload() { return payload instanceof TextCommandPayload.CharacterBrowseRequest browseRequest ? Optional.of(browseRequest) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java index 466d2e05c4..d0968ecf41 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java @@ -71,6 +71,7 @@ public TextCommand parse(String rawLine, TextCommandRegistry registry) { case WORLDS -> new ParsedCommandData(List.of(), new TextCommandPayload.ViewRequest("WORLDS", true)); case REALMS -> parseRealms(tokens); + case JOIN -> parseJoin(tokens); case CHARS -> parseChars(tokens); case LOGOUT -> new ParsedCommandData(List.of(), new TextCommandPayload.None()); case AFK -> parseAfk(tokens); @@ -151,6 +152,15 @@ private ParsedCommandData parseRealms(String[] tokens) { return new ParsedCommandData(args, new TextCommandPayload.Tokens(args)); } + private ParsedCommandData parseJoin(String[] tokens) { + List args = parseRemainingTokens(tokens); + if (TextCommandPayload.fromLegacy(TextCommandType.JOIN, args) + instanceof TextCommandPayload.JoinRequest joinRequest) { + return new ParsedCommandData(args, joinRequest); + } + return new ParsedCommandData(args, new TextCommandPayload.Tokens(args)); + } + private ParsedCommandData parseChars(String[] tokens) { List args = parseRemainingTokens(tokens); if (!args.isEmpty() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandPayload.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandPayload.java index df8e5cfd65..023c4504f7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandPayload.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandPayload.java @@ -10,6 +10,7 @@ public sealed interface TextCommandPayload TextCommandPayload.Credentials, TextCommandPayload.EmailLoginChallengeRequest, TextCommandPayload.RealmBrowseRequest, + TextCommandPayload.JoinRequest, TextCommandPayload.CharacterBrowseRequest, TextCommandPayload.PlayRequest, TextCommandPayload.AfkRequest, @@ -37,6 +38,8 @@ record EmailLoginChallengeRequest(String email) implements TextCommandPayload {} record RealmBrowseRequest(String worldSelector) implements TextCommandPayload {} + record JoinRequest(String worldSelector) implements TextCommandPayload {} + record CharacterBrowseRequest(String worldSelector, String realmSelector) implements TextCommandPayload {} @@ -83,6 +86,10 @@ static TextCommandPayload fromLegacy(TextCommandType type, List args) { parseRealmBrowseRequest(safeArgs) .map(request -> request) .orElseGet(() -> safeArgs.isEmpty() ? new None() : new Tokens(safeArgs)); + case JOIN -> + parseJoinRequest(safeArgs) + .map(request -> request) + .orElseGet(() -> safeArgs.isEmpty() ? new None() : new Tokens(safeArgs)); case CHARS -> parseCharacterBrowseRequest(safeArgs) .map(request -> request) @@ -246,6 +253,16 @@ private static java.util.Optional parseRealmBrowseRequest(Li return java.util.Optional.of(new RealmBrowseRequest(worldSelector)); } + private static java.util.Optional parseJoinRequest(List args) { + if (args == null || args.size() != 1) { + return java.util.Optional.empty(); + } + String worldSelector = normalizeSelectorToken(args.getFirst()); + return StringUtils.hasText(worldSelector) + ? java.util.Optional.of(new JoinRequest(worldSelector)) + : java.util.Optional.empty(); + } + private static java.util.Optional parseCharacterBrowseRequest( List args) { if (args == null || args.isEmpty()) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandType.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandType.java index b447c1966a..86abd56458 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandType.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandType.java @@ -6,6 +6,7 @@ public enum TextCommandType { WORLDS, REALMS, + JOIN, CHARS, LOGIN, LOGOUT, @@ -45,6 +46,7 @@ public static TextCommandType fromToken(String token) { return switch (normalized) { case "WORLDS" -> WORLDS; case "REALMS" -> REALMS; + case "JOIN" -> JOIN; case "CHARS" -> CHARS; case "LOGIN", "LOGON" -> LOGIN; case "LOGOUT", "LOGOFF", "QUIT" -> LOGOUT; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 680d7852c2..98487c773a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -1,14 +1,25 @@ package net.firedevops.firemud.gamesession.command.text; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @@ -21,12 +32,31 @@ public class WorldsCommandHandler { private final GameplayWorldCatalog worldCatalog; private final EntityManagementClient entityManagementClient; + private final AccountClient accountClient; + private final DirectTextConnectScopeSessionStore connectScopeSessionStore; + @Autowired public WorldsCommandHandler( + GameplayWorldCatalog worldCatalog, + EntityManagementClient entityManagementClient, + AccountClient accountClient, + DirectTextConnectScopeSessionStore connectScopeSessionStore) { + this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); + this.entityManagementClient = + Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); + this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); + this.connectScopeSessionStore = + Objects.requireNonNull( + connectScopeSessionStore, "connectScopeSessionStore must not be null"); + } + + WorldsCommandHandler( GameplayWorldCatalog worldCatalog, EntityManagementClient entityManagementClient) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); this.entityManagementClient = Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); + this.accountClient = null; + this.connectScopeSessionStore = new DirectTextConnectScopeSessionStore(); } public WorldsViewOutput browseView() { @@ -37,6 +67,182 @@ public java.util.Optional browseRealms(String worldSelect return worldCatalog.browseRealms(worldSelector); } + public RealmBrowseResult browseRealms(SessionContext sessionContext, String worldSelector) { + Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + return RealmBrowseResult.failure("LOGIN_REQUIRED"); + } + if (connectScopeSessionStore != null) { + connectScopeSessionStore.clearWorldScopes(sessionContext, worldSelector); + } + Optional maybeWorld = worldCatalog.resolveWorld(worldSelector); + if (maybeWorld.isEmpty()) { + return RealmBrowseResult.invalidSelector(); + } + + GameplayWorldCatalog.WorldView world = maybeWorld.orElseThrow(); + List visibleEntries = new ArrayList<>(); + List issuedScopes = new ArrayList<>(); + for (GameplayWorldCatalog.RealmView realm : worldCatalog.visibleRealms(world)) { + if (realm.publicProductionRealm()) { + if (accountClient == null || connectScopeSessionStore == null) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + DirectTextConnectScopeTarget target = connectScopeTarget(world, realm); + if (target == null) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + PlayerExecutionContext playerContext = playerContext(sessionContext, realm); + IssueDirectTextConnectScopeResponse scopeResponse = + accountClient.issueDirectTextConnectScope(playerContext, target); + if (scopeResponse.hasError()) { + String errorCode = scopeResponse.getError().getCode(); + if ("REALM_UNAVAILABLE".equals(errorCode)) { + continue; + } + return RealmBrowseResult.failure(errorCode.isBlank() ? "AUTH_UNAVAILABLE" : errorCode); + } + if (scopeResponse.getConnectScopeId().isBlank()) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + Instant expiresAt; + try { + expiresAt = Instant.parse(scopeResponse.getConnectScopeExpiresAt()); + } catch (DateTimeParseException ex) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + if (!expiresAt.isAfter(Instant.now())) { + return RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); + } + issuedScopes.add( + new DirectTextConnectScopeSessionStore.ScopedRealm( + realm.slug(), true, scopeResponse.getConnectScopeId(), expiresAt, playerContext)); + } + visibleEntries.add(realmEntry(visibleEntries.size() + 1, realm)); + } + + connectScopeSessionStore.replaceWorldScopes( + sessionContext, worldSelector, world.slug(), issuedScopes); + return RealmBrowseResult.success(new RealmBrowseViewOutput(world.slug(), visibleEntries)); + } + + public JoinMembershipResult joinPublicProductionMembership( + SessionContext sessionContext, String worldSelector) { + Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + return JoinMembershipResult.failure("LOGIN_REQUIRED"); + } + if (accountClient == null || connectScopeSessionStore == null) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + Optional maybeJoinScope = + connectScopeSessionStore.publicProductionScopeForJoin( + sessionContext, worldSelector, Instant.now()); + if (maybeJoinScope.isEmpty()) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + DirectTextConnectScopeSessionStore.JoinScope joinScope = maybeJoinScope.orElseThrow(); + DirectTextConnectScopeSessionStore.ScopedRealm scope = joinScope.scope(); + String requestId = joinScope.requestId(); + PlayerExecutionContext playerContext = + scope.playerContext().toBuilder().setRequestId(requestId).build(); + return JoinMembershipResult.response( + accountClient.joinPublicProductionMembership( + playerContext, scope.connectScopeId(), requestId)); + } + + private DirectTextConnectScopeTarget connectScopeTarget( + GameplayWorldCatalog.WorldView world, GameplayWorldCatalog.RealmView realm) { + if (realm.tenantId() <= 0 + || realm.gameInstanceId() <= 0 + || realm.realmId() == null + || realm.playableStateNamespaceId() == null + || realm.catalogRevision() <= 0 + || realm.pointerVersion() <= 0 + || !"SHARED".equals(realm.stateScope()) && !"ISOLATED".equals(realm.stateScope())) { + return null; + } + return new DirectTextConnectScopeTarget( + Long.toString(realm.tenantId()), + world.slug(), + realm.slug(), + realm.realmId().toString(), + realm.playableStateNamespaceId().toString(), + realm.stateScope(), + Long.toString(realm.gameInstanceId()), + realm.catalogRevision(), + realm.pointerVersion()); + } + + private PlayerExecutionContext playerContext( + SessionContext caller, GameplayWorldCatalog.RealmView realm) { + return PlayerExecutionContext.newBuilder() + .setAccountId(Long.toString(caller.accountId())) + .setSessionId(Long.toString(caller.sessionId())) + .setTenantId(Long.toString(realm.tenantId())) + .setRealmId(realm.realmId().toString()) + .setPlayableStateNamespaceId(realm.playableStateNamespaceId().toString()) + .setPlayableStateScope(realm.stateScope()) + .setGameInstanceId(Long.toString(realm.gameInstanceId())) + .build(); + } + + private RealmBrowseViewOutput.RealmEntry realmEntry( + int ordinal, GameplayWorldCatalog.RealmView realm) { + return new RealmBrowseViewOutput.RealmEntry( + ordinal, + realm.slug(), + realm.displayName(), + realm.gameInstanceId(), + realm.requiresCharacterSelection(), + realm.stateScope(), + realm.characterCreationPolicy()); + } + + public sealed interface RealmBrowseResult + permits RealmBrowseResult.Success, + RealmBrowseResult.InvalidSelector, + RealmBrowseResult.Failure { + static RealmBrowseResult success(RealmBrowseViewOutput output) { + return new Success(output); + } + + static RealmBrowseResult invalidSelector() { + return new InvalidSelector(); + } + + static RealmBrowseResult failure(String code) { + return new Failure(code); + } + + record Success(RealmBrowseViewOutput output) implements RealmBrowseResult {} + + record InvalidSelector() implements RealmBrowseResult {} + + record Failure(String code) implements RealmBrowseResult {} + } + + public sealed interface JoinMembershipResult + permits JoinMembershipResult.Response, JoinMembershipResult.Failure { + static JoinMembershipResult response( + net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse response) { + return new Response(response); + } + + static JoinMembershipResult failure(String code) { + return new Failure(code); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf responses are immutable value messages.") + record Response( + net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse response) + implements JoinMembershipResult {} + + record Failure(String code) implements JoinMembershipResult {} + } + public CharacterBrowseResult browseCharacters( SessionContext sessionContext, String worldSelector, String realmSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index d2433f654d..aadecb81e9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -34,7 +34,8 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request List.of( net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( worldsHandler.browseView()))); - case REALMS -> handleRealms(request.command()); + case REALMS -> handleRealms(request); + case JOIN -> handleJoin(request); case CHARS -> handleChars(request); default -> new TextCommandInterpretationResult( @@ -44,7 +45,7 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request net.firedevops.firemud.gamesession.presentation.PlayerOutput.error( "INVALID_ARGUMENT", "Unsupported discovery command"))); }; - if (result.commandResult().accepted()) { + if (result.commandResult().accepted() && request.command().type() != TextCommandType.JOIN) { request .sessionContext() .ifPresent(context -> publishCommandEvent(context, request.command())); @@ -52,21 +53,82 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request return result; } - private TextCommandInterpretationResult handleRealms(TextCommand command) { - return command - .realmBrowsePayload() - .flatMap(payload -> worldsHandler.browseRealms(payload.worldSelector())) - .map( - view -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.view(view)))) - .orElseGet( - () -> - errorResult( - "INVALID_ARGUMENT", - "REALMS requires a valid world selector. Use WORLDS first.")); + private TextCommandInterpretationResult handleRealms(TextCommandDispatchRequest request) { + if (request.command().realmBrowsePayload().isEmpty() || request.sessionContext().isEmpty()) { + return errorResult("INVALID_ARGUMENT", "REALMS requires a world selector after LOGIN."); + } + TextCommandPayload.RealmBrowseRequest payload = + request.command().realmBrowsePayload().orElseThrow(); + return switch (worldsHandler.browseRealms( + request.sessionContext().orElseThrow(), payload.worldSelector())) { + case WorldsCommandHandler.RealmBrowseResult.Success success -> + new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( + success.output()))); + case WorldsCommandHandler.RealmBrowseResult.InvalidSelector ignored -> + errorResult( + "INVALID_ARGUMENT", "REALMS requires a valid world selector. Use WORLDS first."); + case WorldsCommandHandler.RealmBrowseResult.Failure failure -> + errorResult(failure.code(), realmBrowseFailureMessage(failure.code())); + }; + } + + private TextCommandInterpretationResult handleJoin(TextCommandDispatchRequest request) { + if (request.command().joinRequestPayload().isEmpty() || request.sessionContext().isEmpty()) { + return errorResult("INVALID_ARGUMENT", "JOIN requires a world selector after LOGIN."); + } + TextCommandPayload.JoinRequest payload = request.command().joinRequestPayload().orElseThrow(); + return switch (worldsHandler.joinPublicProductionMembership( + request.sessionContext().orElseThrow(), payload.worldSelector())) { + case WorldsCommandHandler.JoinMembershipResult.Failure failure -> + errorResult(failure.code(), joinFailureMessage(failure.code())); + case WorldsCommandHandler.JoinMembershipResult.Response response -> + handleJoinResponse(response.response()); + }; + } + + private TextCommandInterpretationResult handleJoinResponse( + net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse response) { + if (response.hasError()) { + String code = response.getError().getCode(); + if (code.isBlank()) { + code = "JOIN_FAILED"; + } + return errorResult(code, joinFailureMessage(code)); + } + if (!response.getSuccess()) { + String code = response.getOutcomeCode().isBlank() ? "JOIN_FAILED" : response.getOutcomeCode(); + return errorResult(code, joinFailureMessage(code)); + } + return new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.notice( + "Membership is ready. Continue with CHARS and PLAY."))); + } + + private String realmBrowseFailureMessage(String code) { + return switch (code) { + case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> + "Realm authority unavailable. Retry REALMS shortly."; + case "CONNECT_SCOPE_MISMATCH", "ADMISSION_POINTER_UNAVAILABLE" -> + "Realm routing changed or is unavailable. Retry REALMS."; + default -> "Realm selection is unavailable."; + }; + } + + private String joinFailureMessage(String code) { + return switch (code) { + case "CONNECT_SCOPE_MISMATCH" -> "Join scope expired or changed. Run REALMS again."; + case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> + "Account authority unavailable. Retry JOIN shortly."; + case "ENTITLEMENT_UNAVAILABLE" -> + "Join policy could not be checked. Use REALMS and JOIN to start a new attempt later."; + case "LOGIN_REQUIRED" -> "Log in before joining a world."; + default -> "The selected world could not be joined."; + }; } private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest request) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java index 235349c833..27163a0068 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data @@ -13,6 +14,9 @@ public class GameplayAdmissionPointer { private Long tenantId; private Long gameInstanceId; private Long pointerVersion; + private Long catalogRevision; + private UUID realmId; + private UUID playableStateNamespaceId; private boolean visible; private boolean publicProductionRealm; private boolean requiresCharacterSelection; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index a01611bf45..e67eefd155 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -3,10 +3,13 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointer.GAMEPLAY_ADMISSION_POINTER; +import static net.firedevops.firemud.gamesession.jooq.tables.GameplayTenantSharedPlayableStateNamespace.GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerRecord; @@ -73,11 +76,19 @@ public List findAllByOrderByWorldSlugAscRealmSlugAsc() public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { if (entity.getId() == null) { + if (!"SHARED".equals(entity.getStateScope()) && !"ISOLATED".equals(entity.getStateScope())) { + throw new IllegalArgumentException("state_scope must be SHARED or ISOLATED"); + } lockRuntimeTargetForCreation(entity); if (countByRuntimeTarget(entity.getTenantId(), entity.getGameInstanceId()) != 0) { throw new IllegalStateException( "Admission pointer creation conflicted with another route for the runtime target"); } + entity.setRealmId(UUID.randomUUID()); + entity.setPlayableStateNamespaceId( + "SHARED".equals(entity.getStateScope()) + ? getOrCreateTenantSharedNamespace(entity.getTenantId()) + : UUID.randomUUID()); GameplayAdmissionPointerRecord record = dsl.newRecord(GAMEPLAY_ADMISSION_POINTER); populate(record, entity); try { @@ -109,6 +120,12 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { "Admission pointer changed before the requested version could be committed: id=" + entity.getId()); } + if (!Objects.equals(entity.getRealmId(), current.getRealmId()) + || !Objects.equals( + entity.getPlayableStateNamespaceId(), current.getPlayableStateNamespaceId())) { + throw new IllegalStateException( + "Admission pointer update cannot replace durable realm or playable-state identity"); + } long destinationCount = countByRuntimeTargetExcludingId( entity.getTenantId(), entity.getGameInstanceId(), entity.getId()); @@ -127,6 +144,7 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { .set(GAMEPLAY_ADMISSION_POINTER.TENANT_ID, entity.getTenantId()) .set(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID, entity.getGameInstanceId()) .set(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION, entity.getPointerVersion()) + .set(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION, entity.getCatalogRevision()) .set(GAMEPLAY_ADMISSION_POINTER.VISIBLE, entity.isVisible()) .set( GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM, @@ -228,6 +246,33 @@ private void lockRuntimeTargetForCreation(GameplayAdmissionPointer entity) { lockRuntimeTarget(runtimeTargetLockKey(entity.getTenantId(), entity.getGameInstanceId())); } + private UUID getOrCreateTenantSharedNamespace(Long tenantId) { + lockRuntimeTarget("tenant-shared-playable-state:" + tenantId); + var table = GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; + UUID namespace = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (namespace != null) { + return namespace; + } + dsl.insertInto(table) + .set(table.TENANT_ID, tenantId) + .set(table.PLAYABLE_STATE_NAMESPACE_ID, UUID.randomUUID()) + .onDuplicateKeyIgnore() + .execute(); + UUID allocated = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (allocated == null) { + throw new IllegalStateException("Tenant shared playable-state namespace allocation failed"); + } + return allocated; + } + private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPointer entity) { record.setWorldSlug(entity.getWorldSlug()); record.setWorldDisplayName(entity.getWorldDisplayName()); @@ -236,6 +281,9 @@ private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPo record.setTenantId(entity.getTenantId()); record.setGameInstanceId(entity.getGameInstanceId()); record.setPointerVersion(entity.getPointerVersion()); + record.setCatalogRevision(entity.getCatalogRevision()); + record.setRealmId(entity.getRealmId()); + record.setPlayableStateNamespaceId(entity.getPlayableStateNamespaceId()); record.setVisible(entity.isVisible()); record.setPublicProductionRealm(entity.isPublicProductionRealm()); record.setRequiresCharacterSelection(entity.isRequiresCharacterSelection()); @@ -257,6 +305,10 @@ private GameplayAdmissionPointer toEntity(Record record) { entity.setTenantId(record.get(GAMEPLAY_ADMISSION_POINTER.TENANT_ID)); entity.setGameInstanceId(record.get(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID)); entity.setPointerVersion(record.get(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION)); + entity.setCatalogRevision(record.get(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION)); + entity.setRealmId(record.get(GAMEPLAY_ADMISSION_POINTER.REALM_ID)); + entity.setPlayableStateNamespaceId( + record.get(GAMEPLAY_ADMISSION_POINTER.PLAYABLE_STATE_NAMESPACE_ID)); entity.setVisible(Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.VISIBLE))); entity.setPublicProductionRealm( Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java new file mode 100644 index 0000000000..e362bbc763 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Holds Account-issued direct-text scopes only for the transport session that resolved them. */ +@Component +public final class DirectTextConnectScopeSessionStore { + private final ConcurrentMap scopesBySessionId = new ConcurrentHashMap<>(); + + public void replaceWorldScopes( + SessionContext caller, + String requestedWorldSelector, + String canonicalWorldSlug, + List scopes) { + Objects.requireNonNull(caller, "caller must not be null"); + requireCallerIdentity(caller); + String requestedSelector = normalizeSelector(requestedWorldSelector); + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (requestedSelector == null || worldSlug == null) { + throw new IllegalArgumentException("world selectors must not be blank"); + } + List safeScopes = + List.copyOf(Objects.requireNonNull(scopes, "scopes must not be null")); + if (safeScopes.stream().anyMatch(scope -> scope.playerContext().getAccountId().isBlank())) { + throw new IllegalArgumentException("scope caller identity must not be blank"); + } + safeScopes.forEach( + scope -> { + if (!scope.playerContext().getAccountId().equals(Long.toString(caller.accountId())) + || !scope.playerContext().getSessionId().equals(Long.toString(caller.sessionId()))) { + throw new IllegalArgumentException("scope caller identity did not match session"); + } + }); + + scopesBySessionId.compute( + caller.sessionId(), + (sessionId, existing) -> { + Map> byWorld = new HashMap<>(); + Map worldBySelector = new HashMap<>(); + if (existing != null && existing.accountId() == caller.accountId()) { + byWorld.putAll(existing.scopesByWorld()); + worldBySelector.putAll(existing.worldBySelector()); + } + byWorld.put(worldSlug, safeScopes); + worldBySelector.put(worldSlug, worldSlug); + worldBySelector.put(requestedSelector, worldSlug); + return new SessionScopes( + caller.accountId(), Map.copyOf(byWorld), Map.copyOf(worldBySelector)); + }); + } + + public void clearWorldScopes(SessionContext caller, String worldSelector) { + Objects.requireNonNull(caller, "caller must not be null"); + String selector = normalizeSelector(worldSelector); + if (selector == null) { + return; + } + scopesBySessionId.computeIfPresent( + caller.sessionId(), + (sessionId, existing) -> { + if (existing.accountId() != caller.accountId()) { + return null; + } + String worldSlug = existing.worldBySelector().get(selector); + if (worldSlug == null) { + return existing; + } + Map> byWorld = new HashMap<>(existing.scopesByWorld()); + byWorld.remove(worldSlug); + Map worldBySelector = new HashMap<>(existing.worldBySelector()); + worldBySelector.entrySet().removeIf(entry -> worldSlug.equals(entry.getValue())); + if (byWorld.isEmpty()) { + return null; + } + return new SessionScopes( + existing.accountId(), Map.copyOf(byWorld), Map.copyOf(worldBySelector)); + }); + } + + public Optional publicProductionScope( + SessionContext caller, String worldSelector, Instant now) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(now, "now must not be null"); + requireCallerIdentity(caller); + String selector = normalizeSelector(worldSelector); + if (selector == null) { + return Optional.empty(); + } + SessionScopes sessionScopes = scopesBySessionId.get(caller.sessionId()); + if (sessionScopes == null || sessionScopes.accountId() != caller.accountId()) { + if (sessionScopes != null) { + scopesBySessionId.remove(caller.sessionId(), sessionScopes); + } + return Optional.empty(); + } + String canonicalWorldSlug = sessionScopes.worldBySelector().get(selector); + if (canonicalWorldSlug == null) { + return Optional.empty(); + } + List validScopes = + sessionScopes.scopesByWorld().getOrDefault(canonicalWorldSlug, List.of()).stream() + .filter(scope -> scope.expiresAt().isAfter(now)) + .toList(); + List publicScopes = + validScopes.stream().filter(ScopedRealm::publicProductionRealm).toList(); + return publicScopes.size() == 1 ? Optional.of(publicScopes.getFirst()) : Optional.empty(); + } + + /** + * Resolves a public scope and atomically binds one stable JOIN request ID to that scope. Repeated + * JOIN commands reuse the ID; a fresh REALMS response replaces the scope and starts a new logical + * attempt. + */ + public Optional publicProductionScopeForJoin( + SessionContext caller, String worldSelector, Instant now) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(now, "now must not be null"); + requireCallerIdentity(caller); + String selector = normalizeSelector(worldSelector); + if (selector == null) { + return Optional.empty(); + } + AtomicReference selected = new AtomicReference<>(); + scopesBySessionId.computeIfPresent( + caller.sessionId(), + (sessionId, sessionScopes) -> { + if (sessionScopes.accountId() != caller.accountId()) { + return sessionScopes; + } + String worldSlug = sessionScopes.worldBySelector().get(selector); + if (worldSlug == null) { + return sessionScopes; + } + List scopes = + sessionScopes.scopesByWorld().getOrDefault(worldSlug, List.of()); + List validPublicScopes = + scopes.stream() + .filter(scope -> scope.expiresAt().isAfter(now)) + .filter(ScopedRealm::publicProductionRealm) + .toList(); + if (validPublicScopes.size() != 1) { + return sessionScopes; + } + + ScopedRealm scope = validPublicScopes.getFirst(); + String requestId = scope.joinRequestId(); + ScopedRealm boundScope = scope; + if (requestId.isBlank()) { + requestId = UUID.randomUUID().toString(); + boundScope = scope.withJoinRequestId(requestId); + } + + if (boundScope != scope) { + ScopedRealm updatedScope = boundScope; + List updatedScopes = + scopes.stream() + .map( + candidate -> + candidate.connectScopeId().equals(scope.connectScopeId()) + ? updatedScope + : candidate) + .toList(); + Map> byWorld = new HashMap<>(sessionScopes.scopesByWorld()); + byWorld.put(worldSlug, updatedScopes); + sessionScopes = + new SessionScopes( + sessionScopes.accountId(), byWorld, sessionScopes.worldBySelector()); + } + selected.set(new JoinScope(boundScope, requestId)); + return sessionScopes; + }); + return Optional.ofNullable(selected.get()); + } + + public void clearSession(long sessionId) { + scopesBySessionId.remove(sessionId); + } + + @Scheduled(fixedDelay = 60_000L) + void removeExpiredScopes() { + Instant now = Instant.now(); + scopesBySessionId.forEach( + (sessionId, current) -> { + Map> remainingByWorld = new HashMap<>(); + current + .scopesByWorld() + .forEach( + (worldSlug, worldScopes) -> { + List remaining = + worldScopes.stream() + .filter(scope -> scope.expiresAt().isAfter(now)) + .toList(); + if (!remaining.isEmpty()) { + remainingByWorld.put(worldSlug, remaining); + } + }); + if (remainingByWorld.isEmpty()) { + scopesBySessionId.remove(sessionId, current); + return; + } + Map remainingSelectors = new HashMap<>(current.worldBySelector()); + remainingSelectors + .entrySet() + .removeIf(entry -> !remainingByWorld.containsKey(entry.getValue())); + SessionScopes updated = + new SessionScopes( + current.accountId(), + Map.copyOf(remainingByWorld), + Map.copyOf(remainingSelectors)); + scopesBySessionId.replace(sessionId, current, updated); + }); + } + + private void requireCallerIdentity(SessionContext caller) { + if (caller.accountId() <= 0 || caller.sessionId() <= 0) { + throw new IllegalArgumentException( + "authenticated account and transport session are required"); + } + } + + private String normalizeSelector(String selector) { + if (selector == null || selector.isBlank()) { + return null; + } + return selector.trim().toLowerCase(Locale.ROOT); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf execution contexts are immutable value messages.") + public record ScopedRealm( + String realmSlug, + boolean publicProductionRealm, + String connectScopeId, + Instant expiresAt, + PlayerExecutionContext playerContext, + String joinRequestId) { + public ScopedRealm( + String realmSlug, + boolean publicProductionRealm, + String connectScopeId, + Instant expiresAt, + PlayerExecutionContext playerContext) { + this(realmSlug, publicProductionRealm, connectScopeId, expiresAt, playerContext, ""); + } + + public ScopedRealm { + if (realmSlug == null || realmSlug.isBlank()) { + throw new IllegalArgumentException("realmSlug must not be blank"); + } + if (connectScopeId == null || connectScopeId.isBlank()) { + throw new IllegalArgumentException("connectScopeId must not be blank"); + } + Objects.requireNonNull(expiresAt, "expiresAt must not be null"); + Objects.requireNonNull(playerContext, "playerContext must not be null"); + joinRequestId = joinRequestId == null ? "" : joinRequestId; + } + + private ScopedRealm withJoinRequestId(String requestId) { + return new ScopedRealm( + realmSlug, publicProductionRealm, connectScopeId, expiresAt, playerContext, requestId); + } + } + + public record JoinScope(ScopedRealm scope, String requestId) { + public JoinScope { + Objects.requireNonNull(scope, "scope must not be null"); + if (requestId == null || requestId.isBlank()) { + throw new IllegalArgumentException("requestId must not be blank"); + } + } + } + + private record SessionScopes( + long accountId, + Map> scopesByWorld, + Map worldBySelector) { + private SessionScopes { + Map> safeWorlds = new HashMap<>(); + scopesByWorld.forEach((slug, scopes) -> safeWorlds.put(slug, List.copyOf(scopes))); + scopesByWorld = Map.copyOf(safeWorlds); + worldBySelector = Map.copyOf(worldBySelector); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java index 91fa8e464f..5b0a879615 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.service; +import java.util.UUID; + public record GameplayAdmissionPointerSnapshot( String worldSlug, String worldDisplayName, @@ -12,4 +14,70 @@ public record GameplayAdmissionPointerSnapshot( boolean publicProductionRealm, boolean requiresCharacterSelection, String stateScope, - String characterCreationPolicy) {} + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + /** Creates a synthetic snapshot without catalog identity/revision authority. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + null, + null); + } + + /** Creates a synthetic snapshot without catalog authority for legacy test fixtures. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 0L); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index baa71c65e1..c1c216b5cd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -78,9 +78,15 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu && pointer.getTenantId() != mutation.tenantId()) { throw new IllegalArgumentException("tenant_id does not own admission pointer"); } + if (pointer.getId() != null + && !Objects.equals(pointer.getStateScope(), mutation.stateScope())) { + throw new IllegalArgumentException( + "state_scope changes require a new playable-state lifecycle"); + } enforceExpectedPointerVersion(pointer, mutation.expectedPointerVersion()); long nextPointerVersion = pointer.getId() == null ? 1L : Math.max(pointer.getPointerVersion() + 1L, 1L); + long nextCatalogRevision = nextCatalogRevision(pointer, mutation); pointer.setWorldSlug(mutation.worldSlug()); pointer.setWorldDisplayName(mutation.worldDisplayName()); pointer.setRealmSlug(mutation.realmSlug()); @@ -88,6 +94,7 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu pointer.setTenantId(mutation.tenantId()); pointer.setGameInstanceId(mutation.gameInstanceId()); pointer.setPointerVersion(nextPointerVersion); + pointer.setCatalogRevision(nextCatalogRevision); pointer.setVisible(mutation.visible()); pointer.setPublicProductionRealm(mutation.publicProductionRealm()); pointer.setRequiresCharacterSelection(mutation.requiresCharacterSelection()); @@ -167,7 +174,38 @@ private GameplayAdmissionPointerSnapshot toSnapshot(GameplayAdmissionPointer poi pointer.isPublicProductionRealm(), pointer.isRequiresCharacterSelection(), pointer.getStateScope(), - pointer.getCharacterCreationPolicy()); + pointer.getCharacterCreationPolicy(), + pointer.getCatalogRevision() == null ? 0L : pointer.getCatalogRevision(), + pointer.getRealmId(), + pointer.getPlayableStateNamespaceId()); + } + + private long nextCatalogRevision( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + if (pointer.getId() == null) { + return 1L; + } + Long currentRevision = pointer.getCatalogRevision(); + if (currentRevision == null || currentRevision <= 0L) { + throw new IllegalStateException("Admission pointer catalog revision is missing or invalid"); + } + if (!catalogPolicyMatches(pointer, mutation)) { + return Math.addExact(currentRevision, 1L); + } + return currentRevision; + } + + private boolean catalogPolicyMatches( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + return Objects.equals(pointer.getWorldSlug(), mutation.worldSlug()) + && Objects.equals(pointer.getWorldDisplayName(), mutation.worldDisplayName()) + && Objects.equals(pointer.getRealmSlug(), mutation.realmSlug()) + && Objects.equals(pointer.getRealmDisplayName(), mutation.realmDisplayName()) + && pointer.isVisible() == mutation.visible() + && pointer.isPublicProductionRealm() == mutation.publicProductionRealm() + && pointer.isRequiresCharacterSelection() == mutation.requiresCharacterSelection() + && Objects.equals(pointer.getStateScope(), mutation.stateScope()) + && Objects.equals(pointer.getCharacterCreationPolicy(), mutation.characterCreationPolicy()); } private void validateMutation(GameplayAdmissionPointerMutation mutation) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index f39849a79b..896ca96837 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -545,12 +545,20 @@ public void listGameplayRealms( gameplayWorldCatalog .resolveWorld(request.getWorldSlug()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); + List realms = + gameplayWorldCatalog.visibleRealms(world).stream() + .map(realm -> toGameplayRealm(world.slug(), realm)) + .toList(); + ListGameplayRealmsResponse response = + ListGameplayRealmsResponse.newBuilder().addAllRealms(realms).build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (CatalogRevisionUnavailableException ex) { ListGameplayRealmsResponse response = ListGameplayRealmsResponse.newBuilder() - .addAllRealms( - gameplayWorldCatalog.visibleRealms(world).stream() - .map(realm -> toGameplayRealm(world.slug(), realm)) - .toList()) + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -592,10 +600,24 @@ public void getAdmissionPointer( .setPublicProductionRealm(realm.publicProductionRealm()) .setStateScope(realm.stateScope()) .setCharacterCreationPolicy(realm.characterCreationPolicy()) + .setCatalogRevision(requireCatalogRevision(realm.catalogRevision())) + .setRealmId(requireIdentity(realm.realmId(), "realmId")) + .setPlayableStateNamespaceId( + requireIdentity( + realm.playableStateNamespaceId(), "playableStateNamespaceId")) .build()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (CatalogRevisionUnavailableException ex) { + GetAdmissionPointerResponse response = + GetAdmissionPointerResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() @@ -778,9 +800,35 @@ private net.firedevops.firemud.gamesession.v1.GameplayRealm toGameplayRealm( .setPublicProductionRealm(realm.publicProductionRealm()) .setStateScope(realm.stateScope()) .setCharacterCreationPolicy(realm.characterCreationPolicy()) + .setCatalogRevision(requireCatalogRevision(realm.catalogRevision())) + .setRealmId(requireIdentity(realm.realmId(), "realmId")) + .setPlayableStateNamespaceId( + requireIdentity(realm.playableStateNamespaceId(), "playableStateNamespaceId")) .build(); } + private static String requireIdentity(java.util.UUID identity, String fieldName) { + if (identity == null) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay " + fieldName + " is missing"); + } + return identity.toString(); + } + + private static long requireCatalogRevision(long catalogRevision) { + if (catalogRevision <= 0L) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay catalog revision is missing or invalid"); + } + return catalogRevision; + } + + private static final class CatalogRevisionUnavailableException extends RuntimeException { + private CatalogRevisionUnavailableException(String message) { + super(message); + } + } + private static final class AuthorizationException extends RuntimeException { private AuthorizationException(String message) { super(message); diff --git a/services/game-session-service/src/main/resources/db/migration/V3__separate_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V3__separate_gameplay_catalog_revision.sql new file mode 100644 index 0000000000..63e5cd1ce1 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V3__separate_gameplay_catalog_revision.sql @@ -0,0 +1,4 @@ +ALTER TABLE gameplay_admission_pointer + ADD COLUMN catalog_revision bigint NOT NULL DEFAULT 1, + ADD CONSTRAINT gameplay_admission_pointer_catalog_revision_positive + CHECK (catalog_revision > 0); diff --git a/services/game-session-service/src/main/resources/db/migration/V4__persist_gameplay_realm_identity.sql b/services/game-session-service/src/main/resources/db/migration/V4__persist_gameplay_realm_identity.sql new file mode 100644 index 0000000000..41effca0d0 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V4__persist_gameplay_realm_identity.sql @@ -0,0 +1,74 @@ +-- A tenant's shared playable-state namespace is allocated once and reused by every +-- SHARED realm. Isolated realms receive independent namespace UUIDs. +CREATE TABLE gameplay_tenant_shared_playable_state_namespace ( + tenant_id bigint PRIMARY KEY, + playable_state_namespace_id uuid NOT NULL UNIQUE, + allocated_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO gameplay_tenant_shared_playable_state_namespace ( + tenant_id, + playable_state_namespace_id +) +SELECT shared_tenants.tenant_id, gen_random_uuid() +FROM ( + SELECT DISTINCT pointer.tenant_id + FROM gameplay_admission_pointer pointer + WHERE pointer.state_scope = 'SHARED' +) shared_tenants; + +ALTER TABLE gameplay_admission_pointer + ADD COLUMN realm_id uuid, + ADD COLUMN playable_state_namespace_id uuid; + +-- Retained rows with an exact known state scope can be classified without using +-- the replaceable game_instance_id as identity. Unknown legacy values remain +-- explicitly unresolved below. +UPDATE gameplay_admission_pointer +SET realm_id = gen_random_uuid(), + playable_state_namespace_id = ( + SELECT shared_namespace.playable_state_namespace_id + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.tenant_id = gameplay_admission_pointer.tenant_id + ) +WHERE state_scope = 'SHARED'; + +UPDATE gameplay_admission_pointer +SET realm_id = gen_random_uuid(), + playable_state_namespace_id = gen_random_uuid() +WHERE state_scope = 'ISOLATED'; + +CREATE TABLE gameplay_admission_pointer_identity_backfill_issue ( + pointer_id bigint PRIMARY KEY, + tenant_id bigint NOT NULL, + world_slug character varying(120) NOT NULL, + realm_slug character varying(120) NOT NULL, + prior_state_scope character varying(32), + issue_code character varying(64) NOT NULL, + recorded_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO gameplay_admission_pointer_identity_backfill_issue ( + pointer_id, + tenant_id, + world_slug, + realm_slug, + prior_state_scope, + issue_code +) +SELECT id, + tenant_id, + world_slug, + realm_slug, + state_scope, + 'UNKNOWN_PLAYABLE_STATE_SCOPE' +FROM gameplay_admission_pointer +WHERE state_scope IS NULL OR state_scope NOT IN ('SHARED', 'ISOLATED'); + +ALTER TABLE gameplay_admission_pointer + ADD CONSTRAINT gameplay_admission_pointer_identity_pair_complete + CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); + +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_realm_id + ON gameplay_admission_pointer (realm_id) + WHERE realm_id IS NOT NULL; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 155d484a7b..5d84ceca3b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -27,6 +27,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -34,6 +38,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -41,6 +46,102 @@ class AccountClientTest { + @Test + void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + IssueDirectTextConnectScopeResponse expected = + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("account-issued-scope") + .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .build(); + when(stub.issueDirectTextConnectScope(any(IssueDirectTextConnectScopeRequest.class))) + .thenReturn(expected); + AccountClient client = newClient(stub); + PlayerExecutionContext context = directTextContext("request-unused"); + DirectTextConnectScopeTarget target = + new DirectTextConnectScopeTarget( + "22", + "demo-world", + "production", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "42d234a2-7487-4dda-a7e5-a3831214328e", + "SHARED", + "9", + 7L, + 4L); + + IssueDirectTextConnectScopeResponse actual = + client.issueDirectTextConnectScope(context, target); + + assertThat(actual).isEqualTo(expected); + ArgumentCaptor captor = + ArgumentCaptor.forClass(IssueDirectTextConnectScopeRequest.class); + verify(stub).issueDirectTextConnectScope(captor.capture()); + assertThat(captor.getValue().getPlayerContext().getAccountId()).isEqualTo("41"); + assertThat(captor.getValue().getPlayerContext().getSessionId()).isEqualTo("7"); + assertThat(captor.getValue().getTenantId()).isEqualTo("22"); + assertThat(captor.getValue().getWorldSlug()).isEqualTo("demo-world"); + assertThat(captor.getValue().getRealmId()).isEqualTo(target.realmId()); + assertThat(captor.getValue().getPlayableStateNamespaceId()) + .isEqualTo(target.playableStateNamespaceId()); + assertThat(captor.getValue().getPlayableStateScope()).isEqualTo("SHARED"); + assertThat(captor.getValue().getGameInstanceId()).isEqualTo("9"); + assertThat(captor.getValue().getCatalogRevision()).isEqualTo(7L); + assertThat(captor.getValue().getPointerVersion()).isEqualTo(4L); + } + + @Test + void directTextJoinRetryReusesExactContextScopeAndRequestId() throws Exception { + RetryFixture fixture = newRetryFixture(); + when(fixture + .initialStub() + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + JoinPublicProductionMembershipResponse expected = + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("CREATED") + .build(); + when(fixture + .retryStub() + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) + .thenReturn(expected); + AccountClient client = fixture.client(); + PlayerExecutionContext context = directTextContext("join-request-1"); + + JoinPublicProductionMembershipResponse actual = + client.joinPublicProductionMembership(context, "account-issued-scope", "join-request-1"); + + assertThat(actual).isEqualTo(expected); + ArgumentCaptor firstCaptor = + ArgumentCaptor.forClass(JoinPublicProductionMembershipRequest.class); + ArgumentCaptor retryCaptor = + ArgumentCaptor.forClass(JoinPublicProductionMembershipRequest.class); + verify(fixture.initialStub()).joinPublicProductionMembership(firstCaptor.capture()); + verify(fixture.retryStub()).joinPublicProductionMembership(retryCaptor.capture()); + assertThat(firstCaptor.getValue()).isEqualTo(retryCaptor.getValue()); + assertThat(retryCaptor.getValue().getConnectScopeId()).isEqualTo("account-issued-scope"); + assertThat(retryCaptor.getValue().getRequestId()).isEqualTo("join-request-1"); + assertThat(retryCaptor.getValue().getPlayerContext().getRequestId()) + .isEqualTo("join-request-1"); + verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + private static PlayerExecutionContext directTextContext(String requestId) { + return PlayerExecutionContext.newBuilder() + .setAccountId("41") + .setSessionId("7") + .setTenantId("22") + .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") + .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") + .setPlayableStateScope("SHARED") + .setGameInstanceId("9") + .setRequestId(requestId) + .build(); + } + @Test void authenticateReturnsUnavailableWhenStubIsNotInitialized() throws Exception { AuthenticateResponse response = newClient(null).authenticate("demo@example.com", "swordfish"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 9b38159a98..feeccfb89c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -26,6 +26,9 @@ void helpWithoutTopicShowsTopicIndex() { assertTrue(result.outputs().get(0).text().contains("HELP MOVEMENT")); assertTrue(result.outputs().get(0).text().contains("HELP SAY")); assertTrue(result.outputs().get(0).text().contains("HELP WHO")); + assertTrue(result.outputs().get(0).text().contains("HELP REALMS")); + assertTrue(result.outputs().get(0).text().contains("HELP JOIN")); + assertTrue(result.outputs().get(0).text().contains("HELP CHARS")); assertTrue(result.outputs().get(0).text().contains("HELP INVENTORY")); assertTrue(result.outputs().get(0).text().contains("HELP EQUIPMENT")); } @@ -47,6 +50,17 @@ void helpWhoTopicExplainsGameplayOnlyScope() { assertTrue(result.outputs().get(0).text().contains("You must already be in-world with PLAY.")); } + @Test + void helpJoinExplainsTheExplicitPublicMembershipStep() { + TextCommandInterpretationResult result = + handler.handle(new TextCommand(TextCommandType.HELP, List.of("join"), "HELP join")); + + assertTrue(result.commandResult().accepted()); + assertTrue(result.outputs().get(0).text().contains("JOIN ")); + assertTrue(result.outputs().get(0).text().contains("public-production membership")); + assertTrue(result.outputs().get(0).text().contains("Use REALMS first")); + } + @Test void helpFriendsTopicExplainsVisibilityReadAndWriteSurface() { TextCommandInterpretationResult result = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java index 5dc7755cb2..7c2a88a113 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java @@ -46,6 +46,39 @@ void parsesOneArgumentLoginAsEmailChallengeRequest() { assertEquals("demo@example.com", payload.email()); } + @Test + void parsesJoinAsOneAdapterLocalWorldSelector() { + TextCommand command = parser.parse("JOIN tenant-a/world-a"); + + assertEquals(TextCommandType.JOIN, command.type()); + assertEquals(List.of("tenant-a/world-a"), command.args()); + assertEquals(new TextCommandPayload.JoinRequest("tenant-a/world-a"), command.payload()); + } + + @Test + void rejectsJoinWithoutExactlyOneWorldSelector() { + TextCommand missingSelector = parser.parse("JOIN"); + TextCommand extraArguments = parser.parse("JOIN world-a realm-b"); + + assertEquals(TextCommandType.JOIN, missingSelector.type()); + assertFalse(missingSelector.joinRequestPayload().isPresent()); + assertEquals(TextCommandType.JOIN, extraArguments.type()); + assertFalse(extraArguments.joinRequestPayload().isPresent()); + } + + @Test + void resolvesJoinThroughTheBuiltInAuthenticatedWorldDispatchDefinition() { + TextCommandDefinition definition = + new BuiltInTextCommandDefinitionProvider() + .definitions().stream() + .filter(candidate -> candidate.type() == TextCommandType.JOIN) + .findFirst() + .orElseThrow(); + + assertEquals(TextCommandDispatchGroup.WORLDS, definition.dispatchGroup()); + assertEquals(TextCommandStageRequirement.LOGIN, definition.stageRequirement()); + } + @Test void rejectsLegacyThreeArgumentLoginShape() { TextCommand command = parser.parse("LOGIN demo@example.com swordfish 123456"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 1b955207e9..ee07bed6df 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -5,13 +5,19 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; @@ -64,6 +70,7 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { @Test void publishesCommandEventForGameplayScopedRealmsBrowse() { + gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 1L, 2L, false))); SessionContext context = new SessionContext( 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); @@ -144,6 +151,129 @@ void skipsCommandEventWithoutGameplayContext() { Mockito.verifyNoInteractions(scriptEventPublisher); } + @Test + void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + DirectTextConnectScopeSessionStore scopeStore = new DirectTextConnectScopeSessionStore(); + UUID realmId = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + UUID namespaceId = UUID.fromString("42d234a2-7487-4dda-a7e5-a3831214328e"); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo-world", + "Demo World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 9L, + 4L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 7L, + realmId, + namespaceId))))); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore), + scriptEventPublisher); + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-account-scope") + .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .build()); + when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false) + .setOutcomeCode("AUTH_UNAVAILABLE") + .build(), + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("CREATED") + .build()); + SessionContext context = + new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); + + TextCommandInterpretationResult realmsResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.REALMS, List.of("demo-world"), "REALMS demo-world"), + false, + Optional.of(context))); + TextCommandInterpretationResult firstJoinResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), + false, + Optional.of(context))); + TextCommandInterpretationResult retryJoinResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), + false, + Optional.of(context))); + + assertThat(realmsResult.commandResult().accepted()).isTrue(); + assertThat(firstJoinResult.commandResult().accepted()).isFalse(); + assertThat(retryJoinResult.commandResult().accepted()).isTrue(); + assertThat(realmsResult.outputs()) + .singleElement() + .extracting(output -> output.payload()) + .isInstanceOf(RealmBrowseViewOutput.class); + org.mockito.ArgumentCaptor + callerCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + org.mockito.ArgumentCaptor targetCaptor = + org.mockito.ArgumentCaptor.forClass(DirectTextConnectScopeTarget.class); + Mockito.verify(accountClient) + .issueDirectTextConnectScope(callerCaptor.capture(), targetCaptor.capture()); + assertThat(callerCaptor.getValue().getAccountId()).isEqualTo("41"); + assertThat(callerCaptor.getValue().getSessionId()).isEqualTo("7"); + assertThat(targetCaptor.getValue().realmId()).isEqualTo(realmId.toString()); + assertThat(targetCaptor.getValue().catalogRevision()).isEqualTo(7L); + assertThat(targetCaptor.getValue().pointerVersion()).isEqualTo(4L); + + org.mockito.ArgumentCaptor + joinContextCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + org.mockito.ArgumentCaptor scopeIdCaptor = + org.mockito.ArgumentCaptor.forClass(String.class); + org.mockito.ArgumentCaptor requestIdCaptor = + org.mockito.ArgumentCaptor.forClass(String.class); + Mockito.verify(accountClient, Mockito.times(2)) + .joinPublicProductionMembership( + joinContextCaptor.capture(), scopeIdCaptor.capture(), requestIdCaptor.capture()); + List joinContexts = + joinContextCaptor.getAllValues(); + List scopeIds = scopeIdCaptor.getAllValues(); + List requestIds = requestIdCaptor.getAllValues(); + assertThat(scopeIds.getFirst()).isEqualTo("opaque-account-scope"); + assertThat(requestIds.getFirst()).isNotBlank(); + assertThat(requestIds.getLast()).isEqualTo(requestIds.getFirst()); + assertThat(scopeIds.getLast()).isEqualTo(scopeIds.getFirst()); + assertThat(joinContexts.getFirst().getRequestId()).isEqualTo(requestIds.getFirst()); + assertThat(joinContexts.getFirst().getAccountId()).isEqualTo("41"); + assertThat(joinContexts.getFirst().getSessionId()).isEqualTo("7"); + assertThat(joinContexts.getFirst().getRealmId()).isEqualTo(realmId.toString()); + assertThat(joinContexts.getLast()).isEqualTo(joinContexts.getFirst()); + Mockito.verify(scriptEventPublisher) + .publishCommandEvent( + Mockito.eq(context), + Mockito.argThat(gameplayCommand -> "REALMS".equals(gameplayCommand.getCommandName()))); + } + private static GameplayCatalogProperties.World world( String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java new file mode 100644 index 0000000000..cce6340463 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameplayAdmissionPointerRepositoryTest { + @Test + void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-identity;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + + GameplayAdmissionPointer shared = pointer(7L, 44L, "SHARED", "production"); + GameplayAdmissionPointer createdShared = repository.save(shared); + UUID sharedRealmId = createdShared.getRealmId(); + UUID sharedNamespaceId = createdShared.getPlayableStateNamespaceId(); + GameplayAdmissionPointer sharedReadback = + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); + + GameplayAdmissionPointer secondShared = + repository.save(pointer(7L, 45L, "SHARED", "seasonal")); + GameplayAdmissionPointer isolated = repository.save(pointer(7L, 46L, "ISOLATED", "playtest")); + + assertNotNull(sharedRealmId); + assertNotNull(sharedNamespaceId); + assertEquals(sharedRealmId, sharedReadback.getRealmId()); + assertEquals(sharedNamespaceId, sharedReadback.getPlayableStateNamespaceId()); + assertNotNull(secondShared.getRealmId()); + assertNotNull(isolated.getRealmId()); + assertEquals(sharedNamespaceId, secondShared.getPlayableStateNamespaceId()); + assertNotEquals(sharedRealmId, secondShared.getRealmId()); + assertNotEquals(sharedNamespaceId, isolated.getPlayableStateNamespaceId()); + + createdShared.setGameInstanceId(99L); + createdShared.setPointerVersion(2L); + createdShared.setCatalogRevision(1L); + GameplayAdmissionPointer replaced = repository.save(createdShared); + + assertEquals(99L, replaced.getGameInstanceId()); + assertEquals(sharedRealmId, replaced.getRealmId()); + assertEquals(sharedNamespaceId, replaced.getPlayableStateNamespaceId()); + } + } + + @Test + void repositoryRejectsAttemptToReplaceStableRealmIdentity() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-identity-immutable;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + GameplayAdmissionPointer created = repository.save(pointer(7L, 44L, "ISOLATED", "fork")); + + created.setPointerVersion(2L); + created.setRealmId(UUID.randomUUID()); + + org.junit.jupiter.api.Assertions.assertThrows( + IllegalStateException.class, () -> repository.save(created)); + } + } + + private static GameplayAdmissionPointer pointer( + long tenantId, long gameInstanceId, String stateScope, String realmSlug) { + GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); + pointer.setWorldSlug("demo"); + pointer.setWorldDisplayName("Demo World"); + pointer.setRealmSlug(realmSlug); + pointer.setRealmDisplayName(realmSlug); + pointer.setTenantId(tenantId); + pointer.setGameInstanceId(gameInstanceId); + pointer.setPointerVersion(1L); + pointer.setCatalogRevision(1L); + pointer.setVisible(true); + pointer.setPublicProductionRealm("production".equals(realmSlug)); + pointer.setRequiresCharacterSelection(false); + pointer.setStateScope(stateScope); + pointer.setCharacterCreationPolicy("ALLOW_NEW"); + pointer.setLastUpdatedBy("test"); + pointer.setLastUpdateReason("test"); + pointer.setCreatedAt(Instant.parse("2026-09-24T00:00:00Z")); + pointer.setUpdatedAt(Instant.parse("2026-09-24T00:00:00Z")); + return pointer; + } + + private static void createSchema(DSLContext dsl) { + dsl.execute( + """ + CREATE TABLE gameplay_tenant_shared_playable_state_namespace ( + tenant_id BIGINT PRIMARY KEY, + playable_state_namespace_id UUID NOT NULL UNIQUE, + allocated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + """); + dsl.execute( + """ + CREATE TABLE gameplay_admission_pointer ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + realm_slug VARCHAR(120) NOT NULL, + realm_display_name VARCHAR(200) NOT NULL, + tenant_id BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + realm_id UUID, + playable_state_namespace_id UUID, + visible BOOLEAN NOT NULL, + public_production_realm BOOLEAN NOT NULL, + requires_character_selection BOOLEAN NOT NULL, + state_scope VARCHAR(32) NOT NULL, + character_creation_policy VARCHAR(32) NOT NULL, + last_updated_by VARCHAR(200) NOT NULL, + last_update_reason VARCHAR(500) NOT NULL, + created_at TIMESTAMP NOT NULL, + updated_at TIMESTAMP NOT NULL, + CONSTRAINT uq_pointer_tenant_world_realm UNIQUE (tenant_id, world_slug, realm_slug), + CONSTRAINT uq_pointer_tenant_runtime UNIQUE (tenant_id, game_instance_id) + ) + """); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java new file mode 100644 index 0000000000..1faab651a6 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.util.List; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; + +class DirectTextConnectScopeSessionStoreTest { + private final DirectTextConnectScopeSessionStore store = new DirectTextConnectScopeSessionStore(); + + @Test + void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { + SessionContext caller = session(7L, 41L); + Instant expiry = Instant.parse("2030-01-01T00:00:00Z"); + store.replaceWorldScopes( + caller, + "1", + "demo-world", + List.of(scopedRealm(caller, "demo-world", "scope-secret", expiry))); + + assertThat(store.publicProductionScope(caller, "1", Instant.parse("2029-01-01T00:00:00Z"))) + .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("scope-secret")); + assertThat( + store.publicProductionScope( + session(8L, 41L), "1", Instant.parse("2029-01-01T00:00:00Z"))) + .isEmpty(); + assertThat( + store.publicProductionScope( + session(7L, 42L), "1", Instant.parse("2029-01-01T00:00:00Z"))) + .isEmpty(); + } + + @Test + void refusesExpiredAndAmbiguousPublicScopes() { + SessionContext caller = session(7L, 41L); + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of( + scopedRealm( + caller, "production", "expired-scope", Instant.parse("2029-01-01T00:00:00Z")))); + + assertThat( + store.publicProductionScope( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z"))) + .isEmpty(); + + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of( + scopedRealm(caller, "production-a", "scope-a", Instant.parse("2031-01-01T00:00:00Z")), + scopedRealm(caller, "production-b", "scope-b", Instant.parse("2031-01-01T00:00:00Z")))); + + assertThat( + store.publicProductionScope( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z"))) + .isEmpty(); + } + + @Test + void clearsPriorScopeBeforeReplacingTheWorldBinding() { + SessionContext caller = session(7L, 41L); + store.replaceWorldScopes( + caller, + "1", + "demo-world", + List.of( + scopedRealm( + caller, "production", "scope-secret", Instant.parse("2031-01-01T00:00:00Z")))); + + store.clearWorldScopes(caller, "1"); + + assertThat(store.publicProductionScope(caller, "1", Instant.parse("2030-01-01T00:00:00Z"))) + .isEmpty(); + } + + @Test + void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { + SessionContext caller = session(7L, 41L); + Instant expiry = Instant.parse("2031-01-01T00:00:00Z"); + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of(scopedRealm(caller, "production", "scope-first", expiry))); + + DirectTextConnectScopeSessionStore.JoinScope firstAttempt = + store + .publicProductionScopeForJoin( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) + .orElseThrow(); + DirectTextConnectScopeSessionStore.JoinScope retryAttempt = + store + .publicProductionScopeForJoin( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) + .orElseThrow(); + + assertThat(firstAttempt.requestId()).isEqualTo(retryAttempt.requestId()); + assertThat(firstAttempt.scope().connectScopeId()) + .isEqualTo(retryAttempt.scope().connectScopeId()); + + store.clearWorldScopes(caller, "demo-world"); + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of(scopedRealm(caller, "production", "scope-second", expiry))); + DirectTextConnectScopeSessionStore.JoinScope newAttempt = + store + .publicProductionScopeForJoin( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) + .orElseThrow(); + + assertThat(newAttempt.scope().connectScopeId()).isEqualTo("scope-second"); + assertThat(newAttempt.requestId()).isNotEqualTo(firstAttempt.requestId()); + } + + private static SessionContext session(long sessionId, long accountId) { + return new SessionContext(sessionId, 22L, accountId, 7001L, 9L, "jwt"); + } + + private static DirectTextConnectScopeSessionStore.ScopedRealm scopedRealm( + SessionContext caller, String realmSlug, String scopeId, Instant expiry) { + PlayerExecutionContext playerContext = + PlayerExecutionContext.newBuilder() + .setAccountId(Long.toString(caller.accountId())) + .setSessionId(Long.toString(caller.sessionId())) + .setTenantId("22") + .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") + .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") + .setPlayableStateScope("SHARED") + .setGameInstanceId("9") + .build(); + return new DirectTextConnectScopeSessionStore.ScopedRealm( + realmSlug, true, scopeId, expiry, playerContext); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index ae5d5933b0..f84933a724 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -38,6 +38,7 @@ void upsertPointerRejectsMismatchedExpectedVersion() { GameplayAdmissionPointer existing = new GameplayAdmissionPointer(); existing.setId(11L); existing.setPointerVersion(3L); + existing.setStateScope("SHARED"); when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) .thenReturn(Optional.of(existing)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 27318cf7ba..5fb3627876 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -18,13 +18,18 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; @@ -440,36 +445,26 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); - world.setSlug("demo"); - world.setDisplayName("Demo World"); - GameplayCatalogProperties.Realm realm = new GameplayCatalogProperties.Realm(); - realm.setSlug("production"); - realm.setDisplayName("Live Realm"); - realm.setTenantId(7L); - realm.setGameInstanceId(999L); - realm.setPointerVersion(999L); - realm.setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); - realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - world.setRealms(List.of(realm)); - properties.setWorlds(List.of(world)); + GameplayAdmissionPointerSnapshot authoritativeSnapshot = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + false, + false, + "ISOLATED", + "COPIED_ONLY", + 29L, + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(authoritativeSnapshot)); Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn( - java.util.Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 7L, - 44L, - 17L, - true, - false, - false, - "ISOLATED", - "COPIED_ONLY"))); + .thenReturn(java.util.Optional.of(authoritativeSnapshot)); GameSessionGrpcService service = newService( pingService, @@ -478,7 +473,7 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { textCommandInterpreter, gameInstanceRepository, pointerAuthorityService, - TestGameplayWorldCatalogs.fromProperties(properties), + new GameplayWorldCatalog(pointerAuthorityService), tickService, meterRegistry, ipLimiter); @@ -504,6 +499,12 @@ public void onCompleted() {} assertEquals(1, realmsRef.get().getRealmsCount()); assertEquals("production", realmsRef.get().getRealms(0).getRealmSlug()); assertEquals("ISOLATED", realmsRef.get().getRealms(0).getStateScope()); + assertEquals(17L, realmsRef.get().getRealms(0).getPointerVersion()); + assertEquals(29L, realmsRef.get().getRealms(0).getCatalogRevision()); + assertEquals("8a1df0f1-1b57-465e-9c4b-bb34f8153d31", realmsRef.get().getRealms(0).getRealmId()); + assertEquals( + "2ea958e0-13a2-41d0-9c39-59a96cf31412", + realmsRef.get().getRealms(0).getPlayableStateNamespaceId()); AtomicReference pointerRef = new AtomicReference<>(); service.getAdmissionPointer( @@ -529,9 +530,248 @@ public void onCompleted() {} assertEquals("44", pointerRef.get().getAdmissionPointer().getGameInstanceId()); assertEquals(17L, pointerRef.get().getAdmissionPointer().getPointerVersion()); + assertEquals(29L, pointerRef.get().getAdmissionPointer().getCatalogRevision()); + assertEquals( + "8a1df0f1-1b57-465e-9c4b-bb34f8153d31", + pointerRef.get().getAdmissionPointer().getRealmId()); + assertEquals( + "2ea958e0-13a2-41d0-9c39-59a96cf31412", + pointerRef.get().getAdmissionPointer().getPlayableStateNamespaceId()); Mockito.verify(pointerAuthorityService).findPointer(7L, "demo", "production"); } + @Test + void missingCatalogRevisionFailsClosedForCatalogAndAdmissionPointerReads() { + PingService pingService = Mockito.mock(PingService.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); + TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + TickService tickService = Mockito.mock(TickService.class); + IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + GameplayAdmissionPointerSnapshot missingRevision = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 0L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingRevision)); + Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + .thenReturn(java.util.Optional.of(missingRevision)); + GameSessionGrpcService service = + newService( + pingService, + gameInstanceService, + featureFlagService, + textCommandInterpreter, + gameInstanceRepository, + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + tickService, + meterRegistry, + ipLimiter); + + AtomicReference realmsRef = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + realmsRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", realmsRef.get().getError().getCode()); + assertEquals(0, realmsRef.get().getRealmsCount()); + + AtomicReference pointerRef = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + pointerRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerRef.get().getError().getCode()); + assertFalse(pointerRef.get().hasAdmissionPointer()); + } + + @Test + void missingStableRealmIdentityFailsClosedForCatalogReads() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot missingIdentity = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingIdentity)); + Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + .thenReturn(java.util.Optional.of(missingIdentity)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertEquals(0, response.get().getRealmsCount()); + + AtomicReference pointerResponse = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + pointerResponse.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.get().getError().getCode()); + assertFalse(pointerResponse.get().hasAdmissionPointer()); + } + + @Test + void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { + GameplayAdmissionPointerRepository pointerRepository = + Mockito.mock(GameplayAdmissionPointerRepository.class); + GameplayAdmissionPointerEventRepository eventRepository = + Mockito.mock(GameplayAdmissionPointerEventRepository.class); + AtomicReference currentPointer = new AtomicReference<>(); + Mockito.when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + .thenAnswer(invocation -> java.util.Optional.ofNullable(currentPointer.get())); + Mockito.when(pointerRepository.save(Mockito.any(GameplayAdmissionPointer.class))) + .thenAnswer( + invocation -> { + GameplayAdmissionPointer pointer = invocation.getArgument(0); + if (pointer.getId() == null) { + pointer.setId(11L); + } + currentPointer.set(pointer); + return pointer; + }); + Mockito.when(eventRepository.save(Mockito.any(GameplayAdmissionPointerEvent.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + DatabaseGameplayAdmissionPointerAuthorityService authorityService = + new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); + + GameplayAdmissionPointerSnapshot created = + authorityService.upsertPointer(pointerMutation(44L, true, 0L)); + GameplayAdmissionPointerSnapshot policyChanged = + authorityService.upsertPointer(pointerMutation(44L, false, 1L)); + GameplayAdmissionPointerSnapshot routeChanged = + authorityService.upsertPointer(pointerMutation(45L, false, 2L)); + + assertEquals(1L, created.catalogRevision()); + assertEquals(1L, created.pointerVersion()); + assertEquals(2L, policyChanged.catalogRevision()); + assertEquals(2L, policyChanged.pointerVersion()); + assertEquals(2L, routeChanged.catalogRevision()); + assertEquals(3L, routeChanged.pointerVersion()); + } + + private static GameplayAdmissionPointerMutation pointerMutation( + long gameInstanceId, boolean publicProductionRealm, Long expectedPointerVersion) { + return new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + gameInstanceId, + true, + publicProductionRealm, + false, + "SHARED", + "ALLOW_NEW", + "test", + "catalog revision test", + "catalog-revision-test-" + expectedPointerVersion, + expectedPointerVersion, + null); + } + @Test void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java new file mode 100644 index 0000000000..5301aae34d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.loggingadmin.config; + +import java.util.HashSet; +import java.util.Set; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.GlobalServerInterceptor; + +/** Allows mTLS-guarded Account audit methods to run without a JWT token. */ +@Configuration(proxyBeanMethods = false) +public class AccountAuditGrpcAuthConfiguration { + private static final Set ACCOUNT_AUDIT_METHODS = + Set.of( + "logging_admin.v1.LoggingAdminService/CreateLogEvent", + "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt"); + + @Bean + @GlobalServerInterceptor + @ConditionalOnProperty( + prefix = "firemud.auth.grpc", + name = "interceptor-enabled", + havingValue = "true", + matchIfMissing = true) + @ConditionalOnMissingBean(AuthTokenInterceptor.class) + public AuthTokenInterceptor accountAuditAuthTokenInterceptor( + @Qualifier("jwtUtil") JwtUtil jwtUtil, GrpcAuthProperties properties) { + Set unauthenticatedMethods = new HashSet<>(properties.getPublicMethods()); + unauthenticatedMethods.addAll(ACCOUNT_AUDIT_METHODS); + return new AuthTokenInterceptor(jwtUtil, unauthenticatedMethods); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java new file mode 100644 index 0000000000..b80457862e --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public record AccountAuditReceiptDto( + AccountAuditScope scope, + Long tenantId, + String auditEventId, + String receiptId, + long logEventId, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + AccountAuditReceiptStatus status, + AccountAuditReceiptOutcome outcome) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java new file mode 100644 index 0000000000..35bdf8d33a --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditReceiptOutcome { + ACCEPTED, + DUPLICATE, + NON_REPLAYABLE, + IDEMPOTENCY_CONFLICT +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java new file mode 100644 index 0000000000..9c9a8f5047 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditReceiptStatus { + COMMITTED, + MINIMIZED, + CONFLICT +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java new file mode 100644 index 0000000000..e3f9b85a3d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditScope { + PLATFORM("platform"), + TENANT("tenant"); + + private final String databaseValue; + + AccountAuditScope(String databaseValue) { + this.databaseValue = databaseValue; + } + + public String databaseValue() { + return databaseValue; + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java index bbded3dd0b..0e187d9160 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java @@ -1,10 +1,22 @@ package net.firedevops.firemud.loggingadmin.dto; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Size; +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +/** The immutable Account audit envelope accepted by the existing CreateLogEvent RPC. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Protobuf ByteString is immutable, so retaining and exposing the payload is safe.") public record CreateLogEventRequest( - @NotNull Long tenantId, - Long accountId, - @NotNull @Size(max = 50) String type, - @NotNull @Size(max = 255) String message) {} + AccountAuditScope scope, + Long tenantId, + String auditEventId, + String producerService, + String eventType, + Instant occurredAt, + int schemaVersion, + ByteString payload, + int payloadDigestVersion, + String payloadDigest) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java new file mode 100644 index 0000000000..9e04277e29 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.loggingadmin.entity; + +import java.util.UUID; + +/** A durable receiver-side audit envelope and its readback receipt. */ +public record AccountAuditReceipt( + long id, + UUID receiptId, + String scope, + Long tenantId, + String auditEventId, + String producerService, + String eventType, + long occurredAtSeconds, + int occurredAtNanos, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + byte[] payload, + String status, + String outcome) { + public AccountAuditReceipt { + payload = payload == null ? null : payload.clone(); + } + + @Override + public byte[] payload() { + return payload == null ? null : payload.clone(); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java new file mode 100644 index 0000000000..226e9d4046 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java @@ -0,0 +1,3 @@ +package net.firedevops.firemud.loggingadmin.entity; + +public record AccountAuditReceiptInsertResult(AccountAuditReceipt receipt, boolean inserted) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java new file mode 100644 index 0000000000..bcaffd3767 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountAuditReceiptRepository { + private final DSLContext dsl; + + public AccountAuditReceiptRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AccountAuditReceiptInsertResult insertIfAbsent( + CreateLogEventRequest request, UUID receiptId) { + long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); + int inserted = + dsl.insertInto(ACCOUNT_AUDIT_RECEIPTS) + .set(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID, receiptId) + .set(ACCOUNT_AUDIT_RECEIPTS.SCOPE, request.scope().databaseValue()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_ID, request.tenantId()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY, tenantKey) + .set(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID, request.auditEventId()) + .set(ACCOUNT_AUDIT_RECEIPTS.PRODUCER_SERVICE, request.producerService()) + .set(ACCOUNT_AUDIT_RECEIPTS.EVENT_TYPE, request.eventType()) + .set(ACCOUNT_AUDIT_RECEIPTS.OCCURRED_AT_SECONDS, request.occurredAt().getEpochSecond()) + .set(ACCOUNT_AUDIT_RECEIPTS.OCCURRED_AT_NANOS, request.occurredAt().getNano()) + .set(ACCOUNT_AUDIT_RECEIPTS.SCHEMA_VERSION, request.schemaVersion()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD_DIGEST_VERSION, request.payloadDigestVersion()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD_DIGEST, request.payloadDigest()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD, request.payload().toByteArray()) + .set(ACCOUNT_AUDIT_RECEIPTS.STATUS, "COMMITTED") + .set(ACCOUNT_AUDIT_RECEIPTS.OUTCOME, "ACCEPTED") + .onConflictDoNothing() + .execute(); + AccountAuditReceipt receipt = + findByIdentity(request, tenantKey) + .orElseThrow( + () -> + new IllegalStateException( + "Account audit receipt identity conflict did not resolve to a receipt")); + return new AccountAuditReceiptInsertResult(receipt, inserted == 1); + } + + public Optional findByIdentity( + CreateLogEventRequest request, long tenantKey) { + return dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) + .where( + ACCOUNT_AUDIT_RECEIPTS + .SCOPE + .eq(request.scope().databaseValue()) + .and(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY.eq(tenantKey)) + .and(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) + .fetchOptional(this::toEntity); + } + + private AccountAuditReceipt toEntity(Record record) { + AccountAuditReceiptsRecord receiptRecord = (AccountAuditReceiptsRecord) record; + return new AccountAuditReceipt( + receiptRecord.getId(), + receiptRecord.getReceiptId(), + receiptRecord.getScope(), + receiptRecord.getTenantId(), + receiptRecord.getAuditEventId(), + receiptRecord.getProducerService(), + receiptRecord.getEventType(), + receiptRecord.getOccurredAtSeconds(), + receiptRecord.getOccurredAtNanos(), + receiptRecord.getSchemaVersion(), + receiptRecord.getPayloadDigestVersion(), + receiptRecord.getPayloadDigest(), + receiptRecord.getPayload(), + receiptRecord.getStatus(), + receiptRecord.getOutcome()); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java new file mode 100644 index 0000000000..52b49613b5 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.service; + +public class AuditReceiptNotFoundException extends RuntimeException { + public AuditReceiptNotFoundException() { + super("Account audit receipt not found"); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java new file mode 100644 index 0000000000..c8abf99170 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.service; + +public class AuditStorageUnavailableException extends RuntimeException { + public AuditStorageUnavailableException(Throwable cause) { + super("Account audit receipt storage is unavailable", cause); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java index 0617b3ad2e..e86cc22dc0 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.loggingadmin.service; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; public interface LogEventService { - LogEventDto createLogEvent(CreateLogEventRequest request); + AccountAuditReceiptDto createLogEvent(CreateLogEventRequest request); + + AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java index fc3c54d6a0..6d87af4ef8 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java @@ -1,14 +1,28 @@ package net.firedevops.firemud.loggingadmin.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.micrometer.core.annotation.Timed; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; -import net.firedevops.firemud.loggingadmin.entity.LogEvent; -import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; +import org.jooq.exception.DataAccessException; import org.slf4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -19,31 +33,184 @@ justification = "Spring injects the shared repository singleton for this service seam.") public class LogEventServiceImpl implements LogEventService { private static final Logger logger = LoggingUtil.getLogger(LogEventServiceImpl.class); + private static final String ACCOUNT_SERVICE = "account-service"; + private static final String SHA_256_PREFIX = "sha256:"; - private final LogEventRepository repository; + private final AccountAuditReceiptRepository repository; - public LogEventServiceImpl(LogEventRepository repository) { + public LogEventServiceImpl(AccountAuditReceiptRepository repository) { this.repository = repository; } @Override @Transactional - @Timed(value = "logging.createLogEvent") - public LogEventDto createLogEvent(CreateLogEventRequest request) { - logger.info("Creating log event {} for tenant {}", request.type(), request.tenantId()); - LogEvent entity = new LogEvent(); - entity.setTenantId(request.tenantId()); - entity.setAccountId(request.accountId()); - entity.setType(request.type()); - entity.setMessage(request.message()); - entity.setTimestamp(Instant.now()); - entity = repository.save(entity); - return new LogEventDto( - entity.getId(), - entity.getTenantId(), - entity.getAccountId(), - entity.getType(), - entity.getMessage(), - entity.getTimestamp()); + public AccountAuditReceiptDto createLogEvent(CreateLogEventRequest request) { + validateEnvelope(request); + try { + AccountAuditReceiptInsertResult result = + repository.insertIfAbsent(request, UUID.randomUUID()); + return receiptOutcome(result.receipt(), request, result.inserted()); + } catch (DataAccessException ex) { + logger.warn("Account audit receipt write is unavailable: {}", ex.getClass().getSimpleName()); + throw new AuditStorageUnavailableException(ex); + } + } + + @Override + @Transactional(readOnly = true) + public AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request) { + validateEnvelope(request); + try { + long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); + AccountAuditReceipt receipt = + repository + .findByIdentity(request, tenantKey) + .orElseThrow(AuditReceiptNotFoundException::new); + return receiptOutcome(receipt, request, false); + } catch (AuditReceiptNotFoundException ex) { + throw ex; + } catch (DataAccessException ex) { + logger.warn("Account audit receipt read is unavailable: {}", ex.getClass().getSimpleName()); + throw new AuditStorageUnavailableException(ex); + } + } + + private static AccountAuditReceiptDto receiptOutcome( + AccountAuditReceipt receipt, CreateLogEventRequest request, boolean inserted) { + if (inserted) { + return toDto( + receipt, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.ACCEPTED); + } + + boolean metadataMatches = metadataMatches(receipt, request); + if (!metadataMatches) { + return toDto( + receipt, + AccountAuditReceiptStatus.CONFLICT, + AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + } + + byte[] retainedPayload = receipt.payload(); + if (retainedPayload == null) { + return toDto( + receipt, AccountAuditReceiptStatus.MINIMIZED, AccountAuditReceiptOutcome.NON_REPLAYABLE); + } + if (!Arrays.equals(retainedPayload, request.payload().toByteArray())) { + return toDto( + receipt, + AccountAuditReceiptStatus.CONFLICT, + AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + } + + if ("MINIMIZED".equals(receipt.status()) || "NON_REPLAYABLE".equals(receipt.outcome())) { + return toDto( + receipt, AccountAuditReceiptStatus.MINIMIZED, AccountAuditReceiptOutcome.NON_REPLAYABLE); + } + if (!"COMMITTED".equals(receipt.status())) { + throw new IllegalStateException("Unknown persisted account audit receipt status"); + } + return toDto( + receipt, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.DUPLICATE); + } + + private static boolean metadataMatches( + AccountAuditReceipt receipt, CreateLogEventRequest request) { + Instant occurredAt = request.occurredAt(); + return receipt.scope().equals(request.scope().databaseValue()) + && Objects.equals(receipt.tenantId(), request.tenantId()) + && receipt.auditEventId().equals(request.auditEventId()) + && receipt.producerService().equals(request.producerService()) + && receipt.eventType().equals(request.eventType()) + && receipt.occurredAtSeconds() == occurredAt.getEpochSecond() + && receipt.occurredAtNanos() == occurredAt.getNano() + && receipt.schemaVersion() == request.schemaVersion() + && receipt.payloadDigestVersion() == request.payloadDigestVersion() + && receipt.payloadDigest().equals(request.payloadDigest()); + } + + private static AccountAuditReceiptDto toDto( + AccountAuditReceipt receipt, + AccountAuditReceiptStatus status, + AccountAuditReceiptOutcome outcome) { + return new AccountAuditReceiptDto( + "platform".equals(receipt.scope()) + ? net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM + : net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.TENANT, + receipt.tenantId(), + receipt.auditEventId(), + receipt.receiptId().toString(), + receipt.id(), + receipt.schemaVersion(), + receipt.payloadDigestVersion(), + receipt.payloadDigest(), + status, + outcome); + } + + private static void validateEnvelope(CreateLogEventRequest request) { + if (request == null + || request.scope() == null + || request.auditEventId() == null + || request.auditEventId().isBlank() + || request.producerService() == null + || !ACCOUNT_SERVICE.equals(request.producerService()) + || request.eventType() == null + || request.eventType().isBlank() + || request.occurredAt() == null + || request.schemaVersion() <= 0 + || request.payload() == null + || request.payloadDigest() == null) { + throw new IllegalArgumentException("Account audit envelope is incomplete"); + } + if (!isCanonicalUuid(request.auditEventId())) { + throw new IllegalArgumentException("auditEventId must be a canonical UUID"); + } + if (request.scope() == net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM) { + if (request.tenantId() != null) { + throw new IllegalArgumentException("tenantId must be absent for platform scope"); + } + } else if (request.tenantId() == null || request.tenantId() <= 0) { + throw new IllegalArgumentException("tenantId must be positive for tenant scope"); + } + if (request.payloadDigestVersion() != 1) { + throw new IllegalArgumentException("payloadDigestVersion must be 1"); + } + if (!request.payloadDigest().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("payloadDigest must be lowercase sha256 hex"); + } + byte[] payloadBytes = request.payload().toByteArray(); + validateUtf8(payloadBytes); + String computedDigest = SHA_256_PREFIX + sha256Hex(payloadBytes); + if (!computedDigest.equals(request.payloadDigest())) { + throw new IllegalArgumentException("payloadDigest does not match the exact payload bytes"); + } + } + + private static boolean isCanonicalUuid(String value) { + try { + return value.equals(UUID.fromString(value).toString()); + } catch (IllegalArgumentException ex) { + return false; + } + } + + private static void validateUtf8(byte[] payload) { + try { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(payload)); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("payload must contain exact UTF-8 bytes", ex); + } + } + + private static String sha256Hex(byte[] payload) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index 928418f154..f0cecbee96 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -1,23 +1,37 @@ package net.firedevops.firemud.loggingadmin.service.impl; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Set; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.loggingadmin.service.ModerationService; import net.firedevops.firemud.loggingadmin.v1.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.TransactionException; @GrpcService public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdminServiceImplBase { @@ -28,6 +42,11 @@ public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdmi "Feature-flag toggles are unavailable until the shared mutation gate is implemented"; private static final Set MODERATION_POLICY_CALLERS = Set.of("game-session-service", "social-groups-service"); + private static final String ACCOUNT_SERVICE = "account-service"; + private static final Map> ACCOUNT_AUDIT_CALLER_ALLOWLIST = + Map.of( + "CreateLogEvent", Set.of(ACCOUNT_SERVICE), + "ReadLogEventReceipt", Set.of(ACCOUNT_SERVICE)); private final LogQueryService logQueryService; private final LogEventService logEventService; @@ -174,51 +193,227 @@ public void queryLogs( public void createLogEvent( CreateLogEventRequest request, StreamObserver responseObserver) { try { - AdminRoleGuard.requireAdminRole(); - var dto = - logEventService.createLogEvent( - new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.parseOptionalPositiveLong( - request.getAccountId(), "accountId"), - request.getType(), - request.getMessage())); - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder().setLogEventId(String.valueOf(dto.id())).build(); + requireAccountAuditCaller("CreateLogEvent"); + AccountAuditReceiptDto receipt = logEventService.createLogEvent(toAuditRequest(request)); + CreateLogEventResponse response = toCreateLogEventResponse(receipt); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "CreateLogEvent", - "PERMISSION_DENIED", - ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); } catch (IllegalArgumentException ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "CreateLogEvent", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + responseObserver.onError( + Status.INVALID_ARGUMENT.withDescription(ex.getMessage()).asRuntimeException()); + } catch (AuditStorageUnavailableException ex) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(ex.getMessage()).asRuntimeException()); + } catch (DataAccessException | TransactionException ex) { + logger.warn("CreateLogEvent transaction is unavailable: {}", ex.getClass().getSimpleName()); + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Account audit ingress storage is unavailable") + .asRuntimeException()); } catch (Exception ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "CreateLogEvent", ex)) - .build(); - responseObserver.onNext(response); + logger.error("CreateLogEvent failed before producing an audit receipt", ex); + responseObserver.onError( + Status.INTERNAL.withDescription("Account audit ingress failed").asRuntimeException()); + } + } + + @Override + @Timed(value = "loggingadminGrpc.readLogEventReceipt") + public void readLogEventReceipt( + ReadLogEventReceiptRequest request, + StreamObserver responseObserver) { + try { + requireAccountAuditCaller("ReadLogEventReceipt"); + AccountAuditReceiptDto receipt = logEventService.readLogEventReceipt(toAuditRequest(request)); + responseObserver.onNext(toReadLogEventReceiptResponse(receipt)); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.INVALID_ARGUMENT.withDescription(ex.getMessage()).asRuntimeException()); + } catch (AuditReceiptNotFoundException ex) { + responseObserver.onError( + Status.NOT_FOUND.withDescription(ex.getMessage()).asRuntimeException()); + } catch (AuditStorageUnavailableException ex) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(ex.getMessage()).asRuntimeException()); + } catch (DataAccessException | TransactionException ex) { + logger.warn( + "ReadLogEventReceipt transaction is unavailable: {}", ex.getClass().getSimpleName()); + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Account audit receipt storage is unavailable") + .asRuntimeException()); + } catch (Exception ex) { + logger.error("ReadLogEventReceipt failed before producing a receipt", ex); + responseObserver.onError( + Status.INTERNAL + .withDescription("Account audit receipt read failed") + .asRuntimeException()); } } + private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( + CreateLogEventRequest request) { + return toAuditRequest( + request.getScope(), + request.getTenantId(), + request.getAuditEventId(), + request.getProducerService(), + request.getEventType(), + request.hasOccurredAt() ? request.getOccurredAt() : null, + request.getSchemaVersion(), + request.getPayload(), + request.getPayloadDigestVersion(), + request.getPayloadDigest()); + } + + private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( + ReadLogEventReceiptRequest request) { + return toAuditRequest( + request.getScope(), + request.getTenantId(), + request.getAuditEventId(), + request.getProducerService(), + request.getEventType(), + request.hasOccurredAt() ? request.getOccurredAt() : null, + request.getSchemaVersion(), + request.getPayload(), + request.getPayloadDigestVersion(), + request.getPayloadDigest()); + } + + private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope requestScope, + String tenantIdText, + String auditEventId, + String producerService, + String eventType, + Timestamp occurredAt, + int schemaVersion, + ByteString payload, + int payloadDigestVersion, + String payloadDigest) { + AccountAuditScope scope = + switch (requestScope) { + case ACCOUNT_AUDIT_SCOPE_PLATFORM -> AccountAuditScope.PLATFORM; + case ACCOUNT_AUDIT_SCOPE_TENANT -> AccountAuditScope.TENANT; + default -> throw new IllegalArgumentException("scope must be platform or tenant"); + }; + Long tenantId; + if (scope == AccountAuditScope.TENANT) { + tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); + } else { + if (!tenantIdText.isEmpty()) { + throw new IllegalArgumentException("tenantId must be absent for platform scope"); + } + tenantId = null; + } + if (!ACCOUNT_SERVICE.equals(producerService)) { + throw new IllegalArgumentException( + "producerService must match the authenticated account-service workload"); + } + if (occurredAt == null) { + throw new IllegalArgumentException("occurredAt is required"); + } + if (occurredAt.getSeconds() < -62135596800L + || occurredAt.getSeconds() > 253402300799L + || occurredAt.getNanos() < 0 + || occurredAt.getNanos() > 999999999) { + throw new IllegalArgumentException("occurredAt must be a valid protobuf timestamp"); + } + return new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( + scope, + tenantId, + auditEventId, + ACCOUNT_SERVICE, + eventType, + Instant.ofEpochSecond(occurredAt.getSeconds(), occurredAt.getNanos()), + schemaVersion, + payload, + payloadDigestVersion, + payloadDigest); + } + + private static CreateLogEventResponse toCreateLogEventResponse(AccountAuditReceiptDto receipt) { + return CreateLogEventResponse.newBuilder() + .setScope(toProtoScope(receipt.scope())) + .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) + .setAuditEventId(receipt.auditEventId()) + .setReceiptId(receipt.receiptId()) + .setLogEventId(Long.toString(receipt.logEventId())) + .setSchemaVersion(receipt.schemaVersion()) + .setPayloadDigestVersion(receipt.payloadDigestVersion()) + .setPayloadDigest(receipt.payloadDigest()) + .setStatus(toProtoStatus(receipt.status())) + .setOutcome(toProtoOutcome(receipt.outcome())) + .build(); + } + + private static ReadLogEventReceiptResponse toReadLogEventReceiptResponse( + AccountAuditReceiptDto receipt) { + return ReadLogEventReceiptResponse.newBuilder() + .setScope(toProtoScope(receipt.scope())) + .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) + .setAuditEventId(receipt.auditEventId()) + .setReceiptId(receipt.receiptId()) + .setLogEventId(Long.toString(receipt.logEventId())) + .setSchemaVersion(receipt.schemaVersion()) + .setPayloadDigestVersion(receipt.payloadDigestVersion()) + .setPayloadDigest(receipt.payloadDigest()) + .setStatus(toProtoStatus(receipt.status())) + .setOutcome(toProtoOutcome(receipt.outcome())) + .build(); + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditScope toProtoScope( + AccountAuditScope scope) { + return switch (scope) { + case PLATFORM -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; + case TENANT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; + }; + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus toProtoStatus( + AccountAuditReceiptStatus status) { + return switch (status) { + case COMMITTED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED; + case MINIMIZED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED; + case CONFLICT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT; + }; + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome toProtoOutcome( + AccountAuditReceiptOutcome outcome) { + return switch (outcome) { + case ACCEPTED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED; + case DUPLICATE -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE; + case NON_REPLAYABLE -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; + case IDEMPOTENCY_CONFLICT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT; + }; + } + @Override @Timed(value = "loggingadminGrpc.applyModerationAction") public void applyModerationAction( @@ -353,4 +548,15 @@ private static void requireAllowlistedInternalService( methodName + " requires an allowlisted internal service caller"); } } + + private static void requireAccountAuditCaller(String methodName) { + Set allowedServices = ACCOUNT_AUDIT_CALLER_ALLOWLIST.get(methodName); + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (allowedServices == null + || peerIdentity == null + || !allowedServices.contains(peerIdentity.service())) { + throw new AdminAuthorizationException( + methodName + " requires an allowlisted account-service mTLS peer"); + } + } } diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql new file mode 100644 index 0000000000..4e1a61f25a --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql @@ -0,0 +1,47 @@ +CREATE TABLE account_audit_receipts ( + id BIGSERIAL PRIMARY KEY, + receipt_id UUID NOT NULL UNIQUE, + scope VARCHAR(16) NOT NULL, + tenant_id BIGINT, + tenant_key BIGINT NOT NULL, + audit_event_id VARCHAR(36) NOT NULL, + producer_service TEXT NOT NULL, + event_type TEXT NOT NULL, + occurred_at_seconds BIGINT NOT NULL, + occurred_at_nanos INTEGER NOT NULL, + schema_version INTEGER NOT NULL, + payload_digest_version INTEGER NOT NULL, + payload_digest TEXT NOT NULL, + payload BYTEA, + status VARCHAR(16) NOT NULL, + outcome VARCHAR(32) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT chk_account_audit_receipt_scope + CHECK ( + (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND tenant_key = tenant_id + ) + ), + CONSTRAINT chk_account_audit_receipt_occurred_at_nanos + CHECK (occurred_at_nanos BETWEEN 0 AND 999999999), + CONSTRAINT chk_account_audit_receipt_versions + CHECK (schema_version > 0 AND payload_digest_version = 1), + CONSTRAINT chk_account_audit_receipt_digest + CHECK (payload_digest LIKE 'sha256:%' AND length(payload_digest) = 71), + CONSTRAINT chk_account_audit_receipt_terminal_state + CHECK ( + (status = 'COMMITTED' AND outcome IN ('ACCEPTED', 'DUPLICATE') AND payload IS NOT NULL) + OR (status = 'MINIMIZED' AND outcome = 'NON_REPLAYABLE' AND payload IS NULL) + ) +); + +CREATE UNIQUE INDEX uq_account_audit_receipt_identity + ON account_audit_receipts (scope, tenant_key, audit_event_id); + +CREATE INDEX idx_account_audit_receipts_tenant_event + ON account_audit_receipts (tenant_id, audit_event_id) + WHERE scope = 'tenant'; diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java new file mode 100644 index 0000000000..130443b4b4 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class LogEventServiceImplTest { + private static final String AUDIT_EVENT_ID = "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3"; + private static final UUID RECEIPT_ID = UUID.fromString("c0c1f03b-31b7-4281-aaf8-2d66f29e8770"); + + private final AccountAuditReceiptRepository repository = + Mockito.mock(AccountAuditReceiptRepository.class); + private final LogEventServiceImpl service = new LogEventServiceImpl(repository); + + @Test + void firstWriteReturnsCommittedAcceptedReceipt() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + AccountAuditReceipt receipt = + receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn(new AccountAuditReceiptInsertResult(receipt, true)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); + assertEquals(AccountAuditReceiptOutcome.ACCEPTED, result.outcome()); + assertEquals(91L, result.logEventId()); + verify(repository).insertIfAbsent(eq(request), any(UUID.class)); + } + + @Test + void exactRetryReturnsOriginalReceiptAsDuplicate() { + CreateLogEventRequest request = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); + AccountAuditReceipt receipt = + receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn(new AccountAuditReceiptInsertResult(receipt, false)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); + assertEquals(AccountAuditReceiptOutcome.DUPLICATE, result.outcome()); + assertEquals(42L, result.tenantId()); + } + + @Test + void changedImmutableMetadataReturnsIdempotencyConflict() { + CreateLogEventRequest original = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest changed = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH.plusSeconds(1), "{}"); + when(repository.insertIfAbsent(eq(changed), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), + false)); + + var result = service.createLogEvent(changed); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); + } + + @Test + void minimizedRetryIsSuccessfulButNonReplayable() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(request, null, "MINIMIZED", "NON_REPLAYABLE"), false)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.MINIMIZED, result.status()); + assertEquals(AccountAuditReceiptOutcome.NON_REPLAYABLE, result.outcome()); + } + + @Test + void missingReadbackThrowsForCanonicalNotFoundMapping() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + when(repository.findByIdentity(request, 0L)).thenReturn(Optional.empty()); + + assertThrows(AuditReceiptNotFoundException.class, () -> service.readLogEventReceipt(request)); + } + + @Test + void unsupportedDigestVersionFailsBeforeRepositoryAccess() { + CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest unsupported = + new CreateLogEventRequest( + valid.scope(), + valid.tenantId(), + valid.auditEventId(), + valid.producerService(), + valid.eventType(), + valid.occurredAt(), + valid.schemaVersion(), + valid.payload(), + 2, + valid.payloadDigest()); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(unsupported)); + verifyNoInteractions(repository); + } + + @Test + void payloadDigestMismatchFailsBeforeRepositoryAccess() { + CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest mismatched = + new CreateLogEventRequest( + valid.scope(), + valid.tenantId(), + valid.auditEventId(), + valid.producerService(), + valid.eventType(), + valid.occurredAt(), + valid.schemaVersion(), + valid.payload(), + valid.payloadDigestVersion(), + "sha256:" + "0".repeat(64)); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(mismatched)); + verifyNoInteractions(repository); + } + + @Test + void invalidUtf8PayloadFailsBeforeRepositoryAccess() { + ByteString payload = ByteString.copyFrom(new byte[] {(byte) 0xff}); + CreateLogEventRequest request = + new CreateLogEventRequest( + AccountAuditScope.PLATFORM, + null, + AUDIT_EVENT_ID, + "account-service", + "ACCOUNT_REGISTERED", + Instant.EPOCH, + 1, + payload, + 1, + digest(payload.toByteArray())); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(request)); + verifyNoInteractions(repository); + } + + private static CreateLogEventRequest request( + AccountAuditScope scope, Long tenantId, Instant occurredAt, String payloadText) { + ByteString payload = ByteString.copyFrom(payloadText, StandardCharsets.UTF_8); + return new CreateLogEventRequest( + scope, + tenantId, + AUDIT_EVENT_ID, + "account-service", + "ACCOUNT_REGISTERED", + occurredAt, + 1, + payload, + 1, + digest(payload.toByteArray())); + } + + private static AccountAuditReceipt receipt( + CreateLogEventRequest request, byte[] payload, String status, String outcome) { + return new AccountAuditReceipt( + 91L, + RECEIPT_ID, + request.scope().databaseValue(), + request.tenantId(), + request.auditEventId(), + request.producerService(), + request.eventType(), + request.occurredAt().getEpochSecond(), + request.occurredAt().getNano(), + request.schemaVersion(), + request.payloadDigestVersion(), + request.payloadDigest(), + payload, + status, + outcome); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 8a3df2b5fd..78732246a7 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -1,23 +1,49 @@ package net.firedevops.firemud.loggingadmin.service.impl; +import static org.assertj.core.api.Assertions.assertThat; 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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.protobuf.ProtoUtils; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.time.Instant; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; import net.firedevops.firemud.common.security.SessionContext; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; +import net.firedevops.firemud.loggingadmin.config.AccountAuditGrpcAuthConfiguration; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.loggingadmin.service.ModerationService; @@ -29,11 +55,16 @@ import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse; import net.firedevops.firemud.loggingadmin.v1.QueryLogsRequest; import net.firedevops.firemud.loggingadmin.v1.QueryLogsResponse; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; import net.firedevops.firemud.loggingadmin.v1.ToggleFeatureFlagRequest; import net.firedevops.firemud.loggingadmin.v1.ToggleFeatureFlagResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; class LoggingAdminGrpcServiceAuthTest { @AfterEach @@ -41,6 +72,38 @@ void tearDown() { SessionContext.clear(); } + @Test + void auditMethodsBypassJwtRequirementButOtherMethodsRemainProtected() { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withUserConfiguration(AccountAuditGrpcAuthConfiguration.class) + .withPropertyValues( + "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", + "firemud.auth.grpc.public-methods[0]=logging_admin.v1.LoggingAdminService/Ping") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + GrpcAuthProperties properties = context.getBean(GrpcAuthProperties.class); + assertThat(properties.getPublicMethods()) + .containsExactly("logging_admin.v1.LoggingAdminService/Ping"); + AuthTokenInterceptor interceptor = context.getBean(AuthTokenInterceptor.class); + assertTrue( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/CreateLogEvent")); + assertTrue( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt")); + assertTrue( + passesWithoutBearer(interceptor, "logging_admin.v1.LoggingAdminService/Ping")); + assertFalse( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/QueryLogs")); + }); + } + @Test void adminMethodsReturnPermissionDeniedErrorDetail() { SessionContext.setContext("1", List.of("player"), Map.of()); @@ -73,19 +136,23 @@ public void onCompleted() {} } @Test - void createLogEventUsesLogEventServiceWithoutCallingModeration() { - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + void accountMtlSPeerCreatesReceiptWithoutJwtOrAdminRole() { LogEventService logEventService = Mockito.mock(LogEventService.class); ModerationService moderationService = Mockito.mock(ModerationService.class); + String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); when(logEventService.createLogEvent(any())) .thenReturn( - new LogEventDto( + new AccountAuditReceiptDto( + AccountAuditScope.PLATFORM, + null, + "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", + "receipt-1", 77L, - 1L, - 42L, - "ACCOUNT_CREATED", - "account created", - Instant.parse("2026-01-01T00:00:00Z"))); + 1, + 1, + digest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.ACCEPTED)); LoggingAdminGrpcService service = new LoggingAdminGrpcService( Mockito.mock(LogQueryService.class), @@ -94,32 +161,125 @@ void createLogEventUsesLogEventServiceWithoutCallingModeration() { new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); - service.createLogEvent( - CreateLogEventRequest.newBuilder() - .setTenantId("1") - .setAccountId("42") - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(), - new StreamObserver<>() { - @Override - public void onNext(CreateLogEventResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + AtomicReference error = new AtomicReference<>(); + invokeWithPeer( + "account-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(ref, error))); assertNotNull(ref.get()); assertEquals("77", ref.get().getLogEventId()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM, + ref.get().getScope()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED, + ref.get().getStatus()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED, + ref.get().getOutcome()); + assertNull(error.get()); verify(logEventService).createLogEvent(any()); verify(moderationService, never()).applyAction(any()); } + @Test + void adminJwtClaimsDoNotAuthorizeAuditIngressWithoutAccountPeer() { + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + service.createLogEvent(validCreateRequest(), responseObserver(response, error)); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + + @Test + void jwtClaimNamingAccountServiceCannotOverrideWrongMtlsPeer() { + SessionContext.setContext(null, List.of(), Map.of(), true, "account-service", "instance-1"); + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "game-session-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + + @Test + void receiptReadReturnsCanonicalNotFoundStatus() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + when(logEventService.readLogEventReceipt(any())).thenThrow(new AuditReceiptNotFoundException()); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.NOT_FOUND, Status.fromThrowable(error.get()).getCode()); + assertNull(response.get()); + } + + @Test + void accountMtlSPeerCanReadTypedReceiptWithoutJwt() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); + when(logEventService.readLogEventReceipt(any())) + .thenReturn( + new AccountAuditReceiptDto( + AccountAuditScope.PLATFORM, + null, + "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", + "receipt-1", + 77L, + 1, + 1, + digest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.DUPLICATE)); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); + + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE, + response.get().getOutcome()); + assertNull(error.get()); + verify(logEventService).readLogEventReceipt(any()); + } + + @Test + void auditStorageFailureReturnsCanonicalUnavailableStatus() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + when(logEventService.createLogEvent(any())) + .thenThrow(new AuditStorageUnavailableException(new IllegalStateException("database"))); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); + assertNull(response.get()); + } + @Test void toggleFeatureFlagRejectsZeroTenantIdBeforeDispatch() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -259,41 +419,22 @@ public void onCompleted() {} } @Test - void createLogEventRejectsZeroAccountIdBeforeDispatch() { - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + void createLogEventMapsUnsupportedDigestVersionRejectionToInvalidArgument() { LogEventService logEventService = Mockito.mock(LogEventService.class); - LoggingAdminGrpcService service = - new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), - logEventService, - Mockito.mock(ModerationService.class), - new SimpleMeterRegistry()); + when(logEventService.createLogEvent(any())) + .thenThrow(new IllegalArgumentException("payloadDigestVersion must be 1")); + LoggingAdminGrpcService service = newService(logEventService); AtomicReference ref = new AtomicReference<>(); - service.createLogEvent( - CreateLogEventRequest.newBuilder() - .setTenantId("1") - .setAccountId("0") - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(), - new StreamObserver<>() { - @Override - public void onNext(CreateLogEventResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); - verifyNoInteractions(logEventService); + AtomicReference error = new AtomicReference<>(); + CreateLogEventRequest request = + validCreateRequest().toBuilder().setPayloadDigestVersion(2).build(); + invokeWithPeer( + "account-service", () -> service.createLogEvent(request, responseObserver(ref, error))); + + assertEquals(Status.Code.INVALID_ARGUMENT, Status.fromThrowable(error.get()).getCode()); + assertNull(ref.get()); + verify(logEventService).createLogEvent(argThat(dto -> dto.payloadDigestVersion() == 2)); } @Test @@ -640,4 +781,109 @@ public void onCompleted() {} assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); verifyNoInteractions(moderationService); } + + private static LoggingAdminGrpcService newService(LogEventService logEventService) { + return new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + logEventService, + Mockito.mock(ModerationService.class), + new SimpleMeterRegistry()); + } + + private static boolean passesWithoutBearer( + AuthTokenInterceptor interceptor, String fullMethodName) { + MethodDescriptor descriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(ProtoUtils.marshaller(CreateLogEventRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(CreateLogEventResponse.getDefaultInstance())) + .build(); + @SuppressWarnings("unchecked") + ServerCall serverCall = + (ServerCall) Mockito.mock(ServerCall.class); + when(serverCall.getMethodDescriptor()).thenReturn(descriptor); + AtomicReference callStarted = new AtomicReference<>(false); + ServerCallHandler next = + (call, headers) -> { + callStarted.set(true); + return new ServerCall.Listener<>() {}; + }; + + interceptor.interceptCall(serverCall, new Metadata(), next); + return callStarted.get(); + } + + private static StreamObserver responseObserver( + AtomicReference response, AtomicReference error) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable value) { + error.set(value); + } + + @Override + public void onCompleted() {} + }; + } + + private static void invokeWithPeer(String serviceName, Runnable invocation) { + String uri = "spiffe://firemud/ns/firemud/sa/" + serviceName; + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, "firemud", serviceName)); + Context previous = context.attach(); + try { + invocation.run(); + } finally { + context.detach(previous); + } + } + + private static CreateLogEventRequest validCreateRequest() { + ByteString payload = ByteString.copyFrom("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); + return CreateLogEventRequest.newBuilder() + .setScope( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM) + .setAuditEventId("d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3") + .setProducerService("account-service") + .setEventType("ACCOUNT_REGISTERED") + .setOccurredAt(Timestamp.newBuilder().setSeconds(1).setNanos(234567890)) + .setSchemaVersion(1) + .setPayload(payload) + .setPayloadDigestVersion(1) + .setPayloadDigest(digest(payload.toByteArray())) + .build(); + } + + private static ReadLogEventReceiptRequest validReadRequest() { + CreateLogEventRequest create = validCreateRequest(); + return ReadLogEventReceiptRequest.newBuilder() + .setScope(create.getScope()) + .setAuditEventId(create.getAuditEventId()) + .setProducerService(create.getProducerService()) + .setEventType(create.getEventType()) + .setOccurredAt(create.getOccurredAt()) + .setSchemaVersion(create.getSchemaVersion()) + .setPayload(create.getPayload()) + .setPayloadDigestVersion(create.getPayloadDigestVersion()) + .setPayloadDigest(create.getPayloadDigest()) + .build(); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } } From 7ae84af602468e0407e4ba751d78401c2a8e83ee Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 12:02:17 +1200 Subject: [PATCH 02/55] Persist JOIN intent before entitlement read and bind policy evidence --- .../account-service/api-contracts.md | 4 +- .../account-service/runtime-and-data.md | 6 +- .../system-architecture-authentication.md | 31 +- .../accountservice/dto/AccountJoinDigest.java | 39 +- .../AccountJoinOperationRepository.java | 159 +++++-- .../service/impl/AccountServiceImpl.java | 394 ++++++++++++------ ...V26__global_registration_join_evidence.sql | 47 ++- .../AccountRepositoryIntegrationTest.java | 194 +++++++++ .../dto/AccountJoinDigestTest.java | 51 ++- .../service/impl/AccountServiceImplTest.java | 253 +++++++++-- ...untRuntimeStubServerCompatibilityTest.java | 3 + .../test/AccountRuntimeStubServer.java | 125 +++++- 12 files changed, 1056 insertions(+), 250 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index aab82440b9..e2e6c740b1 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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`, including scope/caller validation, fresh public-join policy checks, version-1 policy-bound operation digest, membership transition, durable operation outcome, and tenant audit outbox evidence in the Account transaction. An operation retained as `PENDING` after an unknown database commit outcome still lacks the durable recovery/reconciliation behavior required by ADR 0025, and PostgreSQL runtime and direct text end-to-end proof remain open. The current runtime membership response remains the four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. 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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response remains the four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. 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. ### Current vs Target Export Lifecycle @@ -190,7 +190,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `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 four-field membership response, 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/bootstrap/join` | **Target facade; not currently routable.** The local internal `JoinPublicProductionMembership` operation is implemented for explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. The canonical digest contract is defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); Account verifies the stored scope and current public policy before its membership transaction. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A stale pair or digest returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Durable recovery for an operation left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision. | +| `POST` | `/auth/bootstrap/join` | **Target facade; not currently routable.** The local internal `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. 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. Durable PostgreSQL recovery and direct text end-to-end 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 | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 26866b52de..9749be12e6 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,7 +16,7 @@ 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 implemented locally as the only public-production membership writer: it validates an Account-issued connect scope and caller binding, rechecks current entitlement and `allowPublicJoin` policy at the commit gate, binds a version-1 digest to the verified caller/scope and policy evidence, then commits membership, operation outcome, and tenant-scoped audit outbox evidence in the Account transaction. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. The JOIN operation table persists `PENDING`, `COMMITTED`, and `FAILED`, but durable recovery/reconciliation of a `PENDING` operation after an unknown database commit outcome is unresolved under the Overseer decision and remains an open ADR 0025 obligation. The local focused tests and PostgreSQL integration test source do not establish PostgreSQL runtime proof; 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. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A changed policy digest on a still-pending operation returns `IDEMPOTENCY_CONFLICT` without replacing its bound evidence or terminalizing that operation. 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. No background PENDING-operation reconciler is claimed. 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. 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. @@ -28,7 +28,7 @@ The target realm-grant mutation boundary remains the Account API's tenant-admin Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; atomic single-use consumption and concurrent-reuse proof remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -The local direct-text `REALMS`-to-`JOIN` path issues a short-lived Account-owned scope for an authenticated caller and validates the retained target snapshot and caller binding at `JoinPublicProductionMembership`; Game Session supplies a server-generated join-attempt identity. This is local Account implementation status only: no direct text-client end-to-end proof is claimed, and the durable recovery/reconciliation behavior for an operation left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision and ADR 0025. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +The local direct-text `REALMS`-to-`JOIN` path issues a short-lived Account-owned scope for an authenticated caller and validates the retained target snapshot and caller binding at `JoinPublicProductionMembership`; Game Session supplies a server-generated join-attempt identity. A committed policy-independent intent survives entitlement outages and can be resumed by an exact request retry; when the second transaction outcome is uncertain, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -41,7 +41,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after Logging & Admin returns matching receipt evidence; failures leave it `PENDING` for retry. Logging & Admin locally implements durable receipt deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipts. These are local implementation facts, not PostgreSQL runtime or direct text end-to-end proof. Durable reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025; a terminal-looking database exception is not sufficient evidence to replay or report a membership transition. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after Logging & Admin returns matching receipt evidence; failures leave it `PENDING` for retry. Logging & Admin locally implements durable receipt deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipts. These are local implementation facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry resumes a pending intent; an absent terminal readback is reported as retryable unavailable, not as a membership result. No periodic pending-operation reconciler is claimed. - **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 230e954ca1..a58cfe4152 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -271,7 +271,28 @@ These modes are complementary: public browse remains available before authentica ``` The field names, `=`, line separators, and final newline are literal ASCII bytes. Values use the owning contract's canonical UTF-8 wire forms (including canonical decimal revisions and UTC RFC3339 timestamps), are not trimmed, case-folded, or Unicode-normalized, and may not contain `=` or a newline. `targetClass` is server-derived and not caller input. The bracket notation in the preimage illustration denotes conditional lines, not literal bytes: for `PUBLIC_PRODUCTION`, both lifecycle lines are omitted entirely, never encoded as empty, null, or sentinel values; for `NON_PUBLIC`, both are required, with a positive `playtestStateGeneration`. Account stores the digest with the scope record, including the immutable `evaluatedAt` value, and exact-compares it with the complete stored field set whenever the scope is consumed; a missing, extra, altered, or differently serialized field fails closed. This Account-owned scope-integrity evidence is distinct from the separately signed Gateway context and the JOIN idempotency digest. -- The canonical `JOIN` idempotency digest is `SHA-256` over the UTF-8 bytes of this exact newline-delimited preimage, including the final newline and preserving this field order: +- Before consulting entitlement authority, Account durably claims the stable `requestId` as `PENDING` with a policy-independent `joinIntentDigest/v1`. This immutable intent digest binds the request ID, authenticated account, verified caller binding, verified `connectScopeId` and scope snapshot digest, and the complete server-resolved target. It contains no entitlement availability, policy result, or entitlement version. The claim is committed before policy evaluation so an unavailable authority or an uncertain later transaction cannot erase evidence of the logical attempt. The intent digest is `SHA-256` over the UTF-8 bytes of the exact newline-delimited preimage below, including the final newline. Field names, `=`, separators, and the final newline are literal ASCII bytes; values use the canonical UTF-8 wire forms of the validated request and scope and may not contain `=` or a newline. A retry must match this intent exactly; a changed intent under the same request ID returns `IDEMPOTENCY_CONFLICT`. + + ```text + joinIntentDigestVersion=v1 + operationKind=JOIN + requestId= + accountId= + callerBinding= + connectScopeId= + scopeDigest= + tenantId= + worldSlug= + realmSlug= + realmId= + playableStateNamespaceId= + playableStateScope= + gameInstanceId= + catalogRevision= + pointerVersion= + ``` + + The canonical policy-bound `JOIN` request digest is `SHA-256` over the UTF-8 bytes of this exact newline-delimited preimage, including the final newline and preserving this field order. It is computed only after a fresh authoritative entitlement evaluation returns `AVAILABLE` with an exact `allowPublicJoin` result and positive `entitlementVersion`: ```text joinDigestVersion=v1 @@ -287,12 +308,12 @@ These modes are complementary: public browse remains available before authentica connectScopeId= catalogRevision= pointerVersion= - entitlementAuthorityAvailability= - [allowPublicJoin=] - [entitlementVersion=] + entitlementAuthorityAvailability=AVAILABLE + allowPublicJoin= + entitlementVersion= ``` - Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. Account calculates this unpublished pre-v1 `v1` digest only after establishing entitlement authority availability; when `AVAILABLE`, both policy lines are required and `allowPublicJoin` is lowercase `true` or `false` with a positive canonical decimal `entitlementVersion`. When authority is `UNAVAILABLE` or routing failed before policy evaluation (`NOT_EVALUATED`), both policy lines are omitted entirely, not filled with synthetic values. Account stores the digest version and exact availability/policy evidence with the `requestId`; an exact retry replays the stored outcome and a different digest returns `IDEMPOTENCY_CONFLICT`. No earlier JOIN digest was persisted, so no version-compatibility path is required. +- Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. `allowPublicJoin` is lowercase `true` or `false`; `entitlementVersion` is a positive canonical decimal. Account stores the intent digest/version before evaluation, then stores the request digest/version and exact policy evidence only after `AVAILABLE` authority has supplied both policy values. If entitlement authority is unavailable, Account records the attempt failure and availability while leaving the operation `PENDING`; it does not create a policy-bound request digest or invent a policy result/version. A retry with the same intent may reconcile that pending operation when authority is available. At the membership commit gate Account re-evaluates policy and requires the exact same digest and evidence; changed policy returns `IDEMPOTENCY_CONFLICT` without committing membership or its transition event. Exact retries replay the stored operation result after their required current-policy check. No earlier JOIN digest was persisted, so no version-compatibility path is required. - Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. Normative semantic split: diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java index 2e92c0105f..f205f4711d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java @@ -31,17 +31,10 @@ public static String scope(VerifiedJoinScope scope) { public static String request( VerifiedJoinScope scope, String callerBinding, - String entitlementAuthorityAvailability, Boolean allowPublicJoin, Long entitlementVersion) { - if (!"AVAILABLE".equals(entitlementAuthorityAvailability) - && !"UNAVAILABLE".equals(entitlementAuthorityAvailability) - && !"NOT_EVALUATED".equals(entitlementAuthorityAvailability)) { - throw new IllegalArgumentException("Entitlement authority availability is invalid"); - } - if ("AVAILABLE".equals(entitlementAuthorityAvailability) - != (allowPublicJoin != null && entitlementVersion != null && entitlementVersion > 0L)) { - throw new IllegalArgumentException("Policy evidence must match authority availability"); + if (allowPublicJoin == null || entitlementVersion == null || entitlementVersion <= 0L) { + throw new IllegalArgumentException("A JOIN policy digest requires exact available evidence"); } return hash( "joinDigestVersion=v1\n" @@ -57,11 +50,29 @@ public static String request( + field("connectScopeId", scope.connectScopeId()) + field("catalogRevision", scope.catalogRevision()) + field("pointerVersion", scope.pointerVersion()) - + field("entitlementAuthorityAvailability", entitlementAuthorityAvailability) - + ("AVAILABLE".equals(entitlementAuthorityAvailability) - ? field("allowPublicJoin", allowPublicJoin) - + field("entitlementVersion", entitlementVersion) - : "")); + + field("entitlementAuthorityAvailability", "AVAILABLE") + + field("allowPublicJoin", allowPublicJoin) + + field("entitlementVersion", entitlementVersion)); + } + + public static String intent(String requestId, VerifiedJoinScope scope, String callerBinding) { + return hash( + "joinIntentDigestVersion=v1\n" + + "operationKind=JOIN\n" + + field("requestId", requestId) + + field("accountId", scope.accountId()) + + field("callerBinding", callerBinding) + + field("connectScopeId", scope.connectScopeId()) + + field("scopeDigest", scope.snapshotDigest()) + + field("tenantId", scope.tenantId()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("realmId", scope.realmId()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion())); } public static String tokenHash(String connectScopeId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index 22fee20296..81886acf15 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -36,24 +36,14 @@ public void lockAccount(long accountId) { public Optional find(String requestId) { return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) - .fetchOptional( - row -> - new JoinOperation( - row.getAccountId(), - row.getTenantId(), - row.getVerifiedCallerBinding(), - row.getScopeTokenHash(), - row.getConnectScopeDigest(), - row.getEntitlementAuthorityAvailability(), - row.getAllowPublicJoin(), - row.getEntitlementVersion(), - row.getRequestDigestVersion(), - row.getRequestDigest(), - row.getStatus(), - row.getOutcome(), - row.getMembershipId(), - row.getOutcomeMembershipVersion(), - row.getOutcomeMembershipAuthorityGeneration())); + .fetchOptional(AccountJoinOperationRepository::toJoinOperation); + } + + public Optional findForUpdate(String requestId) { + return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) + .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) + .forUpdate() + .fetchOptional(AccountJoinOperationRepository::toJoinOperation); } public boolean hasRetainedOperation(long accountId) { @@ -61,15 +51,8 @@ public boolean hasRetainedOperation(long accountId) { ACCOUNT_JOIN_OPERATIONS, ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID.eq(accountId)); } - public boolean insertPending( - String requestId, - VerifiedJoinScope scope, - String callerBinding, - String requestDigest, - String entitlementAuthorityAvailability, - Long entitlementVersion, - Boolean allowPublicJoin, - boolean callerBoundAuthorityInvalidated) { + public boolean insertIntent( + String requestId, VerifiedJoinScope scope, String callerBinding, String intentDigest) { int inserted = dsl.insertInto(ACCOUNT_JOIN_OPERATIONS) .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID, requestId) @@ -91,16 +74,11 @@ public boolean insertPending( .set(ACCOUNT_JOIN_OPERATIONS.GAME_INSTANCE_ID, scope.gameInstanceId()) .set(ACCOUNT_JOIN_OPERATIONS.CATALOG_REVISION, scope.catalogRevision()) .set(ACCOUNT_JOIN_OPERATIONS.POINTER_VERSION, scope.pointerVersion()) - .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_VERSION, entitlementVersion) - .set(ACCOUNT_JOIN_OPERATIONS.ALLOW_PUBLIC_JOIN, allowPublicJoin) - .set( - ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, - entitlementAuthorityAvailability) - .set( - ACCOUNT_JOIN_OPERATIONS.CALLER_BOUND_AUTHORITY_INVALIDATED, - callerBoundAuthorityInvalidated) - .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST_VERSION, 1) - .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST, requestDigest) + .set(ACCOUNT_JOIN_OPERATIONS.INTENT_DIGEST_VERSION, 1) + .set(ACCOUNT_JOIN_OPERATIONS.INTENT_DIGEST, intentDigest) + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, "NOT_EVALUATED") + .set(ACCOUNT_JOIN_OPERATIONS.CALLER_BOUND_AUTHORITY_INVALIDATED, false) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, "NOT_EVALUATED") .set(ACCOUNT_JOIN_OPERATIONS.STATUS, "PENDING") .onConflict(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID) .doNothing() @@ -108,6 +86,63 @@ public boolean insertPending( return inserted == 1; } + public void bindPolicyEvidence( + String requestId, String requestDigest, Long entitlementVersion, Boolean allowPublicJoin) { + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, "AVAILABLE") + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_VERSION, entitlementVersion) + .set(ACCOUNT_JOIN_OPERATIONS.ALLOW_PUBLIC_JOIN, allowPublicJoin) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST_VERSION, 1) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST, requestDigest) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, "AVAILABLE") + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, (String) null) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING")) + .and(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull())) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed before policy binding"); + } + } + + public void recordAttemptFailure( + String requestId, String authorityAvailability, String failureCode) { + if (failureCode == null || failureCode.isBlank()) { + throw new IllegalArgumentException("JOIN attempt failure code is required"); + } + if (!"AVAILABLE".equals(authorityAvailability) + && !"UNAVAILABLE".equals(authorityAvailability) + && !"NOT_EVALUATED".equals(authorityAvailability)) { + throw new IllegalArgumentException("JOIN attempt authority availability is invalid"); + } + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set( + ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), authorityAvailability) + .otherwise(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY)) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, authorityAvailability) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, failureCode) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed while recording attempt failure"); + } + } + public void finish( String requestId, String status, @@ -118,15 +153,33 @@ public void finish( if (!"COMMITTED".equals(status) && !"FAILED".equals(status)) { throw new IllegalArgumentException("JOIN terminal status is invalid"); } + if (outcome == null || outcome.isBlank()) { + throw new IllegalArgumentException("JOIN terminal outcome is required"); + } int updated = dsl.update(ACCOUNT_JOIN_OPERATIONS) .set(ACCOUNT_JOIN_OPERATIONS.STATUS, status) .set(ACCOUNT_JOIN_OPERATIONS.OUTCOME, outcome) + .set( + ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), "NOT_EVALUATED") + .otherwise(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY)) + .set( + ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), "NOT_EVALUATED") + .otherwise(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY)) .set(ACCOUNT_JOIN_OPERATIONS.MEMBERSHIP_ID, membershipId) .set(ACCOUNT_JOIN_OPERATIONS.OUTCOME_MEMBERSHIP_VERSION, membershipVersion) .set( ACCOUNT_JOIN_OPERATIONS.OUTCOME_MEMBERSHIP_AUTHORITY_GENERATION, membershipAuthorityGeneration) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, (String) null) .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) .where( ACCOUNT_JOIN_OPERATIONS @@ -163,11 +216,39 @@ public record JoinOperation( String entitlementAuthorityAvailability, Boolean allowPublicJoin, Long entitlementVersion, - int requestDigestVersion, + Integer requestDigestVersion, String requestDigest, String status, String outcome, Long membershipId, Long membershipVersion, - Long membershipAuthorityGeneration) {} + Long membershipAuthorityGeneration, + int intentDigestVersion, + String intentDigest, + String lastAttemptFailureCode, + String lastAttemptAuthorityAvailability) {} + + private static JoinOperation toJoinOperation( + net.firedevops.firemud.accountservice.jooq.tables.records.AccountJoinOperationsRecord row) { + return new JoinOperation( + row.getAccountId(), + row.getTenantId(), + row.getVerifiedCallerBinding(), + row.getScopeTokenHash(), + row.getConnectScopeDigest(), + row.getEntitlementAuthorityAvailability(), + row.getAllowPublicJoin(), + row.getEntitlementVersion(), + row.getRequestDigestVersion(), + row.getRequestDigest(), + row.getStatus(), + row.getOutcome(), + row.getMembershipId(), + row.getOutcomeMembershipVersion(), + row.getOutcomeMembershipAuthorityGeneration(), + row.getIntentDigestVersion(), + row.getIntentDigest(), + row.getLastAttemptFailureCode(), + row.getLastAttemptAuthorityAvailability()); + } } 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 618989a4c0..0cf50e9c34 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 @@ -67,6 +67,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.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -93,9 +94,12 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.StringUtils; import org.springframework.web.server.ResponseStatusException; import tools.jackson.databind.json.JsonMapper; @@ -138,6 +142,7 @@ public class AccountServiceImpl implements AccountService { private final EntityManagementClient entityManagementClient; private final JwtUtil jwtUtil; private final net.firedevops.firemud.accountservice.service.session.SessionService sessionService; + private final TransactionTemplate joinTransactionTemplate; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -166,7 +171,8 @@ public AccountServiceImpl( GameSessionClient gameSessionClient, EntityManagementClient entityManagementClient, JwtUtil jwtUtil, - net.firedevops.firemud.accountservice.service.session.SessionService sessionService) { + net.firedevops.firemud.accountservice.service.session.SessionService sessionService, + PlatformTransactionManager transactionManager) { this.accountRepository = accountRepository; this.accountAuditOutboxRepository = accountAuditOutboxRepository; this.accountConnectScopeRepository = accountConnectScopeRepository; @@ -191,6 +197,9 @@ public AccountServiceImpl( this.entityManagementClient = entityManagementClient; this.jwtUtil = jwtUtil; this.sessionService = sessionService; + this.joinTransactionTemplate = new TransactionTemplate(transactionManager); + this.joinTransactionTemplate.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); } @Override @@ -431,7 +440,6 @@ public List listBootstrapCharacters( } @Override - @Transactional @Timed(value = "account.public_production_join") public JoinPublicProductionResult joinPublicProduction( String bootstrapToken, JoinPublicProductionRequest request) { @@ -492,7 +500,6 @@ public DirectTextJoinScope issueDirectTextConnectScope( } @Override - @Transactional @Timed(value = "account.public_production_join_internal") public JoinPublicProductionResult joinPublicProductionFromGameSession( DirectTextCallerContext caller, JoinPublicProductionRequest request) { @@ -519,151 +526,164 @@ private JoinPublicProductionResult joinPublicProductionForTrustedCaller( || !StringUtils.hasText(request.requestId())) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } - accountJoinOperationRepository.lockAccount(accountId); - Optional existing = - accountJoinOperationRepository.find(request.requestId()); + String requestId = request.requestId(); + String scopeTokenHash = AccountJoinDigest.tokenHash(request.connectScopeId()); + Optional existing = accountJoinOperationRepository.find(requestId); + VerifiedJoinScope retained; if (existing.isPresent()) { - var operation = existing.orElseThrow(); + JoinOperation operation = existing.orElseThrow(); if (operation.accountId() != accountId || !operation.callerBinding().equals(callerBinding) - || !operation - .scopeTokenHash() - .equals(AccountJoinDigest.tokenHash(request.connectScopeId()))) { + || !operation.scopeTokenHash().equals(scopeTokenHash)) { throw new AuthenticationException( "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); } - VerifiedJoinScope retained = - accountConnectScopeRepository - .find(request.connectScopeId()) + retained = retainedJoinScope(request.connectScopeId()); + validateDirectTextJoinScope(directTextCaller, retained); + requireMatchingJoinIntent(operation, requestId, callerBinding, retained); + } else { + ConnectScopeContext signedScope = requireConnectScopeContext(request.connectScopeId()); + retained = retainedJoinScope(request.connectScopeId()); + validateDirectTextJoinScope(directTextCaller, retained); + validateSignedJoinScope(signedScope, retained, accountId); + String intentDigest = AccountJoinDigest.intent(requestId, retained, callerBinding); + try { + joinTransactionTemplate.execute( + transactionStatus -> + accountJoinOperationRepository.insertIntent( + requestId, retained, callerBinding, intentDigest)); + } catch (RuntimeException ex) { + Optional claimReadback = safeFindJoinOperation(requestId); + if (claimReadback.isEmpty()) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN request claim is uncertain; retry the same request", ex); + } + requireMatchingJoinIntent(claimReadback.orElseThrow(), requestId, callerBinding, retained); + } + JoinOperation claimed = + accountJoinOperationRepository + .find(requestId) .orElseThrow( () -> new AuthenticationException( - "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); - validateDirectTextJoinScope(directTextCaller, retained); - JoinEvaluation evaluation = evaluateJoin(retained); - if ("NOT_EVALUATED".equals(evaluation.authorityAvailability()) - && !"NOT_EVALUATED".equals(operation.entitlementAuthorityAvailability())) { - throw new AuthenticationException( - evaluation.failureCode(), "Current JOIN authority could not be revalidated"); - } - if ("UNAVAILABLE".equals(evaluation.authorityAvailability()) - && "AVAILABLE".equals(operation.entitlementAuthorityAvailability())) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Current policy cannot be compared with retained JOIN evidence"); + "AUTH_UNAVAILABLE", "JOIN request claim is not yet readable")); + requireMatchingJoinIntent(claimed, requestId, callerBinding, retained); + } + + try { + return joinTransactionTemplate.execute( + transactionStatus -> executeJoinAttempt(accountId, callerBinding, requestId, retained)); + } catch (AuthenticationException ex) { + if ("IDEMPOTENCY_CONFLICT".equals(ex.getCode())) { + throw ex; } - String requestDigest = - AccountJoinDigest.request( - retained, - callerBinding, - evaluation.authorityAvailability(), - evaluation.allowPublicJoin(), - evaluation.entitlementVersion()); - if (!operation.connectScopeDigest().equals(retained.snapshotDigest()) - || operation.requestDigestVersion() != 1 - || !operation.requestDigest().equals(requestDigest)) { - throw new AuthenticationException("IDEMPOTENCY_CONFLICT", "JOIN request digest changed"); + recordJoinAttemptFailureAfterRollback(requestId, ex.getCode()); + return pendingJoinFailure(retained, ex.getCode()); + } catch (RuntimeException ex) { + Optional outcomeReadback = safeFindJoinOperation(requestId); + if (outcomeReadback.isPresent()) { + JoinOperation operation = outcomeReadback.orElseThrow(); + requireMatchingJoinIntent(operation, requestId, callerBinding, retained); + if (!"PENDING".equals(operation.status())) { + return resultFromJoinOperation(operation, true); + } + recordJoinAttemptFailureAfterRollback(requestId, "AUTH_UNAVAILABLE"); } - if ("PENDING".equals(operation.status())) { - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "JOIN outcome is pending reconciliation"); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN outcome is uncertain; retry the same request", ex); + } + } + + private JoinPublicProductionResult executeJoinAttempt( + long accountId, String callerBinding, String requestId, VerifiedJoinScope scope) { + accountJoinOperationRepository.lockAccount(accountId); + JoinOperation operation = + accountJoinOperationRepository + .findForUpdate(requestId) + .orElseThrow(() -> new IllegalStateException("JOIN request claim disappeared")); + requireMatchingJoinIntent(operation, requestId, callerBinding, scope); + + if (!"PENDING".equals(operation.status())) { + return replayJoinOperation(operation, callerBinding, scope); + } + + JoinEvaluation evaluation = evaluateJoin(scope); + if (evaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(evaluation)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, evaluation.authorityAvailability(), evaluation.failureCode()); + return pendingJoinFailure(scope, evaluation.failureCode()); } - return new JoinPublicProductionResult( - "COMMITTED".equals(operation.status()), - operation.outcome(), - operation.accountId(), - operation.tenantId(), - operation.membershipId() == null ? 0L : operation.membershipId(), - operation.membershipVersion() == null ? 0L : operation.membershipVersion(), - operation.membershipAuthorityGeneration() == null - ? 0L - : operation.membershipAuthorityGeneration(), - true); - } - ConnectScopeContext signedScope = requireConnectScopeContext(request.connectScopeId()); - VerifiedJoinScope retained = - accountConnectScopeRepository - .find(request.connectScopeId()) - .orElseThrow( - () -> - new AuthenticationException( - "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); - validateDirectTextJoinScope(directTextCaller, retained); - if (retained.accountId() != accountId - || signedScope.accountId() != accountId - || signedScope.tenantId() != retained.tenantId() - || signedScope.realmId() != retained.realmId() - || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) - || !signedScope.playableStateScope().equals(retained.playableStateScope()) - || signedScope.gameInstanceId() != retained.gameInstanceId() - || signedScope.catalogRevision() != retained.catalogRevision() - || signedScope.pointerVersion() != retained.pointerVersion() - || !signedScope.worldSlug().equals(retained.worldSlug()) - || !signedScope.realmSlug().equals(retained.realmSlug()) - || !signedScope.evaluatedAt().toString().equals(retained.evaluatedAt()) - || !signedScope - .connectScopeExpiresAt() - .toString() - .equals(retained.connectScopeExpiresAt())) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + return failedJoin(requestId, scope, evaluation.failureCode()); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability()) + || evaluation.allowPublicJoin() == null + || evaluation.entitlementVersion() == null) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, evaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); + return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); } - JoinEvaluation evaluation = evaluateJoin(signedScope); String requestDigest = AccountJoinDigest.request( - retained, - callerBinding, - evaluation.authorityAvailability(), - evaluation.allowPublicJoin(), - evaluation.entitlementVersion()); - boolean operationClaimed = - accountJoinOperationRepository.insertPending( - request.requestId(), - retained, - callerBinding, - requestDigest, - evaluation.authorityAvailability(), - evaluation.entitlementVersion(), - evaluation.allowPublicJoin(), - false); - if (!operationClaimed) { - throw new AuthenticationException( - "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); - } - if (evaluation.failureCode() != null) { - return failedJoin(request.requestId(), retained, evaluation.failureCode()); + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (operation.requestDigest() != null + && (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || !operation.requestDigest().equals(requestDigest))) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, "AVAILABLE", "IDEMPOTENCY_CONFLICT"); + return pendingJoinFailure(scope, "IDEMPOTENCY_CONFLICT"); + } + if (operation.requestDigest() == null) { + accountJoinOperationRepository.bindPolicyEvidence( + requestId, requestDigest, evaluation.entitlementVersion(), evaluation.allowPublicJoin()); } if (!evaluation.gameplayAvailable()) { - return failedJoin(request.requestId(), retained, "TENANT_BILLING_BLOCKED"); + return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); } if (!evaluation.allowPublicJoin()) { - return failedJoin(request.requestId(), retained, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); } - JoinEvaluation commitEvaluation = evaluateJoin(signedScope); + + JoinEvaluation commitEvaluation = evaluateJoin(scope); if (commitEvaluation.failureCode() != null) { - return failedJoin(request.requestId(), retained, commitEvaluation.failureCode()); + if (isRetryableJoinAuthorityFailure(commitEvaluation)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, commitEvaluation.authorityAvailability(), commitEvaluation.failureCode()); + return pendingJoinFailure(scope, commitEvaluation.failureCode()); + } + return failedJoin(requestId, scope, commitEvaluation.failureCode()); } - if (!"AVAILABLE".equals(commitEvaluation.authorityAvailability()) - || !java.util.Objects.equals( - evaluation.entitlementVersion(), commitEvaluation.entitlementVersion()) - || !java.util.Objects.equals( - evaluation.allowPublicJoin(), commitEvaluation.allowPublicJoin())) { - return failedJoin(request.requestId(), retained, "ENTITLEMENT_UNAVAILABLE"); + if (!"AVAILABLE".equals(commitEvaluation.authorityAvailability())) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, commitEvaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); + return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); + } + String commitDigest = + AccountJoinDigest.request( + scope, + callerBinding, + commitEvaluation.allowPublicJoin(), + commitEvaluation.entitlementVersion()); + if (!requestDigest.equals(commitDigest)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, "AVAILABLE", "IDEMPOTENCY_CONFLICT"); + return pendingJoinFailure(scope, "IDEMPOTENCY_CONFLICT"); } if (!commitEvaluation.gameplayAvailable()) { - return failedJoin(request.requestId(), retained, "TENANT_BILLING_BLOCKED"); + return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); } if (!commitEvaluation.allowPublicJoin()) { - return failedJoin(request.requestId(), retained, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); } AccountTenantMembership membership = accountTenantMembershipRepository - .findByAccountIdAndTenantId(accountId, retained.tenantId()) + .findByAccountIdAndTenantId(accountId, scope.tenantId()) .orElse(null); boolean transitioned = false; if (membership == null) { membership = new AccountTenantMembership(); membership.setAccount(requireAccount(accountId)); - membership.setTenantId(retained.tenantId()); + membership.setTenantId(scope.tenantId()); membership.setMembershipVersion(1L); membership.setMembershipAuthorityGeneration(1L); membership.setLifecycleState("ACTIVE"); @@ -672,7 +692,7 @@ private JoinPublicProductionResult joinPublicProductionForTrustedCaller( accountTenantMembershipRepository.save(membership); transitioned = true; } else if ("INACTIVE".equals(membership.getLifecycleState())) { - accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(request.requestId()); + accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); membership.setLifecycleState("ACTIVE"); membership.setGameplayAdmissionAllowed(true); membership.setMembershipVersion(membership.getMembershipVersion() + 1L); @@ -683,26 +703,26 @@ private JoinPublicProductionResult joinPublicProductionForTrustedCaller( transitioned = true; } else if (!"ACTIVE".equals(membership.getLifecycleState()) || !membership.isGameplayAdmissionAllowed()) { - return failedJoin(request.requestId(), retained, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); } if (transitioned) { String payload = AUDIT_JSON.writeValueAsString( new JoinAuditPayload( accountId, - retained.tenantId(), - retained.worldSlug(), - retained.realmSlug(), + scope.tenantId(), + scope.worldSlug(), + scope.realmSlug(), membership.getMembershipVersion(), - request.requestId())); + requestId)); UUID auditEventId = UUID.nameUUIDFromBytes( - ("account-join-audit/v1:" + request.requestId()).getBytes(StandardCharsets.UTF_8)); + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); accountAuditOutboxRepository.append( - auditEventId, "tenant", retained.tenantId(), "ACCOUNT_JOINED_PUBLIC_PRODUCTION", payload); + auditEventId, "tenant", scope.tenantId(), "ACCOUNT_JOINED_PUBLIC_PRODUCTION", payload); } accountJoinOperationRepository.finish( - request.requestId(), + requestId, "COMMITTED", transitioned ? "JOINED" : "ALREADY_ACTIVE", membership.getId(), @@ -712,7 +732,7 @@ private JoinPublicProductionResult joinPublicProductionForTrustedCaller( true, transitioned ? "JOINED" : "ALREADY_ACTIVE", accountId, - retained.tenantId(), + scope.tenantId(), membership.getId(), membership.getMembershipVersion(), membership.getMembershipAuthorityGeneration(), @@ -726,6 +746,132 @@ private JoinPublicProductionResult failedJoin( false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); } + private JoinPublicProductionResult pendingJoinFailure( + VerifiedJoinScope scope, String outcomeCode) { + return new JoinPublicProductionResult( + false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); + } + + private boolean isRetryableJoinAuthorityFailure(JoinEvaluation evaluation) { + return "UNAVAILABLE".equals(evaluation.authorityAvailability()) + || "ADMISSION_POINTER_UNAVAILABLE".equals(evaluation.failureCode()) + || "AUTH_UNAVAILABLE".equals(evaluation.failureCode()) + || "ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode()); + } + + private VerifiedJoinScope retainedJoinScope(String connectScopeId) { + return accountConnectScopeRepository + .find(connectScopeId) + .orElseThrow( + () -> + new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); + } + + private void validateSignedJoinScope( + ConnectScopeContext signedScope, VerifiedJoinScope retained, long accountId) { + if (retained.accountId() != accountId + || signedScope.accountId() != accountId + || signedScope.tenantId() != retained.tenantId() + || signedScope.realmId() != retained.realmId() + || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) + || !signedScope.playableStateScope().equals(retained.playableStateScope()) + || signedScope.gameInstanceId() != retained.gameInstanceId() + || signedScope.catalogRevision() != retained.catalogRevision() + || signedScope.pointerVersion() != retained.pointerVersion() + || !signedScope.worldSlug().equals(retained.worldSlug()) + || !signedScope.realmSlug().equals(retained.realmSlug()) + || !signedScope.evaluatedAt().toString().equals(retained.evaluatedAt()) + || !signedScope + .connectScopeExpiresAt() + .toString() + .equals(retained.connectScopeExpiresAt())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private void requireMatchingJoinIntent( + JoinOperation operation, String requestId, String callerBinding, VerifiedJoinScope scope) { + String expectedIntentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); + if (operation.accountId() != scope.accountId() + || !operation.callerBinding().equals(callerBinding) + || !operation.scopeTokenHash().equals(AccountJoinDigest.tokenHash(scope.connectScopeId())) + || !operation.connectScopeDigest().equals(scope.snapshotDigest()) + || operation.intentDigestVersion() != 1 + || !operation.intentDigest().equals(expectedIntentDigest)) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + } + + private JoinPublicProductionResult replayJoinOperation( + JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { + if (operation.requestDigest() != null) { + JoinEvaluation evaluation = evaluateJoin(scope); + if (evaluation.failureCode() != null) { + throw new AuthenticationException( + evaluation.failureCode(), "Current JOIN authority could not be revalidated"); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability())) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Current JOIN policy could not be revalidated"); + } + String currentDigest = + AccountJoinDigest.request( + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || !operation.requestDigest().equals(currentDigest)) { + throw new AuthenticationException("IDEMPOTENCY_CONFLICT", "JOIN request digest changed"); + } + } + return resultFromJoinOperation(operation, true); + } + + private JoinPublicProductionResult resultFromJoinOperation( + JoinOperation operation, boolean replayed) { + return new JoinPublicProductionResult( + "COMMITTED".equals(operation.status()), + operation.outcome(), + operation.accountId(), + operation.tenantId(), + operation.membershipId() == null ? 0L : operation.membershipId(), + operation.membershipVersion() == null ? 0L : operation.membershipVersion(), + operation.membershipAuthorityGeneration() == null + ? 0L + : operation.membershipAuthorityGeneration(), + replayed); + } + + private Optional safeFindJoinOperation(String requestId) { + try { + return accountJoinOperationRepository.find(requestId); + } catch (RuntimeException ignored) { + return Optional.empty(); + } + } + + private void recordJoinAttemptFailureAfterRollback(String requestId, String failureCode) { + String availability = + "ENTITLEMENT_UNAVAILABLE".equals(failureCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; + try { + joinTransactionTemplate.execute( + transactionStatus -> { + accountJoinOperationRepository + .findForUpdate(requestId) + .ifPresent( + operation -> { + if ("PENDING".equals(operation.status())) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, availability, failureCode); + } + }); + return null; + }); + } catch (RuntimeException ignored) { + // The durable intent stays pending, and the caller retries the same request ID. + } + } + private void validateDirectTextJoinScope( DirectTextCallerContext caller, VerifiedJoinScope scope) { if (caller != null diff --git a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql index 277dc970b7..46191a87b5 100644 --- a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql +++ b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql @@ -168,12 +168,16 @@ CREATE TABLE account_join_operations ( game_instance_id BIGINT NOT NULL, catalog_revision BIGINT NOT NULL, pointer_version BIGINT NOT NULL, + intent_digest_version INTEGER NOT NULL, + intent_digest VARCHAR(71) NOT NULL, entitlement_version BIGINT, allow_public_join BOOLEAN, - entitlement_authority_availability VARCHAR(16) NOT NULL, + entitlement_authority_availability VARCHAR(16) NOT NULL DEFAULT 'NOT_EVALUATED', caller_bound_authority_invalidated BOOLEAN NOT NULL, - request_digest_version INTEGER NOT NULL, - request_digest VARCHAR(71) NOT NULL, + request_digest_version INTEGER, + request_digest VARCHAR(71), + last_attempt_failure_code VARCHAR(64), + last_attempt_authority_availability VARCHAR(16) NOT NULL DEFAULT 'NOT_EVALUATED', status VARCHAR(16) NOT NULL, outcome VARCHAR(64), membership_id BIGINT REFERENCES account_tenant_membership(id), @@ -192,10 +196,41 @@ CREATE TABLE account_join_operations ( AND entitlement_version IS NOT NULL AND allow_public_join IS NOT NULL) OR (entitlement_authority_availability IN ('UNAVAILABLE', 'NOT_EVALUATED') AND entitlement_version IS NULL AND allow_public_join IS NULL)), - CONSTRAINT account_join_digest_version_check CHECK (request_digest_version = 1), + CONSTRAINT account_join_last_attempt_availability_check + CHECK (last_attempt_authority_availability IN ('AVAILABLE', 'UNAVAILABLE', 'NOT_EVALUATED')), + CONSTRAINT account_join_intent_digest_version_check + CHECK (intent_digest_version = 1 AND length(intent_digest) = 71 + AND intent_digest LIKE 'sha256:%'), + CONSTRAINT account_join_policy_digest_check + CHECK ((request_digest_version IS NULL AND request_digest IS NULL + AND entitlement_authority_availability <> 'AVAILABLE' + AND entitlement_version IS NULL AND allow_public_join IS NULL) + OR (request_digest_version = 1 AND request_digest IS NOT NULL + AND length(request_digest) = 71 AND request_digest LIKE 'sha256:%' + AND entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL AND allow_public_join IS NOT NULL)), + CONSTRAINT account_join_outcome_state_check + CHECK ((status = 'PENDING' AND outcome IS NULL + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'COMMITTED' AND outcome IS NOT NULL + AND membership_id IS NOT NULL + AND outcome_membership_version IS NOT NULL + AND outcome_membership_version > 0 + AND outcome_membership_authority_generation IS NOT NULL + AND outcome_membership_authority_generation > 0) + OR (status = 'FAILED' AND outcome IS NOT NULL + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL)), + CONSTRAINT account_join_pending_attempt_failure_check + CHECK (last_attempt_failure_code IS NULL + OR (status = 'PENDING' AND btrim(last_attempt_failure_code) <> '')), CONSTRAINT account_join_committed_policy_check - CHECK (status <> 'COMMITTED' OR (entitlement_version > 0 AND allow_public_join = TRUE - AND membership_id IS NOT NULL AND outcome_membership_version > 0 + CHECK (status <> 'COMMITTED' OR (entitlement_version IS NOT NULL + AND entitlement_version > 0 AND allow_public_join = TRUE + AND membership_id IS NOT NULL AND outcome_membership_version IS NOT NULL + AND outcome_membership_version > 0 + AND outcome_membership_authority_generation IS NOT NULL AND outcome_membership_authority_generation > 0)) ); 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 e158886d5b..f22a7e9192 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 @@ -5,8 +5,12 @@ import java.nio.file.Path; import java.util.Objects; +import java.util.UUID; +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.AccountLifecycleState; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; @@ -21,7 +25,11 @@ import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -63,9 +71,195 @@ void setUpRepository() { @BeforeEach void cleanTables() { + dsl.execute("TRUNCATE TABLE account_audit_outbox"); dsl.execute("TRUNCATE TABLE accounts RESTART IDENTITY CASCADE"); } + @Test + void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + DSLContext transactionAwareDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + AccountJoinOperationRepository joinOperations = + new AccountJoinOperationRepository(transactionAwareDsl); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository(transactionAwareDsl); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(transactionAwareDsl); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "two-phase-join", + "two-phase-join@example.com", + "hash")); + VerifiedJoinScope scope = joinScope(accountId); + String callerBinding = "bootstrap-jti-two-phase"; + String requestId = "join-two-phase-1"; + String intentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); + + transaction.executeWithoutResult( + status -> joinOperations.insertIntent(requestId, scope, callerBinding, intentDigest)); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("PENDING"); + assertThat(joinOperation(joinOperations, requestId).outcome()).isNull(); + assertThat(joinOperation(joinOperations, requestId).intentDigest()).isEqualTo(intentDigest); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isNull(); + assertThat(joinOperation(joinOperations, requestId).entitlementVersion()).isNull(); + assertThat(joinOperation(joinOperations, requestId).allowPublicJoin()).isNull(); + + String policyDigest = AccountJoinDigest.request(scope, callerBinding, true, 1L); + UUID auditEventId = UUID.randomUUID(); + Account account = new Account(); + account.setId(accountId); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> + commitJoinOutcome( + joinOperations, + memberships, + outbox, + account, + requestId, + scope, + policyDigest, + auditEventId, + true))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulate second-transaction rollback"); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("PENDING"); + assertThat(joinOperation(joinOperations, requestId).outcome()).isNull(); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isNull(); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + Long.class, + accountId, + scope.tenantId())) + .isZero(); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", + Long.class, + auditEventId)) + .isZero(); + + transaction.executeWithoutResult( + status -> + commitJoinOutcome( + joinOperations, + memberships, + outbox, + account, + requestId, + scope, + policyDigest, + auditEventId, + false)); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("COMMITTED"); + assertThat(joinOperation(joinOperations, requestId).outcome()).isEqualTo("JOINED"); + assertThat(joinOperation(joinOperations, requestId).intentDigest()).isEqualTo(intentDigest); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isEqualTo(policyDigest); + assertThat(joinOperation(joinOperations, requestId).entitlementVersion()).isEqualTo(1L); + assertThat(joinOperation(joinOperations, requestId).allowPublicJoin()).isEqualTo(true); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND authority_provenance = 'EXPLICIT_JOIN'", + Long.class, + accountId, + scope.tenantId())) + .isEqualTo(1L); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND delivery_status = 'PENDING'", + Long.class, + auditEventId)) + .isEqualTo(1L); + } + + private void commitJoinOutcome( + AccountJoinOperationRepository joinOperations, + AccountTenantMembershipRepository memberships, + AccountAuditOutboxRepository outbox, + Account account, + String requestId, + VerifiedJoinScope scope, + String policyDigest, + UUID auditEventId, + boolean simulateRollback) { + joinOperations.bindPolicyEvidence(requestId, policyDigest, 1L, true); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(scope.tenantId()); + membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + memberships.save(membership); + outbox.append( + auditEventId, + "tenant", + scope.tenantId(), + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + "{\"requestId\":\"" + requestId + "\"}"); + joinOperations.finish( + requestId, + "COMMITTED", + "JOINED", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + if (simulateRollback) { + throw new IllegalStateException("simulate second-transaction rollback"); + } + } + + private AccountJoinOperationRepository.JoinOperation joinOperation( + AccountJoinOperationRepository joinOperations, String requestId) { + return joinOperations.find(requestId).orElseThrow(); + } + + private static VerifiedJoinScope joinScope(long accountId) { + VerifiedJoinScope base = + new VerifiedJoinScope( + "two-phase-connect-scope", + accountId, + 7L, + 31L, + "demo", + "production", + "namespace-44", + "SHARED", + 44L, + 23L, + 17L, + "2026-09-24T10:00:00Z", + "2026-09-24T10:02:00Z", + "unused"); + String digest = AccountJoinDigest.scope(base); + return new VerifiedJoinScope( + base.connectScopeId(), + base.accountId(), + base.tenantId(), + base.realmId(), + base.worldSlug(), + base.realmSlug(), + base.playableStateNamespaceId(), + base.playableStateScope(), + base.gameInstanceId(), + base.catalogRevision(), + base.pointerVersion(), + base.evaluatedAt(), + base.connectScopeExpiresAt(), + digest); + } + @ParameterizedTest @EnumSource( value = AccountLifecycleState.class, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java index 4e47d83b37..a068abc0b7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java @@ -16,20 +16,26 @@ void scopeAndRequestDigestsMatchUtf8CanonicalVectors() { AccountJoinDigest.scope(scope)); assertEquals( "sha256:764b03cbe948293517acb4ce201dbd24fc4d2a0a2306e853f2ab0a6c3775a768", - AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 5L)); + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L)); assertNotEquals( - AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 5L), - AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", false, 5L)); + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope, "bootstrap-jti-α", false, 5L)); assertNotEquals( - AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 5L), - AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 6L)); + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 6L)); assertNotEquals( - AccountJoinDigest.request(scope, "bootstrap-jti-α", "AVAILABLE", true, 5L), - AccountJoinDigest.request( - scope("scope-token-α", "preview"), "bootstrap-jti-α", "AVAILABLE", true, 5L)); + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope("scope-token-α", "preview"), "bootstrap-jti-α", true, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(withGameInstance(scope, 45L), "bootstrap-jti-α", true, 5L)); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.request(scope, "bootstrap-jti-α", null, null)); + assertEquals( - "sha256:3450f964af0d11503e93a34d5178697de8c07c0eb7fe7e215d70de61a93f5a38", - AccountJoinDigest.request(scope, "bootstrap-jti-α", "UNAVAILABLE", null, null)); + "sha256:d6cfe1a2c241a63bdb0f5c381e18fddae1f00431da5f27cbfbf0f0a4b9748a3b", + AccountJoinDigest.intent("join-request-α", scope, "bootstrap-jti-α")); } @Test @@ -43,13 +49,28 @@ void canonicalSerializationRejectsAmbiguousValues() { assertThrows( IllegalArgumentException.class, () -> - AccountJoinDigest.request( - scope("scope-token", "production"), "bad=binding", "AVAILABLE", true, 1L)); + AccountJoinDigest.request(scope("scope-token", "production"), "bad=binding", true, 1L)); assertThrows( IllegalArgumentException.class, - () -> - AccountJoinDigest.request( - scope("scope-token", "production"), "caller", "AVAILABLE", true, null)); + () -> AccountJoinDigest.request(scope("scope-token", "production"), "caller", true, null)); + } + + private static VerifiedJoinScope withGameInstance(VerifiedJoinScope scope, long gameInstanceId) { + return new VerifiedJoinScope( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + gameInstanceId, + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.snapshotDigest()); } private static VerifiedJoinScope scope(String connectScopeId, String realmSlug) { 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 c2a90471ca..a77ba42633 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 @@ -73,6 +73,9 @@ import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; @@ -96,6 +99,7 @@ class AccountServiceImplTest { @Mock private PaymentTransactionRepository paymentTransactionRepository; @Mock private SubscriptionRepository subscriptionRepository; @Mock private ExternalAccountRepository externalAccountRepository; + @Mock private PlatformTransactionManager transactionManager; @Mock private EmailVerificationTokenRepository emailVerificationTokenRepository; @@ -108,6 +112,9 @@ class AccountServiceImplTest { @BeforeEach void setup() { MockitoAnnotations.openMocks(this); + when(transactionManager.getTransaction( + org.mockito.ArgumentMatchers.any(TransactionDefinition.class))) + .thenAnswer(invocation -> new SimpleTransactionStatus()); Subscription explicitActiveEntitlement = new Subscription(); explicitActiveEntitlement.setId(1L); explicitActiveEntitlement.setTenantId(7L); @@ -205,7 +212,8 @@ void setup() { gameSessionClient, entityManagementClient, jwtUtil, - sessionService); + sessionService, + transactionManager); } @Test @@ -416,11 +424,27 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou when(sessionService.isAccountSessionActive( org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) .thenReturn(true); + Subscription recovered = new Subscription(); + recovered.setId(22L); + recovered.setTenantId(7L); + recovered.setStatus("active"); + recovered.setEntitlementVersion(1L); when(subscriptionRepository.findByTenantIdForUpdate(7L)) .thenReturn( ambiguous ? java.util.List.of(new Subscription(), new Subscription()) - : java.util.List.of()); + : java.util.List.of(), + java.util.List.of(recovered), + java.util.List.of(recovered)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + return membership; + }); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); @@ -435,22 +459,38 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou JoinPublicProductionResult first = service.joinPublicProduction(bootstrap.bootstrapToken(), request); - JoinPublicProductionResult retry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertFalse(first.success()); assertEquals("ENTITLEMENT_UNAVAILABLE", first.outcomeCode()); - assertFalse(retry.success()); - assertTrue(retry.replayed()); - assertEquals(first.outcomeCode(), retry.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("UNAVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); + assertNotNull(retainedOperation.get().intentDigest()); + assertEquals(null, retainedOperation.get().requestDigest()); + assertEquals(null, retainedOperation.get().requestDigestVersion()); assertEquals(null, retainedOperation.get().allowPublicJoin()); assertEquals(null, retainedOperation.get().entitlementVersion()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + + JoinPublicProductionResult retriedAfterRecovery = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertTrue(retriedAfterRecovery.success()); + assertEquals("JOINED", retriedAfterRecovery.outcomeCode()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertNotNull(retainedOperation.get().requestDigest()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-unavailable-1")); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) .findByTenantIdForUpdate(7L); } @@ -495,8 +535,11 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { new JoinPublicProductionRequest(connectScopeId, "join-race-1")); assertFalse(result.success()); - assertEquals("ENTITLEMENT_UNAVAILABLE", result.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", result.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().lastAttemptFailureCode()); + assertNotNull(retainedOperation.get().requestDigest()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); @@ -504,6 +547,52 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { .findByTenantIdForUpdate(7L); } + @Test + void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenThrow(new IllegalStateException("entitlement storage unavailable")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1"))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertNotNull(retainedOperation.get().intentDigest()); + assertEquals(null, retainedOperation.get().requestDigest()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) + .commit(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) + .rollback(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + @Test void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { Account account = new Account(); @@ -524,17 +613,29 @@ void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { retainJoinEvidence(retainedScope, retainedOperation); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - org.mockito.Mockito.when( - accountJoinOperationRepository.insertPending( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Boolean.class), - org.mockito.ArgumentMatchers.anyBoolean())) - .thenReturn(false); + VerifiedJoinScope scope = retainedScope.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + 12L, + scope.tenantId(), + "different-caller", + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + scope.snapshotDigest(), + "NOT_EVALUATED", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + "join-global-collision-1", scope, "different-caller"), + null, + "NOT_EVALUATED")); AuthenticationException conflict = assertThrows( @@ -609,15 +710,14 @@ private void retainJoinEvidence( .thenAnswer(invocation -> Optional.ofNullable(retainedScope.get())); when(accountJoinOperationRepository.find(org.mockito.ArgumentMatchers.anyString())) .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + when(accountJoinOperationRepository.findForUpdate(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); org.mockito.Mockito.doAnswer( invocation -> { String requestId = invocation.getArgument(0); VerifiedJoinScope scope = invocation.getArgument(1); String callerBinding = invocation.getArgument(2); - String requestDigest = invocation.getArgument(3); - String authorityAvailability = invocation.getArgument(4); - Long entitlementVersion = invocation.getArgument(5); - Boolean allowPublicJoin = invocation.getArgument(6); + String intentDigest = invocation.getArgument(3); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( scope.accountId(), @@ -626,28 +726,94 @@ private void retainJoinEvidence( net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( scope.connectScopeId()), scope.snapshotDigest(), - authorityAvailability, - allowPublicJoin, - entitlementVersion, - 1, - requestDigest, + "NOT_EVALUATED", + null, + null, + null, + null, "PENDING", null, null, null, - null)); + null, + 1, + intentDigest, + null, + "NOT_EVALUATED")); return true; }) .when(accountJoinOperationRepository) - .insertPending( + .insertIntent( org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + "AVAILABLE", + invocation.getArgument(3), + invocation.getArgument(2), + 1, + invocation.getArgument(1), + pending.status(), + pending.outcome(), + pending.membershipId(), + pending.membershipVersion(), + pending.membershipAuthorityGeneration(), + pending.intentDigestVersion(), + pending.intentDigest(), + null, + "AVAILABLE")); + return null; + }) + .when(accountJoinOperationRepository) + .bindPolicyEvidence( org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Boolean.class), + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + String availability = invocation.getArgument(1); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.requestDigest() == null + ? availability + : pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + pending.status(), + pending.outcome(), + pending.membershipId(), + pending.membershipVersion(), + pending.membershipAuthorityGeneration(), + pending.intentDigestVersion(), + pending.intentDigest(), + invocation.getArgument(2), + availability)); + return null; + }) + .when(accountJoinOperationRepository) + .recordAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); org.mockito.Mockito.doAnswer( invocation -> { var pending = retainedOperation.get(); @@ -667,7 +833,11 @@ private void retainJoinEvidence( invocation.getArgument(2), invocation.getArgument(3), invocation.getArgument(4), - invocation.getArgument(5))); + invocation.getArgument(5), + pending.intentDigestVersion(), + pending.intentDigest(), + null, + pending.lastAttemptAuthorityAvailability())); return null; }) .when(accountJoinOperationRepository) @@ -1168,7 +1338,8 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { gameSessionClient, entityManagementClient, jwtUtil, - sessionService); + sessionService, + transactionManager); IllegalStateException ex = assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("boom-token")); diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 30a088e01d..a9c826f671 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -37,5 +37,8 @@ void accountServiceMethodSetIsFullyCategorized() { AccountRuntimeStubServer.implementedRuntimeMethodNames().stream(), NON_RUNTIME_METHODS.stream()) .collect(java.util.stream.Collectors.toSet())); + + assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) + .contains("IssueDirectTextConnectScope", "JoinPublicProductionMembership"); } } 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 06a325ea23..5fdff55e61 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 @@ -4,6 +4,7 @@ import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Set; @@ -22,12 +23,18 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.PingRequest; import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.account.AccountProfileJson; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; /** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase @@ -39,7 +46,9 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe "Authenticate", "GetTenantMembershipForRuntime", "GetRealmAccessGrantForRuntime", - "GetTenantEntitlementsForRuntime"); + "GetTenantEntitlementsForRuntime", + "IssueDirectTextConnectScope", + "JoinPublicProductionMembership"); private final Server server; private final List authenticateRequests = new CopyOnWriteArrayList<>(); @@ -49,8 +58,10 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final AtomicBoolean allowPublicJoin = new AtomicBoolean(true); private final AtomicBoolean realmAccessGranted = new AtomicBoolean(true); private final AtomicLong defaultAccountId = new AtomicLong(1L); + private final AtomicLong nextConnectScopeId = new AtomicLong(1L); private final Map accountIdsByEmail = new ConcurrentHashMap<>(); private final Map profilesByAccountId = new ConcurrentHashMap<>(); + private final Map connectScopesById = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { this.server = NettyServerBuilder.forPort(port).addService(this).build().start(); @@ -198,6 +209,109 @@ public void getTenantEntitlementsForRuntime( responseObserver.onCompleted(); } + @Override + public void issueDirectTextConnectScope( + IssueDirectTextConnectScopeRequest request, + StreamObserver responseObserver) { + PlayerExecutionContext caller = request.getPlayerContext(); + if (caller.getAccountId().isBlank() + || caller.getTenantId().isBlank() + || caller.getRealmId().isBlank() + || caller.getGameInstanceId().isBlank() + || caller.getPlayableStateNamespaceId().isBlank() + || caller.getPlayableStateScope().isBlank() + || request.getTenantId().isBlank() + || request.getRealmId().isBlank() + || request.getGameInstanceId().isBlank() + || request.getWorldSlug().isBlank() + || request.getRealmSlug().isBlank() + || request.getPlayableStateNamespaceId().isBlank() + || request.getPlayableStateScope().isBlank() + || !caller.getTenantId().equals(request.getTenantId()) + || !caller.getRealmId().equals(request.getRealmId()) + || !caller.getGameInstanceId().equals(request.getGameInstanceId()) + || !caller.getPlayableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) + || !caller.getPlayableStateScope().equals(request.getPlayableStateScope())) { + responseObserver.onNext( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage("Direct-text connect scope request is incomplete")) + .build()); + } else { + String scopeId = "stub-connect-scope-" + nextConnectScopeId.getAndIncrement(); + Instant expiresAt = Instant.now().plusSeconds(300); + connectScopesById.put( + scopeId, + new StubConnectScope( + caller.getAccountId(), + request.getTenantId(), + request.getRealmId(), + request.getGameInstanceId(), + request.getPlayableStateNamespaceId(), + request.getPlayableStateScope(), + expiresAt)); + responseObserver.onNext( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(scopeId) + .setConnectScopeExpiresAt(expiresAt.toString()) + .build()); + } + responseObserver.onCompleted(); + } + + @Override + public void joinPublicProductionMembership( + JoinPublicProductionMembershipRequest request, + StreamObserver responseObserver) { + PlayerExecutionContext caller = request.getPlayerContext(); + StubConnectScope scope = connectScopesById.get(request.getConnectScopeId()); + if (request.getConnectScopeId().isBlank() + || request.getRequestId().isBlank() + || !request.getRequestId().equals(caller.getRequestId()) + || caller.getAccountId().isBlank() + || caller.getTenantId().isBlank() + || scope == null + || !scope.expiresAt().isAfter(Instant.now()) + || !scope.accountId().equals(caller.getAccountId()) + || !scope.tenantId().equals(caller.getTenantId()) + || !scope.realmId().equals(caller.getRealmId()) + || !scope.gameInstanceId().equals(caller.getGameInstanceId()) + || !scope.playableStateNamespaceId().equals(caller.getPlayableStateNamespaceId()) + || !scope.playableStateScope().equals(caller.getPlayableStateScope())) { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage("Direct-text JOIN request is incomplete")) + .build()); + } else if (!allowPublicJoin.get()) { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .build()); + } else { + membershipExists.set(true); + gameplayAdmissionAllowed.set(true); + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .setMembershipId( + "stub-membership-" + caller.getAccountId() + "-" + caller.getTenantId()) + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .build()); + } + responseObserver.onCompleted(); + } + @Override public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { @@ -262,4 +376,13 @@ private StubProfile withPresenceVisibilityPolicy(String visibilityPolicy) { visibilityPolicy == null ? DEFAULT_VISIBILITY_POLICY : visibilityPolicy); } } + + private record StubConnectScope( + String accountId, + String tenantId, + String realmId, + String gameInstanceId, + String playableStateNamespaceId, + String playableStateScope, + Instant expiresAt) {} } From 74de8f22df5ef553f26d8c5183890b4fd23eca2f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 12:04:11 +1200 Subject: [PATCH 03/55] Bind Account audit receipts to scoped log projections and peer identity --- .../logging-admin-service/api-contracts.md | 4 +- .../logging-admin-service/runtime-and-data.md | 2 +- ...hared-runtime-contracts-and-persistence.md | 2 +- k8s/base/logging-admin-service.yaml | 4 + k8s/helm/firemud/templates/apps.yaml | 2 +- .../entity/AccountAuditReceipt.java | 1 + .../AccountAuditReceiptRepository.java | 42 ++++ .../repository/LogEventRepository.java | 15 +- .../service/impl/LogEventServiceImpl.java | 2 +- .../service/impl/LoggingAdminGrpcService.java | 25 ++- .../migration/V2__account_audit_receipts.sql | 25 +++ ...oggingAdminApplicationIntegrationTest.java | 196 ++++++++++++++++++ .../service/impl/LogEventServiceImplTest.java | 24 ++- .../impl/LoggingAdminGrpcServiceAuthTest.java | 32 ++- 14 files changed, 356 insertions(+), 20 deletions(-) diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 9860a6516d..412f90e9f6 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -8,7 +8,9 @@ The canonical Account-to-Logging & Admin audit ingress is the existing `logging_ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenantId` only for `tenant` scope and never for `platform` scope, stable `auditEventId` generated and persisted by Account, `producerService`, `eventType`, producer `occurredAt`, positive `schemaVersion`, exact UTF-8 `payload`, `payloadDigestVersion` exactly `1` until a later canonical digest-version registry is accepted, and `payloadDigest`. Global registration, `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity events use `platform` scope with no `tenantId`; tenant profile and JOIN events use `tenant` scope with the exact committed `tenantId`. Unsupported digest versions fail before deduplication or persistence. `producerService` is derived from the authenticated Account workload identity and a mismatching request value is rejected. An upstream producer domain-event digest, when present inside `payload`, remains opaque payload evidence and is distinct from the receiver's `payloadDigest`. `payloadDigest` is `sha256:` followed by 64 lowercase hexadecimal characters over the exact UTF-8 payload bytes under `payloadDigestVersion=1`; no JSON reserialization or alternate canonicalization is permitted. Retry equivalence is the complete immutable `(scope, tenantId-if-tenant, auditEventId, producerService, eventType, occurredAt, schemaVersion, payloadDigestVersion, payloadDigest, exact payload bytes)` tuple: while exact payload bytes remain retained, an exact match returns the original receipt, while any changed field or payload bytes fails closed as `IDEMPOTENCY_CONFLICT`. After the safe watermark permits payload minimization, the retained identity and metadata may still detect a changed non-payload field, but the receiver must not claim exact payload equality or replay; a matching late request is a terminal non-replayable result. Timeout, transport failure, or an ambiguous response is not success; the producer retries or reconciles with the same identity and digest and never mints a replacement event. -`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. **Current local implementation:** the Account audit request/response schema, Account workload check, exact payload digest validation, durable receipt insert/deduplication, bounded receipt readback, and accepted/duplicate/conflict/minimized outcomes are implemented locally. Account registration and JOIN now produce owner-local outbox entries; Account's delivery client checks returned receipt evidence before marking delivery complete. Focused local unit coverage exists, but PostgreSQL runtime proof and direct text-client-to-Logging end-to-end proof are not claimed. The target contract remains authoritative for full retention/readback horizons and any unresolved runtime edge cases. +Each accepted Account audit request commits one `log_events` audit projection in the same PostgreSQL transaction as its durable receipt. `logEventId` is the projection's `log_events.id`, distinct from `receiptId` and the receipt row's database key. The projection is deliberately a bounded identity summary: `type` is the fixed value `ACCOUNT_AUDIT`, `message` is `Account audit event` followed by one ASCII space and `auditEventId`, and `timestamp`, `scope`, and `tenantId` come from the envelope. `account_id` remains unset because the envelope has no typed account-principal field. The exact payload and `eventType` remain in the receipt and are not copied into this projection, so payload minimization does not leave a second permanent payload copy. Platform projections retain `scope=platform` and `tenantId=NULL`; tenant projections retain `scope=tenant` and the exact positive `tenantId`. `QueryLogs` remains tenant-only and excludes platform rows; it can locate a projected audit event by its `auditEventId`, but this contract does not define or imply a platform query route. A scope-qualified `(scope, tenantId-or-zero, auditEventId)` uniqueness boundary ensures an exact retry returns the original receipt and projection IDs, while a changed tuple conflicts without another projection. + +`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. **Current local implementation:** the Account audit request/response schema, Account workload check, exact payload digest validation, atomic scope-aware log projection and durable receipt insert/deduplication, bounded receipt readback, and accepted/duplicate/conflict/minimized outcomes are implemented locally. Account registration and JOIN now produce owner-local outbox entries; Account's delivery client checks returned receipt evidence before marking delivery complete. Focused local unit coverage exists, but PostgreSQL runtime proof and direct text-client-to-Logging end-to-end proof are not claimed. The target contract remains authoritative for full retention/readback horizons and any unresolved runtime edge cases. The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index f58464631b..c5a123e1e5 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -113,7 +113,7 @@ For plugin operations, Automation remains the activation/lifecycle owner and Gam ## Data Model -- `log_events` is the current service-owned PostgreSQL domain table. `LogQueryServiceImpl` queries it by exact `tenantId` and case-insensitive message containment and returns only stored messages. No current implementation mirrors this table into Elasticsearch or proves the profile-aware emitter-to-query path; selected-profile indexed, compatible-backend, or console/journal querying remains target-state under [Logging & Monitoring](../../system-architecture-logging-monitoring.md#log-pipeline-queryability-contract). +- `log_events` is the current service-owned PostgreSQL domain table and also holds the Account audit projection defined in [Account Audit Ingress and Receipt](./api-contracts.md#account-audit-ingress-and-receipt). Audit projections retain explicit `platform` or `tenant` scope; platform rows have no `tenantId` and are excluded from tenant queries. `LogQueryServiceImpl` queries tenant-scope rows by exact `tenantId` and case-insensitive message containment and returns only stored messages. No current implementation mirrors this table into Elasticsearch or proves the profile-aware emitter-to-query path; selected-profile indexed, compatible-backend, or console/journal querying remains target-state under [Logging & Monitoring](../../system-architecture-logging-monitoring.md#log-pipeline-queryability-contract). - `moderation_actions` is the target durable record for accepted moderation policy intent and audit evidence, with the fixed category, normalized explicit scope, actor/case/source request, safe notice/reason, local intent-reference redemption outcome, separate owner command/result linkage when a later enforcement command exists, and the idempotency identity, digest, and timestamps. A linked owner-result revision is recorded only when that result supplies it; the local policy-intent commit never synthesizes owner revision or enforcement epoch. Raw authorization references are never persisted. The legacy `POST /moderation/actions` and `ApplyModerationAction` transport stubs now hard fail closed after narrow checks without persisting their generic legacy row; they are unsupported/nonconformant and not target fixed-category proof. Owner restriction tables and owner-command redemption are separate; Logging & Admin does not mutate them. - `moderation_appeal_cases` and bounded `moderation_appeal_evidence_refs` are target Logging & Admin records for the `SUBMITTED -> UNDER_REVIEW -> DECIDED` lifecycle, exact appealed owner revision/digest, jurisdiction, eligibility policy, safe submission/decision, bounded evidence references, retention/legal-hold/export state, and resulting owner command identity. No complete appeal table or workflow is currently implemented. - `player_reports` is the target durable store for abuse and bug reports accepted through the report-persistence seam, including tenant scope in its `tenant_id` column. Current report persistence is unavailable: both the internal `CreateReport` ingress and the service-layer mutation fail closed before any repository save, and public administrative and target caller-bound external/player submission remain unavailable. 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 4cfb0318f1..d230b522e3 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 @@ -117,7 +117,7 @@ The [gRPC outcome and transport classification](../../architecture/system-archit ### Audit, Moderation, and Authority Boundaries -Logging & Admin exposes dedicated non-destructive `CreateLogEvent` ingress, but account-creation audit delivery remains partial: it is still a post-commit best-effort effect rather than the target owner-local outbox and receiver contract. The normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt); see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for the producer's current implementation, proof, and gap status. Account logging for payment uses the existing RPC and `LogEvent` persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. Focused tests prove the current log-event behavior and the absence of destructive account/session effects. +Logging & Admin exposes dedicated non-destructive `CreateLogEvent` ingress. Global registration and explicit JOIN now append Account-owned audit outbox entries in their local transactions, and Logging & Admin retains receipt/deduplication evidence; delivery and readback are still partial until the audit projection, uncertain-commit reconciliation, and PostgreSQL/end-to-end proof are complete. The normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt); see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for the producer's current implementation, proof, and gap status. Account logging for payment uses the existing RPC and `LogEvent` persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. Focused tests prove the current log-event behavior and the absence of destructive account/session effects. Current status only: Logging & Admin exposes the non-destructive `EvaluateModerationPolicy` read and a gated/unavailable moderation-action seam; current focused proof is partial and covers bounded read, denied, and validation paths only. It does not cover target mutation or appeal workflows, or focused `CHAT_SEND` stale/unavailable dependency and owner-read failure cases. The remaining implementation and proof gaps are tracked against [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md) and [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md). diff --git a/k8s/base/logging-admin-service.yaml b/k8s/base/logging-admin-service.yaml index 1bd8c367a1..0f0651ee7c 100644 --- a/k8s/base/logging-admin-service.yaml +++ b/k8s/base/logging-admin-service.yaml @@ -30,6 +30,10 @@ spec: value: /tls/client.key - name: FIREMUD_GRPC_CA_CERT_PATH value: /tls/ca.crt + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace envFrom: - configMapRef: name: firemud-config diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index ff8bd43a1a..2c130ea7e7 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -177,7 +177,7 @@ spec: {{- if $service.springProfile }} - name: SPRING_PROFILES_ACTIVE value: "prod" - {{- if has $service.name (include "firemud.grpcWorkloadNames" $ | fromJsonArray) }} + {{- if or (has $service.name (include "firemud.grpcWorkloadNames" $ | fromJsonArray)) (eq $service.name "logging-admin-service") }} - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE valueFrom: fieldRef: diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java index 9e04277e29..2d3eeeb6c7 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java @@ -5,6 +5,7 @@ /** A durable receiver-side audit envelope and its readback receipt. */ public record AccountAuditReceipt( long id, + long logEventId, UUID receiptId, String scope, Long tenantId, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java index bcaffd3767..ef646e3987 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.loggingadmin.repository; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; +import static net.firedevops.firemud.loggingadmin.jooq.tables.LogEvents.LOG_EVENTS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Optional; @@ -18,6 +20,9 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountAuditReceiptRepository { + private static final String ACCOUNT_AUDIT_PROJECTION_TYPE = "ACCOUNT_AUDIT"; + private static final String ACCOUNT_AUDIT_PROJECTION_MESSAGE_PREFIX = "Account audit event "; + private final DSLContext dsl; public AccountAuditReceiptRepository(DSLContext dsl) { @@ -27,8 +32,10 @@ public AccountAuditReceiptRepository(DSLContext dsl) { public AccountAuditReceiptInsertResult insertIfAbsent( CreateLogEventRequest request, UUID receiptId) { long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); + long logEventId = insertOrFindProjection(request); int inserted = dsl.insertInto(ACCOUNT_AUDIT_RECEIPTS) + .set(ACCOUNT_AUDIT_RECEIPTS.LOG_EVENT_ID, logEventId) .set(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID, receiptId) .set(ACCOUNT_AUDIT_RECEIPTS.SCOPE, request.scope().databaseValue()) .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_ID, request.tenantId()) @@ -55,6 +62,40 @@ public AccountAuditReceiptInsertResult insertIfAbsent( return new AccountAuditReceiptInsertResult(receipt, inserted == 1); } + private long insertOrFindProjection(CreateLogEventRequest request) { + Long tenantKey = request.tenantId() == null ? Long.valueOf(0L) : request.tenantId(); + dsl.insertInto(LOG_EVENTS) + .set(LOG_EVENTS.SCOPE, request.scope().databaseValue()) + .set(LOG_EVENTS.TENANT_ID, request.tenantId()) + .set(LOG_EVENTS.TENANT_KEY, tenantKey) + .set(LOG_EVENTS.AUDIT_EVENT_ID, request.auditEventId()) + .set(LOG_EVENTS.TYPE, ACCOUNT_AUDIT_PROJECTION_TYPE) + .set(LOG_EVENTS.MESSAGE, ACCOUNT_AUDIT_PROJECTION_MESSAGE_PREFIX + request.auditEventId()) + .set(LOG_EVENTS.TIMESTAMP, toLocalDateTime(request.occurredAt())) + .set(LOG_EVENTS.ACCOUNT_ID, (Long) null) + .onConflictDoNothing() + .execute(); + + var tenantCondition = + request.tenantId() == null + ? LOG_EVENTS.TENANT_ID.isNull() + : LOG_EVENTS.TENANT_ID.eq(request.tenantId()); + Long logEventId = + dsl.select(LOG_EVENTS.ID) + .from(LOG_EVENTS) + .where( + LOG_EVENTS + .SCOPE + .eq(request.scope().databaseValue()) + .and(tenantCondition) + .and(LOG_EVENTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) + .fetchOne(LOG_EVENTS.ID); + if (logEventId == null) { + throw new IllegalStateException("Account audit projection identity did not resolve"); + } + return logEventId; + } + public Optional findByIdentity( CreateLogEventRequest request, long tenantKey) { return dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) @@ -71,6 +112,7 @@ private AccountAuditReceipt toEntity(Record record) { AccountAuditReceiptsRecord receiptRecord = (AccountAuditReceiptsRecord) record; return new AccountAuditReceipt( receiptRecord.getId(), + receiptRecord.getLogEventId(), receiptRecord.getReceiptId(), receiptRecord.getScope(), receiptRecord.getTenantId(), diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java index 0abd0a35c2..3554945a10 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java @@ -7,6 +7,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import java.util.Optional; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; import net.firedevops.firemud.loggingadmin.entity.LogEvent; import net.firedevops.firemud.loggingadmin.jooq.tables.records.LogEventsRecord; import org.jooq.DSLContext; @@ -32,7 +33,12 @@ public List findByTenantIdAndMessageContainingIgnoreCase( Long tenantId, String message) { String filter = message == null ? "" : message; return dsl.selectFrom(LOG_EVENTS) - .where(LOG_EVENTS.TENANT_ID.eq(tenantId).and(LOG_EVENTS.MESSAGE.containsIgnoreCase(filter))) + .where( + LOG_EVENTS + .SCOPE + .eq(AccountAuditScope.TENANT.databaseValue()) + .and(LOG_EVENTS.TENANT_ID.eq(tenantId)) + .and(LOG_EVENTS.MESSAGE.containsIgnoreCase(filter))) .fetch(this::toEntity); } @@ -43,6 +49,7 @@ public Optional findFirstByTenantIdAndTypeAndMessage( LOG_EVENTS .TENANT_ID .eq(tenantId) + .and(LOG_EVENTS.SCOPE.eq(AccountAuditScope.TENANT.databaseValue())) .and(LOG_EVENTS.TYPE.eq(type)) .and(LOG_EVENTS.MESSAGE.eq(message))) .orderBy(LOG_EVENTS.ID.asc()) @@ -61,11 +68,13 @@ public LogEvent save(LogEvent entity) { int updated = dsl.update(LOG_EVENTS) .set(LOG_EVENTS.TENANT_ID, entity.getTenantId()) + .set(LOG_EVENTS.TENANT_KEY, entity.getTenantId()) + .set(LOG_EVENTS.SCOPE, AccountAuditScope.TENANT.databaseValue()) .set(LOG_EVENTS.TYPE, entity.getType()) .set(LOG_EVENTS.MESSAGE, entity.getMessage()) .set(LOG_EVENTS.TIMESTAMP, toLocalDateTime(entity.getTimestamp())) .set(LOG_EVENTS.ACCOUNT_ID, entity.getAccountId()) - .where(LOG_EVENTS.ID.eq(entity.getId())) + .where(LOG_EVENTS.ID.eq(entity.getId()).and(LOG_EVENTS.AUDIT_EVENT_ID.isNull())) .execute(); if (updated != 1) { throw new IllegalStateException("Failed to update log_events id=" + entity.getId()); @@ -79,6 +88,8 @@ private Optional findById(Long id) { private void populate(LogEventsRecord record, LogEvent entity) { record.setTenantId(entity.getTenantId()); + record.setTenantKey(entity.getTenantId()); + record.setScope(AccountAuditScope.TENANT.databaseValue()); record.setType(entity.getType()); record.setMessage(entity.getMessage()); record.setTimestamp(toLocalDateTime(entity.getTimestamp())); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java index 6d87af4ef8..8baf9b73f1 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java @@ -139,7 +139,7 @@ private static AccountAuditReceiptDto toDto( receipt.tenantId(), receipt.auditEventId(), receipt.receiptId().toString(), - receipt.id(), + receipt.logEventId(), receipt.schemaVersion(), receipt.payloadDigestVersion(), receipt.payloadDigest(), diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index f0cecbee96..5dfd71dbfd 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -29,6 +29,8 @@ import net.firedevops.firemud.loggingadmin.v1.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; import org.springframework.transaction.TransactionException; @@ -51,21 +53,33 @@ public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdmi private final LogQueryService logQueryService; private final LogEventService logEventService; private final ModerationService moderationService; + private final String workloadNamespace; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "MeterRegistry is thread-safe and only stored") private final MeterRegistry meterRegistry; + @Autowired public LoggingAdminGrpcService( LogQueryService logQueryService, LogEventService logEventService, ModerationService moderationService, - MeterRegistry meterRegistry) { + MeterRegistry meterRegistry, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.logQueryService = logQueryService; this.logEventService = logEventService; this.moderationService = moderationService; this.meterRegistry = meterRegistry; + this.workloadNamespace = workloadNamespace; + } + + LoggingAdminGrpcService( + LogQueryService logQueryService, + LogEventService logEventService, + ModerationService moderationService, + MeterRegistry meterRegistry) { + this(logQueryService, logEventService, moderationService, meterRegistry, ""); } @Override @@ -549,12 +563,17 @@ private static void requireAllowlistedInternalService( } } - private static void requireAccountAuditCaller(String methodName) { + private void requireAccountAuditCaller(String methodName) { Set allowedServices = ACCOUNT_AUDIT_CALLER_ALLOWLIST.get(methodName); GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); if (allowedServices == null || peerIdentity == null - || !allowedServices.contains(peerIdentity.service())) { + || workloadNamespace == null + || workloadNamespace.isBlank() + || !allowedServices.contains(peerIdentity.service()) + || !peerIdentity + .uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service")) { throw new AdminAuthorizationException( methodName + " requires an allowlisted account-service mTLS peer"); } diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql index 4e1a61f25a..d5305828fa 100644 --- a/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql +++ b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql @@ -1,5 +1,30 @@ +ALTER TABLE log_events + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE log_events + ADD COLUMN scope VARCHAR(16) NOT NULL DEFAULT 'tenant'; + +ALTER TABLE log_events + ADD COLUMN audit_event_id VARCHAR(36); + +ALTER TABLE log_events + ADD COLUMN tenant_key BIGINT NOT NULL DEFAULT 0; + +UPDATE log_events SET tenant_key = tenant_id; + +ALTER TABLE log_events + ADD CONSTRAINT chk_log_events_scope_tenant + CHECK ( + (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) + OR (scope = 'tenant' AND tenant_id IS NOT NULL AND tenant_key = tenant_id) + ); + +CREATE UNIQUE INDEX uq_log_events_account_audit_identity + ON log_events (scope, tenant_key, audit_event_id); + CREATE TABLE account_audit_receipts ( id BIGSERIAL PRIMARY KEY, + log_event_id BIGINT NOT NULL UNIQUE REFERENCES log_events (id), receipt_id UUID NOT NULL UNIQUE, scope VARCHAR(16) NOT NULL, tenant_id BIGINT, diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index e9cfceb262..9f1ac3ed47 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -1,19 +1,45 @@ package net.firedevops.firemud.loggingadmin; +import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; +import static net.firedevops.firemud.loggingadmin.jooq.tables.LogEvents.LOG_EVENTS; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.ByteString; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Duration; +import java.time.Instant; +import java.util.HexFormat; import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.loggingadmin.client.AccountClient; import net.firedevops.firemud.loggingadmin.client.GameSessionClient; import net.firedevops.firemud.loggingadmin.client.GameSessionControlPlaneClient; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.dto.QueryLogsRequest; +import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; +import net.firedevops.firemud.loggingadmin.jooq.tables.records.LogEventsRecord; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; +import net.firedevops.firemud.loggingadmin.service.LogEventService; +import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -71,6 +97,176 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private GameSessionControlPlaneClient gameSessionControlPlaneClient; + @Autowired private DSLContext dsl; + @Autowired private LogEventService logEventService; + @Autowired private LogQueryService logQueryService; + + @Test + void accountAuditReceiptAndProjectionShareStableIdentityAcrossRetryAndConflict() { + String eventId = "82a6f475-0baa-4fd0-a86b-580f286a9940"; + String payload = "{\"accountId\":91,\"auditMarker\":\"tenant-retry-proof\"}"; + CreateLogEventRequest request = tenantAuditRequest(eventId, payload); + + var accepted = logEventService.createLogEvent(request); + var duplicate = logEventService.createLogEvent(request); + var conflict = + logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"changed\":true}")); + + assertThat(accepted.status()).isEqualTo(AccountAuditReceiptStatus.COMMITTED); + assertThat(accepted.outcome()).isEqualTo(AccountAuditReceiptOutcome.ACCEPTED); + assertThat(duplicate.outcome()).isEqualTo(AccountAuditReceiptOutcome.DUPLICATE); + assertThat(duplicate.receiptId()).isEqualTo(accepted.receiptId()); + assertThat(duplicate.logEventId()).isEqualTo(accepted.logEventId()); + assertThat(conflict.status()).isEqualTo(AccountAuditReceiptStatus.CONFLICT); + assertThat(conflict.outcome()).isEqualTo(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + assertThat(conflict.logEventId()).isEqualTo(accepted.logEventId()); + + LogEventsRecord projection = + dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(accepted.logEventId())).fetchOne(); + AccountAuditReceiptsRecord receipt = + dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) + .where(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId)) + .fetchOne(); + assertThat(projection).isNotNull(); + assertThat(projection.getScope()).isEqualTo("tenant"); + assertThat(projection.getTenantId()).isEqualTo(42L); + assertThat(projection.getAuditEventId()).isEqualTo(eventId); + assertThat(projection.getType()).isEqualTo("ACCOUNT_AUDIT"); + assertThat(projection.getMessage()).isEqualTo("Account audit event " + eventId); + assertThat(projection.getMessage()).doesNotContain("accountId", "tenant-retry-proof"); + assertThat(receipt).isNotNull(); + assertThat(receipt.getLogEventId()).isEqualTo(projection.getId()); + assertThat(receipt.getPayload()).isEqualTo(payload.getBytes(StandardCharsets.UTF_8)); + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isOne(); + assertThat( + dsl.fetchCount( + ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) + .isOne(); + assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))) + .containsExactly("Account audit event " + eventId); + } + + @Test + void platformAuditProjectionHasNoTenantAndIsExcludedFromTenantQuery() { + String eventId = "41613d4b-3e66-4c9a-9f1c-7e02f54d0c34"; + String marker = "platform-only-marker"; + String payload = "{\"accountId\":92,\"auditMarker\":\"" + marker + "\"}"; + CreateLogEventRequest request = platformAuditRequest(eventId, payload); + + var accepted = logEventService.createLogEvent(request); + + LogEventsRecord projection = + dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(accepted.logEventId())).fetchOne(); + assertThat(projection).isNotNull(); + assertThat(projection.getScope()).isEqualTo("platform"); + assertThat(projection.getTenantId()).isNull(); + assertThat(projection.getAuditEventId()).isEqualTo(eventId); + assertThat(projection.getMessage()).isEqualTo("Account audit event " + eventId); + assertThat(projection.getMessage()).doesNotContain(marker); + assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))).isEmpty(); + } + + @Test + void receiptFailureRollsBackTheAlreadyInsertedAuditProjection() { + String eventId = "f15e1f7a-f2ee-4f90-b83d-77695bcac86c"; + dsl.execute( + "CREATE OR REPLACE FUNCTION fail_test_account_audit_receipt() RETURNS trigger " + + "LANGUAGE plpgsql AS $$ BEGIN IF NEW.audit_event_id = '" + + eventId + + "' THEN RAISE EXCEPTION 'injected receipt insert failure'; END IF; RETURN NEW; END $$"); + dsl.execute( + "CREATE TRIGGER fail_test_account_audit_receipt BEFORE INSERT ON account_audit_receipts " + + "FOR EACH ROW EXECUTE FUNCTION fail_test_account_audit_receipt()"); + try { + assertThatThrownBy( + () -> + logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"accountId\":93}"))) + .isInstanceOf(AuditStorageUnavailableException.class); + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isZero(); + assertThat( + dsl.fetchCount( + ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) + .isZero(); + } finally { + dsl.execute( + "DROP TRIGGER IF EXISTS fail_test_account_audit_receipt ON account_audit_receipts"); + dsl.execute("DROP FUNCTION IF EXISTS fail_test_account_audit_receipt()"); + } + } + + @Test + void concurrentExactRetriesCreateOneProjectionAndReturnTheSameIdentifiers() throws Exception { + String eventId = "4b7d9ee5-62f5-44dd-8b35-dcf6490d7404"; + CreateLogEventRequest request = tenantAuditRequest(eventId, "{\"accountId\":94}"); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> createAfter(start, request)); + Future second = executor.submit(() -> createAfter(start, request)); + start.countDown(); + var firstResult = first.get(20, TimeUnit.SECONDS); + var secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult.logEventId()).isEqualTo(secondResult.logEventId()); + assertThat(firstResult.receiptId()).isEqualTo(secondResult.receiptId()); + assertThat(java.util.List.of(firstResult.outcome(), secondResult.outcome())) + .containsExactlyInAnyOrder( + AccountAuditReceiptOutcome.ACCEPTED, AccountAuditReceiptOutcome.DUPLICATE); + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isOne(); + assertThat( + dsl.fetchCount( + ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) + .isOne(); + } finally { + executor.shutdownNow(); + } + } + + private AccountAuditReceiptDto createAfter(CountDownLatch start, CreateLogEventRequest request) { + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent audit test did not start"); + } + return logEventService.createLogEvent(request); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent audit test was interrupted", ex); + } + } + + private static CreateLogEventRequest tenantAuditRequest(String eventId, String payload) { + return auditRequest(AccountAuditScope.TENANT, 42L, eventId, payload); + } + + private static CreateLogEventRequest platformAuditRequest(String eventId, String payload) { + return auditRequest(AccountAuditScope.PLATFORM, null, eventId, payload); + } + + private static CreateLogEventRequest auditRequest( + AccountAuditScope scope, Long tenantId, String eventId, String payload) { + ByteString payloadBytes = ByteString.copyFrom(payload, StandardCharsets.UTF_8); + return new CreateLogEventRequest( + scope, + tenantId, + eventId, + "account-service", + "ACCOUNT_AUDIT_INTEGRATION_TEST", + Instant.parse("2026-09-24T00:00:00Z"), + 1, + payloadBytes, + 1, + digest(payloadBytes.toByteArray())); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + @Test void pingEndpointReturnsPong() throws Exception { String token = diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java index 130443b4b4..fe7e669f6b 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java @@ -30,6 +30,7 @@ class LogEventServiceImplTest { private static final String AUDIT_EVENT_ID = "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3"; private static final UUID RECEIPT_ID = UUID.fromString("c0c1f03b-31b7-4281-aaf8-2d66f29e8770"); + private static final long LOG_EVENT_ID = 192L; private final AccountAuditReceiptRepository repository = Mockito.mock(AccountAuditReceiptRepository.class); @@ -47,7 +48,7 @@ void firstWriteReturnsCommittedAcceptedReceipt() { assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); assertEquals(AccountAuditReceiptOutcome.ACCEPTED, result.outcome()); - assertEquals(91L, result.logEventId()); + assertEquals(LOG_EVENT_ID, result.logEventId()); verify(repository).insertIfAbsent(eq(request), any(UUID.class)); } @@ -64,6 +65,26 @@ void exactRetryReturnsOriginalReceiptAsDuplicate() { assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); assertEquals(AccountAuditReceiptOutcome.DUPLICATE, result.outcome()); assertEquals(42L, result.tenantId()); + assertEquals(LOG_EVENT_ID, result.logEventId()); + assertEquals(RECEIPT_ID.toString(), result.receiptId()); + } + + @Test + void changedPayloadReturnsIdempotencyConflict() { + CreateLogEventRequest original = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); + CreateLogEventRequest changed = + request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{\"changed\":true}"); + when(repository.insertIfAbsent(eq(changed), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), + false)); + + var result = service.createLogEvent(changed); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); + assertEquals(LOG_EVENT_ID, result.logEventId()); } @Test @@ -185,6 +206,7 @@ private static AccountAuditReceipt receipt( CreateLogEventRequest request, byte[] payload, String status, String outcome) { return new AccountAuditReceipt( 91L, + LOG_EVENT_ID, RECEIPT_ID, request.scope().databaseValue(), request.tenantId(), diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 78732246a7..533f39e7d1 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -153,12 +153,7 @@ void accountMtlSPeerCreatesReceiptWithoutJwtOrAdminRole() { digest, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.ACCEPTED)); - LoggingAdminGrpcService service = - new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), - logEventService, - moderationService, - new SimpleMeterRegistry()); + LoggingAdminGrpcService service = newService(logEventService); AtomicReference ref = new AtomicReference<>(); AtomicReference error = new AtomicReference<>(); @@ -214,6 +209,21 @@ void jwtClaimNamingAccountServiceCannotOverrideWrongMtlsPeer() { verifyNoInteractions(logEventService); } + @Test + void accountAuditMethodsRejectAccountPeerFromWrongNamespace() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeerUri( + "spiffe://firemud/ns/other/sa/account-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + @Test void receiptReadReturnsCanonicalNotFoundStatus() { LogEventService logEventService = Mockito.mock(LogEventService.class); @@ -787,7 +797,8 @@ private static LoggingAdminGrpcService newService(LogEventService logEventServic Mockito.mock(LogQueryService.class), logEventService, Mockito.mock(ModerationService.class), - new SimpleMeterRegistry()); + new SimpleMeterRegistry(), + "firemud"); } private static boolean passesWithoutBearer( @@ -835,10 +846,13 @@ public void onCompleted() {} private static void invokeWithPeer(String serviceName, Runnable invocation) { String uri = "spiffe://firemud/ns/firemud/sa/" + serviceName; + invokeWithPeerUri(uri, invocation); + } + + private static void invokeWithPeerUri(String uri, Runnable invocation) { Context context = Context.current() - .withValue( - GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, "firemud", serviceName)); + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); Context previous = context.attach(); try { invocation.run(); From a2466f206e0f6f843257a04cacaa6e48af7dae7b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 12:47:57 +1200 Subject: [PATCH 04/55] Reject expired pending JOIN scope and align Account status --- .../account-service/api-contracts.md | 8 +- .../account-service/runtime-and-data.md | 9 +- .../system-architecture-authentication.md | 4 +- .../service/impl/AccountServiceImpl.java | 12 +++ .../service/impl/AccountServiceImplTest.java | 100 ++++++++++++++++++ 5 files changed, 122 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index e2e6c740b1..92867d7a07 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -78,7 +78,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `CreateAccount` – registers a global Account identity and returns its `accountId`; it does not select a tenant or create membership/profile state. Registration also appends a platform-scoped audit outbox record in the Account transaction. - `SendNotification` – deliver account notifications asynchronously. - `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. -- `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); a `PENDING` operation after an unknown database commit outcome still requires unresolved recovery/reconciliation work under ADR 0025. +- `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. - `ResolveEffectiveSecurityPolicy` – **Target-state internal Account contract.** Resolve the effective policy for the exact account, optional tenant-scoped action, and action class from the versioned platform baseline, deployment policy, and applicable tenant policy using the tightening precedence in ADR 0045. Return the contributing policy versions, resolved values, and opaque `effectivePolicyVersion`/digest from one Account-owned resolution. Callers must not merge inputs or use cached/default policy; missing, invalid, contradictory, stale, or unavailable resolution fails the sensitive action closed. No other service is a policy authority. - `ApplyAccountSafetyRestriction` / `GetAccountSafetyRestrictions` – target Account-owned owner-command and safe projection contracts for `account_security_lock` and `platform_access_ban`. The command carries one exact category, global account scope, source case/security-event identity, a distinct `ownerEnforcementRequestId`, owner-enforcement digest, and owner authorization evidence; `controlPlaneRequestId` remains correlation-only and never carries or aliases the owner identity. Account validates and atomically commits its monotonic revision, account authority-generation effects, and idempotent result. The current proto/transport mapping does not yet expose the distinct owner request field; that is implementation drift, not proof that the target command is implemented. These contracts do not create a moderation appeal case, and current proto/implementation/proof do not yet provide the complete lifecycle. - `RefreshGameplayServiceToken` – Account-local RPC for the token refresh/replacement operation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). Account validates the declared receiver binding and current authority, while Game Session supplies the binding-refresh installation/reconciliation consequence; the current proto and implementation do not yet prove the target registry-backed operation. @@ -106,7 +106,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `IssueDirectTextConnectScope` – implemented local internal Account API called by authenticated Game Session during authenticated `REALMS`. The request carries authenticated caller context in typed `PlayerExecutionContext` plus the server-resolved target; Account validates caller context separately from the short-lived scope and returns an opaque `connectScopeId` bound to the evaluated routing snapshot. It is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the membership mutation. Reachable missing or invalid routing evidence fails as `ADMISSION_POINTER_UNAVAILABLE`; a changed exact routing pair fails as `CONNECT_SCOPE_MISMATCH`; unavailable authority fails as `AUTH_UNAVAILABLE`. Fresh Account membership checks remain required separately at applicable admission gates. The canonical scope and transport requirements remain owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); this local status does not claim direct text-client end-to-end proof. - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). -- `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery for an operation left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision; PostgreSQL runtime and direct text-client end-to-end proof are not claimed. +- `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the response is the four-field admission shape documented above and does not expose lifecycle state or `membershipAuthorityGeneration`. **Target-only:** the response adds `membershipLifecycleState` and opaque `membershipAuthorityGeneration`, with the independent `membershipVersion`, from one fresh atomic Account membership snapshot. @@ -190,7 +190,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `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 four-field membership response, 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/bootstrap/join` | **Target facade; not currently routable.** The local internal `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. 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. Durable PostgreSQL recovery and direct text end-to-end proof remain open. | +| `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 fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. 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. Exact-final-head PostgreSQL proof, recovery/reconciliation after an unknown commit outcome, 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 | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -229,7 +229,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | --- | --- | --- | --- | | Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. `POST /auth/verify-email` is target-public but is excluded from the current public allowlist and therefore requires a bearer under the current configuration; the allowlisted `GET` has no controller mapping. | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | -| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, while explicit `/auth/bootstrap/join` remains the unimplemented target-state first-party open-enrollment writer. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Account delivers the connect token only through the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. | +| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Account delivers the connect token only through the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | | Authenticated account control-plane APIs | Current legacy `/accounts/{accountId}/export`; target `/auth/logout`, `/auth/logout-all`, `/tenants/{tenantId}/profiles/{accountId}`, active-account `/accounts/{accountId}/exports/**`, `/accounts/{accountId}`, `/tenants/{tenantId}/memberships/me`, `/tenants/{tenantId}/memberships/{accountId}` | Exact ordinary account subject through the declared `control-ui` JWT route class | This is the target authentication class only while the account remains eligible for ordinary authority. The current singular legacy export is classified here as an ordinary authenticated account-subject route; the target export lifecycle uses the authenticated account subject while active. The REST inventory identifies which routes are currently implemented and which remain target-only. | | Tenant-admin billing-safe export | `/tenant-admin/tenants/{tenantId}/export` | Exact `control-ui` caller with live `tenantAdmin` membership bound to the `{tenantId}` route segment | `billing_safe_tenant` classification. The route has a tenant binding but no `accountId` subject selector, requires live membership and membership-generation evidence, and remains target-only/not currently routable. | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9749be12e6..b01a047e7c 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. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A changed policy digest on a still-pending operation returns `IDEMPOTENCY_CONFLICT` without replacing its bound evidence or terminalizing that operation. 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. No background PENDING-operation reconciler is claimed. 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 or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A changed policy digest on a still-pending operation returns `IDEMPOTENCY_CONFLICT` without replacing its bound evidence or terminalizing that operation. 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. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. 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. 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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the two admission fields are true; an eligible public-production request with missing or non-admitting membership may return non-actionable `JOIN_REQUIRED`, but the current response cannot distinguish `INACTIVE` from another existing non-admitting lifecycle state. These paths do not create or restore membership. 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. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision, so ADR 0025 is not complete. Focused local tests exist, but PostgreSQL runtime proof and direct text-to-Logging end-to-end proof are not claimed. `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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit 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 response cannot distinguish `INACTIVE` from another existing non-admitting lifecycle state. These paths do not create or restore membership. 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. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains open; no Overseer decision is implied. 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` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. @@ -139,7 +139,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 runtime requires existing caller-bound membership for character discovery, connect-token issuance, and text `PLAY` and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. For a publicly visible public-production target whose joining policy permits entry, `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating or restoring membership; the latter response is not lifecycle-aware and explicit `JOIN` remains unavailable. 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 runtime requires existing caller-bound membership for character discovery, connect-token issuance, and text `PLAY` and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. For a publicly visible public-production target whose joining policy permits entry, `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED` without creating or restoring membership; the latter response 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. - 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. @@ -268,8 +268,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### Runtime Implementation Status and Drift -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may return non-actionable `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter response cannot be classified as `INACTIVE` because lifecycle state is target-only, and explicit `JOIN` remains unavailable. The current non-public mappings differ by surface: connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. -- Explicit `JOIN`/`Join & Play` and the membership-authority-generation reread at connect-token issuance remain target follow-through. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may return `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter response cannot be classified as `INACTIVE` because lifecycle state is target-only. The local explicit `JOIN`/`Join & Play` operation and controller exist; the current non-public mappings differ by surface: connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. PostgreSQL exact-final-head proof, recovery/reconciliation after unknown commit outcomes, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. ## Monetization and Notification Domain Notes diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index a58cfe4152..2bd550bb6a 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The explicit join action and the required `membershipAuthorityGeneration` reread at connect-token issuance remain unimplemented/proof gaps. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The adapter response has no `membershipLifecycleState` field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`, and explicit `JOIN` remains unavailable. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result is a fail-closed, non-actionable denial while explicit `JOIN`/`Join & Play` is unimplemented; it must not be presented as proof that the target repair flow is available. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains target-only and individual bootstrap/connect-token endpoints remain partial implementation surfaces. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The adapter response has no `membershipLifecycleState` field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result remains a fail-closed admission denial until the caller completes the local explicit join operation; it is not proof of the target lifecycle snapshot or final admission flow. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains partial and its PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof remain open. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. @@ -314,7 +314,7 @@ These modes are complementary: public browse remains available before authentica ``` - Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. `allowPublicJoin` is lowercase `true` or `false`; `entitlementVersion` is a positive canonical decimal. Account stores the intent digest/version before evaluation, then stores the request digest/version and exact policy evidence only after `AVAILABLE` authority has supplied both policy values. If entitlement authority is unavailable, Account records the attempt failure and availability while leaving the operation `PENDING`; it does not create a policy-bound request digest or invent a policy result/version. A retry with the same intent may reconcile that pending operation when authority is available. At the membership commit gate Account re-evaluates policy and requires the exact same digest and evidence; changed policy returns `IDEMPOTENCY_CONFLICT` without committing membership or its transition event. Exact retries replay the stored operation result after their required current-policy check. No earlier JOIN digest was persisted, so no version-compatibility path is required. -- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. +- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery; for a retained `PENDING` operation, an expired scope terminally returns `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. Normative semantic split: 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 0cf50e9c34..db0338c25b 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 @@ -607,6 +607,10 @@ private JoinPublicProductionResult executeJoinAttempt( return replayJoinOperation(operation, callerBinding, scope); } + if (isConnectScopeExpired(scope)) { + return failedJoin(requestId, scope, "CONNECT_SCOPE_INVALID"); + } + JoinEvaluation evaluation = evaluateJoin(scope); if (evaluation.failureCode() != null) { if (isRetryableJoinAuthorityFailure(evaluation)) { @@ -752,6 +756,14 @@ private JoinPublicProductionResult pendingJoinFailure( false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); } + private boolean isConnectScopeExpired(VerifiedJoinScope scope) { + try { + return !Instant.parse(scope.connectScopeExpiresAt()).isAfter(Instant.now()); + } catch (RuntimeException ex) { + return true; + } + } + private boolean isRetryableJoinAuthorityFailure(JoinEvaluation evaluation) { return "UNAVAILABLE".equals(evaluation.authorityAvailability()) || "ADMISSION_POINTER_UNAVAILABLE".equals(evaluation.failureCode()) 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 a77ba42633..27e1700bb4 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 @@ -593,6 +593,106 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); } + @Test + void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = "expired-connect-scope"; + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-expired-pending-1"); + + VerifiedJoinScope expiredScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + 101L, + "demo", + "production", + "production-namespace-7", + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + expiredScope = + new VerifiedJoinScope( + expiredScope.connectScopeId(), + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + expiredScope.worldSlug(), + expiredScope.realmSlug(), + expiredScope.playableStateNamespaceId(), + expiredScope.playableStateScope(), + expiredScope.gameInstanceId(), + expiredScope.catalogRevision(), + expiredScope.pointerVersion(), + expiredScope.evaluatedAt(), + expiredScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(expiredScope)); + retainedScope.set(expiredScope); + String callerBinding = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(bootstrap.bootstrapToken()) + .getPayload() + .get("jti") + .toString(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + expiredScope.accountId(), + expiredScope.tenantId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + expiredScope.snapshotDigest(), + "UNAVAILABLE", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + request.requestId(), expiredScope, callerBinding), + "ENTITLEMENT_UNAVAILABLE", + "UNAVAILABLE")); + + JoinPublicProductionResult expiredRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult terminalReadback = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(expiredRetry.success()); + assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); + assertFalse(terminalReadback.success()); + assertTrue(terminalReadback.replayed()); + assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); + verifyNoInteractions( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + } + @Test void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { Account account = new Account(); From 71ee430f649d8df67fdf3c437402b2b35a699b1d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 12:49:07 +1200 Subject: [PATCH 05/55] Align Unit 1A JOIN status and audit identity manifest proof --- ...025-explicit-open-enrollment-membership.md | 4 +-- ...nt-and-tenant-scoped-game-relationships.md | 4 +-- .../game-session-service/protocols.md | 6 ++-- .../system-architecture-authz-route-matrix.md | 2 +- design/product/user-journeys/players.md | 6 ++-- .../design-alignment/README.md | 6 ++-- .../whole-corpus-authority-review-plan.md | 3 +- .../realm-routing-and-playable-state.md | 10 +++--- ...d-identity-controller-manifest-contract.sh | 36 ++++++++++++++++++- 9 files changed, 56 insertions(+), 21 deletions(-) diff --git a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md index 64a64ef86d..fdf4b6b5ae 100644 --- a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md +++ b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The accepted explicit-join decision is target state. Current first-party connect-token issuance and text `PLAY` now require existing membership and do not invoke an implicit membership writer; fresh authoritative missing or `INACTIVE` public-production membership fails closed with `JOIN_REQUIRED`. The obsolete differently named writer RPC and service implementation have been removed rather than retained as compatibility behavior. Explicit `JOIN` / `Join & Play`, the membership transaction, monotonic versioning, durable audit/outbox boundary, and the exact current membership snapshot plus independent `membershipVersion` and `membershipAuthorityGeneration` reread at every connect-token issuance remain incomplete. No complete runtime implementation is claimed by this ADR. +The accepted explicit-join decision remains the target contract, with a local Account implementation now present. Global-only registration creates global account state and a platform-scoped audit outbox record without membership or profile authority; `JoinPublicProductionMembership` is the sole local public-production membership writer, with a policy-independent durable intent followed by a policy-bound digest, membership transition, operation outcome, and tenant-scoped audit/outbox evidence committed by the Account transaction. Current first-party connect-token issuance and text `PLAY` require existing membership and do not invoke an implicit membership writer; fresh authoritative missing or non-admitting public-production membership fails closed with `JOIN_REQUIRED` where the current adapter can establish that predicate. The obsolete differently named writer RPC and service implementation remain removed rather than retained as compatibility behavior. This local seam has focused unit and repository proof, but PostgreSQL execution is unavailable locally, no pending-operation recovery/reconciliation worker or direct text-to-Logging end-to-end proof is claimed, and the complete lifecycle snapshot plus independent `membershipVersion` and `membershipAuthorityGeneration` reread at every connect-token issuance remain incomplete. ADR 0025 therefore does not claim complete runtime or production proof. ## Decision Record @@ -24,7 +24,7 @@ The accepted explicit-join decision is target state. Current first-party connect A tenant may deliberately expose one default production realm for public discovery. Joining that game should create a durable Account-owned player membership: the relationship powers the player's game library, later discovery, return-to-game flows, creator membership views, moderation, and account/tenant data handling. -The earlier admission flow created membership implicitly during first-party connect-token issuance or text-client `PLAY` through an obsolete membership writer. Current admission callers have been corrected to require existing membership and return `JOIN_REQUIRED`, and that writer RPC/service seam has been removed without introducing a compatibility path. The remaining implementation also lacks the accepted explicit-join boundary, target transaction, versioning, and durable audit/outbox contract. +The earlier admission flow created membership implicitly during first-party connect-token issuance or text-client `PLAY` through an obsolete membership writer. Current admission callers have been corrected to require existing membership and return `JOIN_REQUIRED`, and that writer RPC/service seam has been removed without introducing a compatibility path. The accepted explicit-join boundary, policy-bound Account transaction, and local durable audit/outbox seam now exist; PostgreSQL, recovery/reconciliation, downstream snapshot-generation, and end-to-end transport proof remain incomplete. ## Decision diff --git a/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md b/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md index 53c53531ae..0624429fd5 100644 --- a/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md +++ b/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The global-account and explicit-membership model is target state and is not yet fully implemented or proved. Current registration DTOs, service call sites, fixtures, and persistence still carry legacy `tenantId`/`accounts.tenant_id` assumptions, so registration remains tenant-aware implementation drift rather than evidence that the target global-only registration contract is live. Direct convergence must make registration create only the global account and leave tenant membership to explicit `JOIN`. +The global-account and explicit-membership model has a local implementation, but is not yet fully proved or deployment-ready. Current registration now creates only global account state and a platform-scoped audit outbox record, while `JoinPublicProductionMembership` is the sole local public-production membership writer and records a policy-independent intent before binding exact policy evidence, membership, operation outcome, and tenant-scoped audit/outbox evidence. Legacy migrations and retained-data paths still carry `tenantId`/`accounts.tenant_id` assumptions, so the global-only registration contract must not be read as proof that legacy data is reconciled or safe to deploy. Exact-final-head PostgreSQL validation, pending-operation recovery/reconciliation, and direct text-to-Logging end-to-end proof remain incomplete; direct convergence still requires registration to remain global-only and tenant membership to remain explicit `JOIN`. ## Decision Record @@ -32,7 +32,7 @@ The current implementation still carries legacy `accounts.tenant_id` drift. That - Registration creates only the global account. It does not create tenant membership, roles, a profile, a character, an entitlement, or gameplay authority. - Explicit `JOIN` creates the durable account-to-tenant membership for one game according to the accepted admission contract. - The canonical membership relation enforces exactly one row per `(account_id, tenant_id)` with a database unique constraint. Account serializes `JOIN` on that membership key. An exact retry with the same request ID and digest replays that operation's stored outcome. A concurrent request with a different request ID or digest waits for the first membership-key transition, then records its own durable no-op outcome referencing the canonical membership; it does not replay another operation's stored result, insert another row, or emit another logical membership event. -- Every `JOIN` carries a caller-stable operation ID (`requestId`) and a canonical digest whose preimage includes `operationKind=JOIN`, the authenticated account, verified caller binding, verified target, and other authority-bearing inputs. Account persists those inputs with the operation ID, digest, lifecycle status, and terminal outcome in durable storage before returning a terminal result. An exact retry with the same ID and digest returns that operation's stored outcome; reuse with a different digest is rejected as `IDEMPOTENCY_CONFLICT`; an unresolved or ambiguous operation remains pending and never becomes an implicit success. +- Every `JOIN` carries a caller-stable operation ID (`requestId`) and a canonical digest whose preimage includes `operationKind=JOIN`, the authenticated account, verified caller binding, verified target, and other authority-bearing inputs. Account persists those inputs with the operation ID, digest, lifecycle status, and terminal outcome in durable storage before returning a terminal result. Before replaying a stored terminal result, Account performs the current-policy check; unavailable or unsafe current policy fails closed without overwriting or re-executing the stored result, and a later retry under the same policy may replay it. A changed policy or digest is rejected as `IDEMPOTENCY_CONFLICT`; an unresolved or ambiguous operation remains pending and never becomes an implicit success. - The membership transition and its durable audit/outbox event are committed atomically with the same persisted `JOIN` operation ID and digest. An exact retry therefore replays that one stored outcome and cannot create a second membership transition or logical event; a concurrent distinct operation records its own no-op outcome after the canonical row is visible and also emits no transition event. The operation record, membership row, transition evidence, and event must be sufficient to reconcile a lost response without re-executing the join. - Leaving is a distinct operation kind with its own stable operation ID, canonical digest, stored outcome, membership transition, and audit/outbox event. A later rejoin is a new `JOIN` operation and a distinct `INACTIVE` -> `ACTIVE` transition; it must not replay or mutate the earlier leave outcome. `JOIN` is not a general lifecycle repair and cannot restore any state other than `INACTIVE`. - Tenant roles, profiles, characters, tenant-bound purchases, subscriptions, entitlements, grants, and gameplay state are tenant-scoped relationships or records. They must carry and enforce their owning `tenantId` rather than becoming global account attributes. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index be24a5b9c6..1d14a6758f 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account does not yet expose `membershipLifecycleState`, so an `ACTIVE` or `INACTIVE` classification is target-only until Account exposes that field. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. The local Account `JoinPublicProductionMembership` operation and Game Session translation/scope seam now exist, but complete direct-text and first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and the Account lifecycle/authority-generation snapshot needed by final admission remain incomplete. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account does not yet expose `membershipLifecycleState`, so an `ACTIVE` or `INACTIVE` classification is target-only until Account exposes that field. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). @@ -82,14 +82,14 @@ Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable ` The canonical JOIN and membership-admission contract is defined in [Authentication & Authorization](../../system-architecture-authentication.md#normative-target-contract); this section keeps only Game Session's protocol translation and local handling. -The target Account membership operation is `JoinPublicProductionMembership`; it remains target-only and unimplemented, so there is no current implicit membership writer. When the explicit text action is implemented, Game Session translates `JOIN ` to the sole target operation `JoinPublicProductionMembership`; it does not create membership locally or use another join writer. +The target Account membership operation is `JoinPublicProductionMembership`; a local Account operation and Game Session translation/scope seam now exist, and there is no current implicit membership writer. The local path does not claim complete direct-text/first-party transport proof, PostgreSQL execution, or pending-operation recovery. Game Session translates `JOIN ` to the sole operation; it does not create membership locally or use another join writer. - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. - Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the pending transport-local scope and passes the same identity to Account for retries. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. - An ambiguous or stale world/realm selector is a lobby-selection error: Game Session does not guess, does not invoke Account, and directs the client to refresh `WORLDS`/`REALMS`. A discovered scope that is stale or no longer matches the resolved `worldSlug`/`realmSlug` fails closed with the applicable scope or admission error rather than being translated to a newer target. - JOIN idempotency uses the canonical preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session generates and retains the server-side `requestId`, passes the verified local digest inputs and retained scope to Account, and reuses that identity through retries and scope-expiry cleanup. Account replays an exact `{requestId, digest}` outcome and rejects a different digest as `IDEMPOTENCY_CONFLICT`; a new `requestId` is a distinct attempt after a new scope. -Current `JOIN` availability and the membership-authority-generation gap are recorded in [Implementation Status](#implementation-status); this section defines only the target translation and must not be read as evidence that the explicit-join action is live. +Current local `JOIN` availability and the membership-authority-generation gap are recorded in [Implementation Status](#implementation-status); this section defines Game Session's transport consequence and must not be read as complete end-to-end or production proof. ## Login and Play Flow diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index b2c5844a2f..d6a4831f71 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. Explicit `JOIN` remains unimplemented. +- 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. - `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy in rows 260-261. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. - 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. diff --git a/design/product/user-journeys/players.md b/design/product/user-journeys/players.md index 50659a67c6..9dd5a944ff 100644 --- a/design/product/user-journeys/players.md +++ b/design/product/user-journeys/players.md @@ -41,7 +41,7 @@ These journeys define observable product behavior and user-facing outcomes; tech ## Implementation Status -The target journeys below are primary. Current runtime status is concise: explicit `JOIN` / `Join & Play` and the complete realm-scoped character gate remain unimplemented; existing credential-bearing clients may still use direct `LOGIN` -> `PLAY` when they already have usable membership and a character. Connect-token issuance and text `PLAY` require existing membership and return `JOIN_REQUIRED` for eligible missing or `INACTIVE` public-production membership. Realm-aware discovery is implemented at the backend boundary, but the richer character-creation descriptor remains a gap. Account export is still Account/profile-only, and the complete cross-service deletion workflow is not yet proved. See the [Account Service export contract](../../architecture/microservices/account-service/api-contracts.md#current-vs-target-export-lifecycle), [ADR 0043](../../architecture/decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md#decision), and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#decision) for those implementation boundaries. +The target journeys below are primary. Current runtime status is concise: the local Account `JOIN` / `Join & Play` operation and global-only registration seam are implemented, but the complete realm-scoped character gate remains unimplemented and direct text/first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and downstream lifecycle/authority-generation admission proof remain incomplete. Existing credential-bearing clients may still use direct `LOGIN` -> `PLAY` when they already have usable membership and a character. Connect-token issuance and text `PLAY` require existing membership and return `JOIN_REQUIRED` for an eligible missing or non-admitting public-production membership; the current adapter cannot classify the latter specifically as `INACTIVE`. Realm-aware discovery is implemented at the backend boundary, but the richer character-creation descriptor remains a gap. Account export is still Account/profile-only, and the complete cross-service deletion workflow is not yet proved. See the [Account Service export contract](../../architecture/microservices/account-service/api-contracts.md#current-vs-target-export-lifecycle), [ADR 0043](../../architecture/decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md#decision), and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#decision) for those implementation boundaries. Current gameplay supports room views, movement, foundational inventory/container/equipment commands, and room-local `SAY`, `WHISPER`, and `TELL`. Guild chat and mail remain deferred target behavior and are not current player-runtime capabilities. The shared current communication path includes metadata-only whisper observers and recipient-side delivery for generic WebSocket and Telnet clients; broader audible scopes and first-party/MCP-aware presentation remain gaps. The target player-facing report ingress is not currently available; current support is limited to an internal service-to-service report-persistence seam, not player ingress. @@ -109,7 +109,7 @@ Player → Account bootstrap/discovery → [Join & Play when public membership i → connect-token issuance → Gateway WebSocket handshake → bare LOGIN → PLAY ``` -Target-state example text-client transcript (explicit `JOIN` is not implemented in the current runtime): +Target-state example text-client transcript (the local `JOIN` seam exists; complete transport end-to-end proof remains incomplete): ```text WORLDS @@ -138,7 +138,7 @@ LOGIN PLAY [realm] [character] ``` -Target-state example first-time public production join (explicit `JOIN`/`Join & Play`, including `POST /auth/bootstrap/join`, is not implemented in the current runtime): +Target-state example first-time public production join (the local Account `JOIN`/`Join & Play` operation exists; complete transport and production proof remains incomplete): ```text POST /auth/player-bootstrap { accountIdentifier=player@example.com, secret= } diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 4092bf4f3c..1973f82001 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Cycle 17 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–17 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 refreshed the 28-source manifest, corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and recorded the unresolved exact-binding reconnect token/lease handoff for Overseer without authorizing an LKG fallback. Cycle 17 exposed the concrete public-registration membership bypass of disabled public joining; AA-1.1/AA-1.2 now state the live gap, and a containment/deployment decision is pending because coherent global registration also needs platform-scoped durable audit. The optional external-provider product summary now matches ADR 0049. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 18 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–18 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and recorded the unresolved exact-binding reconnect token/lease handoff for Overseer without authorizing an LKG fallback. Cycle 17 exposed the concrete public-registration membership bypass of disabled public joining. Cycle 18 corrected stale corpus status: global-only registration, the local explicit `JOIN` operation, and the Account audit-ingress seam are implemented locally, while PostgreSQL execution, retained-data deployment disposition, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, lifecycle/authority-generation snapshot completion, and full billing evidence remain open. Drafts #2846, #2847, and #2848 are correction evidence only and do not establish corpus taper. The optional external-provider product summary now matches ADR 0049. Cycle 18 routed non-public realm-discovery leakage and stale join guidance to Unit 1B; those are not discarded. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 retains the target decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | @@ -159,9 +159,9 @@ PR closure follows the hosted review evidence and judgment described by the [PR ## Automated Gates -Focused validation on 2026-09-09 Pacific/Auckland passed for the current `355` discovered sources (`352` allocated, `3` explicit exemptions) and `180` ADR records, with `172` carrying completed review metadata and `11` pre-formal records; those categories overlap for accepted legacy pre-formal records carrying exact provenance. Prior parcel validation remains historical evidence only. On 2026-08-28 Pacific/Auckland, the integrated local gates passed against the then-current `354` discovered sources (`351` allocated, `3` explicit exemptions) and `179` ADR records, with `171` carrying completed review metadata and `11` pre-formal records: implementation tracking covered `79` leaves across `10` trackers, the authorization-route matrix passed, the full architecture-document contract suite passed, `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded), `lintMarkdown` checked `535` files (`0` issues), and `git diff --check` was clean. These listed gates are local documentation/structure checks only. The current port also includes controller, Kubernetes, workflow, and deployment-tooling implementation with focused local proof; its owning domain tracker remains authoritative for implementation and proof status. Live hosted-environment proof remains unavailable, and neither the target contracts nor local checks should be read as commit, PR, CI, or live-hosted proof. +Focused validation on 2026-09-09 Pacific/Auckland passed for the then-current `355` discovered sources (`352` allocated, `3` explicit exemptions) and `180` ADR records, with `172` carrying completed review metadata and `11` pre-formal records; those categories overlap for accepted legacy pre-formal records carrying exact provenance. The current allocation has `356` discovered sources (`353` allocated, `3` explicit exemptions), including pending, unaccepted ADR 0183; this is a source inventory, not a new accepted decision. Prior parcel validation remains historical evidence only. On 2026-08-28 Pacific/Auckland, the integrated local gates passed against the then-current `354` discovered sources (`351` allocated, `3` explicit exemptions) and `179` ADR records, with `171` carrying completed review metadata and `11` pre-formal records: implementation tracking covered `79` leaves across `10` trackers, the authorization-route matrix passed, the full architecture-document contract suite passed, `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded), `lintMarkdown` checked `535` files (`0` issues), and `git diff --check` was clean. These listed gates are local documentation/structure checks only. The current port also includes controller, Kubernetes, workflow, and deployment-tooling implementation with focused local proof; its owning domain tracker remains authoritative for implementation and proof status. Live hosted-environment proof remains unavailable, and neither the target contracts nor local checks should be read as commit, PR, CI, or live-hosted proof. -- `python3 dev-tools/validation/check-design-capability-allocation.py` derives the product and architecture source sets, parses each allocation ledger, and reconciles the declared current coverage summary (`355` discovered sources, `352` allocated sources, and the canonical `2` governance/template exemptions plus `1` registry exemption). +- `python3 dev-tools/validation/check-design-capability-allocation.py` derives the product and architecture source sets, parses each allocation ledger, and reconciles the declared current coverage summary (`356` discovered sources, `353` allocated sources, and the canonical `2` governance/template exemptions plus `1` registry exemption). - all intended FireMUD user, creator, operator, runtime, authoring, automation, platform, and commercial concerns have a capability home; - every Markdown source under `design/product/**` and `design/architecture/**` is present and classified in the allocation ledger, including generated/index material, unless it is one of the two explicit governance/template exemptions or the decision-registry exemption; - mixed canonical documents have heading-level allocations where file-level allocation would hide a real ownership split; diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index a00f87064b..0f9d2f3db8 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -38,7 +38,7 @@ These recovered manifests are starting review prompts, not frozen inventories or ### 1A -Unit 1A's substantive boundary is the following 28 identity, membership, entitlement, billing, and hosted-terms sources: +Unit 1A's substantive boundary is the following 29 identity, membership, entitlement, billing, and hosted-terms sources: 1. `design/architecture/service-responsibility-matrix.md` 2. `design/architecture/system-architecture-overview.md` @@ -68,6 +68,7 @@ Unit 1A's substantive boundary is the following 28 identity, membership, entitle 26. `design/architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md` 27. `design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md` 28. `design/architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md` +29. `design/architecture/microservices/account-service/README.md` Review Account's sole authority for global identity, credentials, explicit membership, entitlement, Creator Party and terms evidence; account-global versus tenant-scoped records; public versus private/playtest access; strict and continuity entitlement freshness; authentication path separation; role versus gameplay authority; hosted creator mutation currentness; changed-terms decline and prior-rights continuity; and payment evidence versus runtime entitlement. Unit 1A consumes 5A token/authority primitives and hands gameplay binding to 1B and operator reference execution to 6C. Refresh for material 5A, 6C, 1B, 5B/5D, 3A, or billing/provider changes. Repository licence/terms files remain legal-policy handoffs rather than technical authority sources. 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 a7bb6391dc..64acb919cc 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target-only and unimplemented; Account issuance/validation and Game Session transport-local scope retention, retry, terminal-outcome, and expiry behavior still need implementation and proof. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, catalog and route revisions are combined, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. +The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a local Account issuance/validation and Game Session transport-local scope seam; retry, terminal-outcome, expiry, PostgreSQL execution, direct text-to-Logging end-to-end proof, and pending-operation recovery/reconciliation remain incomplete. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, catalog and route revisions are combined, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. ## Packet 4 Status and Proof Gaps @@ -55,11 +55,11 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current connect-token issuance and text-client `PLAY` consume an Account membership response identified by `accountId` and `tenantId` with four admission-evidence fields, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they admit only when the two admission fields are true, and an eligible public-production request with `membershipExists=false` may return non-actionable `JOIN_REQUIRED`. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. Explicit `JOIN` / `Join & Play` remains unimplemented, and the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current connect-token issuance and text-client `PLAY` consume an Account membership response identified by `accountId` and `tenantId` with four admission-evidence fields, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they admit only when the two admission fields are true, and an eligible public-production request with `membershipExists=false` may return non-actionable `JOIN_REQUIRED`. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. The local Account `JOIN` operation and Game Session transport seam now exist; PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, the target membership-authority-generation reread, and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. -The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target/unimplemented because Account direct-text `JOIN` issuance/validation and Game Session transport-local scope retention through retry, terminal outcome, or expiry still lack implementation and focused proof. This is distinct from the browser/WebSocket bootstrap snapshot and remains a contract gap rather than current proof. +The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) has a local Account direct-text `JOIN` issuance/validation and Game Session transport-local scope seam. Retry, terminal outcome, expiry, PostgreSQL execution, pending-operation recovery/reconciliation, and focused direct text-to-Logging end-to-end proof remain incomplete. This is distinct from the browser/WebSocket bootstrap snapshot and remains a contract gap rather than current proof. Gateway and Game Session preserve and validate `worldSlug`, `realmSlug`, `connectScopeId`, `connectRequestId`, `pointerVersion`, and resolved target in first-party connect context. The durable bootstrap shell stores the selector identity and is the reconnect/login/`PLAY` fallback when transient registry state is absent. Generic websocket bootstrap preserves an incoming complete bundle, repairs a runtime-only shell only from one complete current pointer, and collapses ambiguous or incomplete authority to no bundle. If a reused shell had a bundle and the repaired incoming shell does not, it is a real route change: the `BOOTSTRAP_ROUTE_CHANGED` path clears authenticated/gameplay state instead of preserving the older route. @@ -95,13 +95,13 @@ The legacy Automation `PATCH /factions/{id}/reputation` controller has been remo ### Recorded Proof -The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. These are historical validation facts; the decision review did not rerun them. +The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The local Account `JOIN` operation and Game Session scope/translation seam are implementation evidence, not full bridge proof. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove the complete `WORLDS`, `REALMS`, `JOIN`, and post-join path, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. These are historical validation facts; the decision review did not rerun them. ## Active Gaps - 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` remains unimplemented. Current connect-token issuance and `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and never create membership; an eligible public-production response with `membershipExists=false` may return `JOIN_REQUIRED`. For non-public membership, connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED`. An existing non-admitting response cannot be classified as `INACTIVE` because the live adapter does not expose lifecycle state. The target membership-authority-generation reread at issuance remains a gap. +- Explicit `JOIN`/`Join & Play` now has a local Account operation and Game Session scope/translation seam, but the complete bridge remains unproved. Current connect-token issuance and `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and never create membership; an eligible public-production response with `membershipExists=false` may return `JOIN_REQUIRED`. For non-public membership, connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED`. An existing non-admitting response cannot be classified as `INACTIVE` because the live adapter does not expose lifecycle state. 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. - 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/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 2cc5163dc2..09ee362dba 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -4128,6 +4128,34 @@ def assert_paths_and_mount(container, service, cert_path, key_path): fail(f"Deployment/{service} grpc-tls must mount read-only at /tls") +def allows_shared_namespace_identity(service, env): + namespace_identity = env.get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") + expected_namespace_identity = { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + } + if service == "logging-admin-service": + return namespace_identity == expected_namespace_identity + return namespace_identity is None + + +# The exact downward-API namespace identity is valid only for Logging & Admin +# among shared transports; every other shared service must reject this shape. +negative_shared_namespace_fixture = { + "FIREMUD_GRPC_WORKLOAD_NAMESPACE": { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + } +} +for service in shared_services: + if service != "logging-admin-service" and allows_shared_namespace_identity( + service, negative_shared_namespace_fixture + ): + fail( + f"shared namespace identity fixture unexpectedly accepted for {service}" + ) + + for service in distinct_workload_services: deployment = deployment_for(service) container, pod_spec = workload_container(deployment, service) @@ -4164,7 +4192,13 @@ for service in shared_services: deployment = deployment_for(service) container, pod_spec = workload_container(deployment, service) assert_paths_and_mount(container, service, "/tls/client.crt", "/tls/client.key") - if "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in env_map(container, service): + env = env_map(container, service) + if not allows_shared_namespace_identity(service, env): + if service == "logging-admin-service": + fail( + f"Deployment/{service} must derive FIREMUD_GRPC_WORKLOAD_NAMESPACE " + "from metadata.namespace" + ) fail( f"Deployment/{service} shared transport unexpectedly declares " "FIREMUD_GRPC_WORKLOAD_NAMESPACE" From c9cfe3899f0609b06d36fcebdee2854aeb781ff4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 13:49:14 +1200 Subject: [PATCH 06/55] Converge JOIN realm identity on UUID and correct Account proof status --- .../account-service/api-contracts.md | 6 +- .../account-service/runtime-and-data.md | 4 +- .../accountservice/dto/AccountJoinDigest.java | 4 +- .../accountservice/dto/BootstrapRealmDto.java | 1 + .../dto/DirectTextCallerContext.java | 4 +- .../dto/DirectTextJoinTarget.java | 4 +- .../accountservice/dto/VerifiedJoinScope.java | 4 +- .../AccountJoinOperationRepository.java | 3 + .../service/impl/AccountGrpcService.java | 22 +- .../service/impl/AccountServiceImpl.java | 39 +++- ...V26__global_registration_join_evidence.sql | 8 +- .../src/main/resources/openapi.yaml | 4 + .../AccountRepositoryIntegrationTest.java | 38 +++- .../controller/AuthControllerTest.java | 2 + .../dto/AccountJoinDigestTest.java | 31 ++- .../service/impl/AccountGrpcServiceTest.java | 70 +++++- .../service/impl/AccountServiceImplTest.java | 209 +++++++++++++++--- ...ionAccountCrossServiceIntegrationTest.java | 3 +- 18 files changed, 384 insertions(+), 72 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 92867d7a07..45ff2a4ecb 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response remains the four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. 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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain 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. ### Current vs Target Export Lifecycle @@ -109,7 +109,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the response is the four-field admission shape documented above and does not expose lifecycle state or `membershipAuthorityGeneration`. **Target-only:** the response adds `membershipLifecycleState` and opaque `membershipAuthorityGeneration`, with the independent `membershipVersion`, from one fresh atomic Account membership snapshot. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. @@ -189,7 +189,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 four-field membership response, 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 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/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 fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. 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. Exact-final-head PostgreSQL proof, recovery/reconciliation after an unknown commit outcome, 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/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index b01a047e7c..9c820d421c 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -20,7 +20,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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit 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 response cannot distinguish `INACTIVE` from another existing non-admitting lifecycle state. These paths do not create or restore membership. 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. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains open; no Overseer decision is implied. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit 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. These paths do not create or restore membership. 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. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains open; no Overseer decision is implied. 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` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. @@ -176,7 +176,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`. Current generated proto, Account implementation, and runtime callers do not yet expose and prove every target field, including `membershipLifecycleState`, `authorityAvailability`, and the opaque generation; that remains 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 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. - `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/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java index f205f4711d..bf2147fa79 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java @@ -16,7 +16,7 @@ public static String scope(VerifiedJoinScope scope) { + "targetClass=PUBLIC_PRODUCTION\n" + field("connectScopeId", scope.connectScopeId()) + field("tenantId", scope.tenantId()) - + field("realmId", scope.realmId()) + + field("realmId", scope.realmId().toString()) + field("worldSlug", scope.worldSlug()) + field("realmSlug", scope.realmSlug()) + field("playableStateNamespaceId", scope.playableStateNamespaceId()) @@ -67,7 +67,7 @@ public static String intent(String requestId, VerifiedJoinScope scope, String ca + field("tenantId", scope.tenantId()) + field("worldSlug", scope.worldSlug()) + field("realmSlug", scope.realmSlug()) - + field("realmId", scope.realmId()) + + field("realmId", scope.realmId().toString()) + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + field("playableStateScope", scope.playableStateScope()) + field("gameInstanceId", scope.gameInstanceId()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java index 796fe0ad76..51b97cb66e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java @@ -4,6 +4,7 @@ public record BootstrapRealmDto( String worldSlug, String realmSlug, + String realmId, String displayName, long tenantId, long gameInstanceId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java index 6978876722..2638dc9cfb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.accountservice.dto; +import java.util.UUID; + /** Parsed scope data from a verified Game Session mTLS call, never an independent capability. */ public record DirectTextCallerContext( long accountId, long tenantId, - long realmId, + UUID realmId, String playableStateNamespaceId, String playableStateScope, long gameInstanceId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java index ad036ab1cb..b4273bf5b5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java @@ -1,11 +1,13 @@ package net.firedevops.firemud.accountservice.dto; +import java.util.UUID; + /** * Game Session's complete selected-target evidence, re-resolved by Account before scope issuance. */ public record DirectTextJoinTarget( long tenantId, - long realmId, + UUID realmId, String worldSlug, String realmSlug, String playableStateNamespaceId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java index 84fd71c5fe..3d96e8c217 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java @@ -1,11 +1,13 @@ package net.firedevops.firemud.accountservice.dto; +import java.util.UUID; + /** Immutable Account-owned target snapshot retained for an explicit public-production JOIN. */ public record VerifiedJoinScope( String connectScopeId, long accountId, long tenantId, - long realmId, + UUID realmId, String worldSlug, String realmSlug, String playableStateNamespaceId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index 81886acf15..a43a4b536b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -5,6 +5,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import org.jooq.DSLContext; import org.springframework.stereotype.Repository; @@ -210,6 +211,7 @@ public void recordCallerBoundAuthorityInvalidation(String requestId) { public record JoinOperation( long accountId, long tenantId, + UUID realmId, String callerBinding, String scopeTokenHash, String connectScopeDigest, @@ -233,6 +235,7 @@ private static JoinOperation toJoinOperation( return new JoinOperation( row.getAccountId(), row.getTenantId(), + row.getRealmId(), row.getVerifiedCallerBinding(), row.getScopeTokenHash(), row.getConnectScopeDigest(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 903585fbca..769e404424 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -4,6 +4,7 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -103,10 +104,10 @@ public void issueDirectTextConnectScope( requireGameSessionPeer(); DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); - long realmId = requirePositiveRequestId(request.getRealmId(), "realmId"); + UUID realmId = requireCanonicalRealmId(request.getRealmId()); long gameInstanceId = requirePositiveRequestId(request.getGameInstanceId(), "gameInstanceId"); if (caller.tenantId() != tenantId - || caller.realmId() != realmId + || !caller.realmId().equals(realmId) || caller.gameInstanceId() != gameInstanceId || !caller.playableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) || !caller.playableStateScope().equals(request.getPlayableStateScope())) { @@ -198,7 +199,7 @@ private DirectTextCallerContext directTextCaller( return new DirectTextCallerContext( requirePositiveRequestId(context.getAccountId(), "accountId"), requirePositiveRequestId(context.getTenantId(), "tenantId"), - requirePositiveRequestId(context.getRealmId(), "realmId"), + requireCanonicalRealmId(context.getRealmId()), requireText(context.getPlayableStateNamespaceId(), "playableStateNamespaceId"), requireText(context.getPlayableStateScope(), "playableStateScope"), requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"), @@ -206,6 +207,21 @@ private DirectTextCallerContext directTextCaller( context.getRequestId()); } + private UUID requireCanonicalRealmId(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("realmId is required"); + } + try { + UUID realmId = UUID.fromString(value); + if (!realmId.toString().equals(value)) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + return realmId; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("realmId must be a canonical UUID", ex); + } + } + private String requireText(String value, String fieldName) { int maxLength = "connectScopeId".equals(fieldName) ? 2048 : 128; if (value == null || value.isBlank() || value.length() > maxLength) { 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 db0338c25b..018319b58b 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 @@ -396,6 +396,7 @@ public List listBootstrapRealms(String bootstrapToken, String new BootstrapRealmDto( realm.worldSlug(), realm.realmSlug(), + realm.realmId().toString(), realm.displayName(), realm.tenantId(), realm.gameInstanceId(), @@ -470,7 +471,7 @@ public DirectTextJoinScope issueDirectTextConnectScope( || target == null || caller.accountId() <= 0L || caller.tenantId() != target.tenantId() - || caller.realmId() != target.realmId() + || !caller.realmId().equals(target.realmId()) || caller.gameInstanceId() != target.gameInstanceId() || !caller.playableStateNamespaceId().equals(target.playableStateNamespaceId()) || !caller.playableStateScope().equals(target.playableStateScope())) { @@ -483,7 +484,7 @@ public DirectTextJoinScope issueDirectTextConnectScope( throw new AuthenticationException( "REALM_UNAVAILABLE", "Selected public realm is unavailable"); } - if (current.realmId() != target.realmId() + if (!current.realmId().equals(target.realmId()) || !current.playableStateNamespaceId().equals(target.playableStateNamespaceId()) || !current.stateScope().equals(target.playableStateScope()) || current.gameInstanceId() != target.gameInstanceId() @@ -785,7 +786,7 @@ private void validateSignedJoinScope( if (retained.accountId() != accountId || signedScope.accountId() != accountId || signedScope.tenantId() != retained.tenantId() - || signedScope.realmId() != retained.realmId() + || !signedScope.realmId().equals(retained.realmId()) || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) || !signedScope.playableStateScope().equals(retained.playableStateScope()) || signedScope.gameInstanceId() != retained.gameInstanceId() @@ -806,6 +807,7 @@ private void requireMatchingJoinIntent( JoinOperation operation, String requestId, String callerBinding, VerifiedJoinScope scope) { String expectedIntentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); if (operation.accountId() != scope.accountId() + || !operation.realmId().equals(scope.realmId()) || !operation.callerBinding().equals(callerBinding) || !operation.scopeTokenHash().equals(AccountJoinDigest.tokenHash(scope.connectScopeId())) || !operation.connectScopeDigest().equals(scope.snapshotDigest()) @@ -889,7 +891,7 @@ private void validateDirectTextJoinScope( if (caller != null && (caller.accountId() != scope.accountId() || caller.tenantId() != scope.tenantId() - || caller.realmId() != scope.realmId() + || !caller.realmId().equals(scope.realmId()) || caller.gameInstanceId() != scope.gameInstanceId() || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) || !caller.playableStateScope().equals(scope.playableStateScope()))) { @@ -1303,7 +1305,7 @@ private RuntimeRealmTarget requireRealmTarget( readRuntimeRealmTarget( gameSessionClient.getAdmissionPointer(candidate.tenantId(), worldSlug, realmSlug)); if (realm.tenantId() != candidate.tenantId() - || realm.realmId() != candidate.realmId() + || !realm.realmId().equals(candidate.realmId()) || !realm.playableStateNamespaceId().equals(candidate.playableStateNamespaceId()) || !realm.stateScope().equals(candidate.stateScope()) || realm.gameInstanceId() != candidate.gameInstanceId() @@ -1372,7 +1374,7 @@ private String mintConnectScopeId( Map.entry("aud", "bootstrap-connect-scope"), Map.entry("accountId", bootstrapContext.accountId()), Map.entry("tenantId", realm.tenantId()), - Map.entry("realmId", realm.realmId()), + Map.entry("realmId", realm.realmId().toString()), Map.entry("worldSlug", realm.worldSlug()), Map.entry("realmSlug", realm.realmSlug()), Map.entry("playableStateNamespaceId", realm.playableStateNamespaceId()), @@ -1457,7 +1459,7 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { return new ConnectScopeContext( routingClaims.accountId(), routingClaims.tenantId(), - requirePositiveLong(claims.get("realmId"), "realmId"), + requireCanonicalRealmId(claims.get("realmId")), routingClaims.worldSlug(), routingClaims.realmSlug(), JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"), @@ -1521,7 +1523,7 @@ private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext requireRealmTarget( scopeContext.tenantId(), scopeContext.worldSlug(), scopeContext.realmSlug()); if (currentRealm.tenantId() != scopeContext.tenantId() - || currentRealm.realmId() != scopeContext.realmId() + || !currentRealm.realmId().equals(scopeContext.realmId()) || !currentRealm.playableStateNamespaceId().equals(scopeContext.playableStateNamespaceId()) || !currentRealm.stateScope().equals(scopeContext.playableStateScope()) || currentRealm.gameInstanceId() != scopeContext.gameInstanceId() @@ -2163,7 +2165,7 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( boolean requiresCharacterSelection, String displayName) { long tenantId = requirePositiveLong(tenantIdText, "tenantId"); - long realmId = requirePositiveLong(realmIdText, "realmId"); + UUID realmId = requireCanonicalRealmId(realmIdText); long gameInstanceId = requirePositiveLong(gameInstanceIdText, "gameInstanceId"); if (!StringUtils.hasText(playableStateNamespaceId)) { throw new IllegalArgumentException("playableStateNamespaceId is required"); @@ -2214,10 +2216,25 @@ private long requirePositiveLong(Object value, String field) { return JwtClaims.requireLong(value, field, false); } + private UUID requireCanonicalRealmId(Object value) { + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + try { + UUID realmId = UUID.fromString(text); + if (!realmId.toString().equals(text)) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + return realmId; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("realmId must be a canonical UUID", ex); + } + } + private record ConnectScopeContext( long accountId, long tenantId, - long realmId, + UUID realmId, String worldSlug, String realmSlug, String playableStateNamespaceId, @@ -2230,7 +2247,7 @@ private record ConnectScopeContext( private record RuntimeRealmTarget( long tenantId, - long realmId, + UUID realmId, String playableStateNamespaceId, long gameInstanceId, String worldSlug, diff --git a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql index 46191a87b5..dc0f1647d5 100644 --- a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql +++ b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql @@ -126,7 +126,7 @@ CREATE TABLE account_connect_scope_records ( account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, target_class VARCHAR(20) NOT NULL, tenant_id BIGINT NOT NULL, - realm_id BIGINT NOT NULL, + realm_id UUID NOT NULL, world_slug VARCHAR(128) NOT NULL, realm_slug VARCHAR(128) NOT NULL, playable_state_namespace_id VARCHAR(128) NOT NULL, @@ -146,7 +146,7 @@ CREATE TABLE account_connect_scope_records ( OR (target_class = 'NON_PUBLIC' AND playtest_lifecycle_id IS NOT NULL AND playtest_state_generation > 0)), CONSTRAINT account_connect_scope_positive_check - CHECK (tenant_id > 0 AND realm_id > 0 AND game_instance_id > 0 + CHECK (tenant_id > 0 AND game_instance_id > 0 AND catalog_revision > 0 AND pointer_version > 0) ); @@ -162,7 +162,7 @@ CREATE TABLE account_join_operations ( connect_scope_digest VARCHAR(71) NOT NULL, world_slug VARCHAR(128) NOT NULL, realm_slug VARCHAR(128) NOT NULL, - realm_id BIGINT NOT NULL, + realm_id UUID NOT NULL, playable_state_namespace_id VARCHAR(128) NOT NULL, playable_state_scope VARCHAR(32) NOT NULL, game_instance_id BIGINT NOT NULL, @@ -188,7 +188,7 @@ CREATE TABLE account_join_operations ( CONSTRAINT account_join_operation_status_check CHECK (status IN ('PENDING', 'COMMITTED', 'FAILED')), CONSTRAINT account_join_operation_positive_versions_check - CHECK (tenant_id > 0 AND realm_id > 0 AND game_instance_id > 0 AND catalog_revision > 0 + CHECK (tenant_id > 0 AND game_instance_id > 0 AND catalog_revision > 0 AND pointer_version > 0 AND (entitlement_version IS NULL OR entitlement_version > 0)), CONSTRAINT account_join_operation_policy_evidence_check diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 996a80163b..85d5db9ef7 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -177,11 +177,15 @@ components: type: string BootstrapRealmDto: type: object + required: [worldSlug, realmSlug, realmId] properties: worldSlug: type: string realmSlug: type: string + realmId: + type: string + format: uuid displayName: type: string tenantId: 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 f22a7e9192..6517d4d00a 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 @@ -38,6 +38,7 @@ @SuppressWarnings("resource") @TestInstance(TestInstance.Lifecycle.PER_CLASS) class AccountRepositoryIntegrationTest { + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); private static final String MIGRATION_PROOF_SCHEMA = "account_migration_proof"; @@ -104,8 +105,15 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { status -> joinOperations.insertIntent(requestId, scope, callerBinding, intentDigest)); assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("PENDING"); + assertThat(joinOperation(joinOperations, requestId).realmId()).isEqualTo(REALM_ID); assertThat(joinOperation(joinOperations, requestId).outcome()).isNull(); assertThat(joinOperation(joinOperations, requestId).intentDigest()).isEqualTo(intentDigest); + assertThat( + jdbc.queryForObject( + "SELECT realm_id FROM account_join_operations WHERE request_id = ?", + UUID.class, + requestId)) + .isEqualTo(REALM_ID); assertThat(joinOperation(joinOperations, requestId).requestDigest()).isNull(); assertThat(joinOperation(joinOperations, requestId).entitlementVersion()).isNull(); assertThat(joinOperation(joinOperations, requestId).allowPublicJoin()).isNull(); @@ -182,6 +190,34 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { .isEqualTo(1L); } + @Test + void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "scope-uuid", + "scope-uuid@example.com", + "hash")); + AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(dsl); + VerifiedJoinScope scope = joinScope(accountId); + + scopes.insert(scope); + + assertThat(scopes.find(scope.connectScopeId()).orElseThrow().realmId()).isEqualTo(REALM_ID); + UUID changedRealmId = UUID.fromString("57c58f36-c5ea-4aa8-8ef7-91a45e407f01"); + jdbc.update( + "UPDATE account_connect_scope_records SET realm_id = ? WHERE scope_token_hash = ?", + changedRealmId, + AccountJoinDigest.tokenHash(scope.connectScopeId())); + + assertThatThrownBy(() -> scopes.find(scope.connectScopeId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("JOIN scope digest mismatch"); + } + private void commitJoinOutcome( AccountJoinOperationRepository joinOperations, AccountTenantMembershipRepository memberships, @@ -231,7 +267,7 @@ private static VerifiedJoinScope joinScope(long accountId) { "two-phase-connect-scope", accountId, 7L, - 31L, + REALM_ID, "demo", "production", "namespace-44", 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 4b9d9e131c..926a4dc7a4 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 @@ -170,6 +170,7 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { new BootstrapRealmDto( "demo", "production", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", "Live Realm", 1L, 42L, @@ -188,6 +189,7 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) .andExpect(jsonPath("$.data[0].realmSlug").value("production")) + .andExpect(jsonPath("$.data[0].realmId").value("4c4b57d8-e3a2-48fe-9977-e7df0fdce901")) .andExpect(jsonPath("$.data[0].connectScopeId").value("scope-1")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java index a068abc0b7..0a9a029857 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java @@ -4,15 +4,18 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.UUID; import org.junit.jupiter.api.Test; class AccountJoinDigestTest { + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + @Test void scopeAndRequestDigestsMatchUtf8CanonicalVectors() { VerifiedJoinScope scope = scope("scope-token-α", "production"); assertEquals( - "sha256:3ecdb49d051fb18e9e925031da8245504af61d956993b5b44fc7b4f0781b0da6", + "sha256:15efd695569eca4a26589922c7ad128c3a2318203d1a2181666cc3ed6650f5b8", AccountJoinDigest.scope(scope)); assertEquals( "sha256:764b03cbe948293517acb4ce201dbd24fc4d2a0a2306e853f2ab0a6c3775a768", @@ -29,12 +32,16 @@ void scopeAndRequestDigestsMatchUtf8CanonicalVectors() { assertNotEquals( AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), AccountJoinDigest.request(withGameInstance(scope, 45L), "bootstrap-jti-α", true, 5L)); + assertNotEquals( + AccountJoinDigest.scope(scope), + AccountJoinDigest.scope( + withRealm(scope, UUID.fromString("57c58f36-c5ea-4aa8-8ef7-91a45e407f01")))); assertThrows( IllegalArgumentException.class, () -> AccountJoinDigest.request(scope, "bootstrap-jti-α", null, null)); assertEquals( - "sha256:d6cfe1a2c241a63bdb0f5c381e18fddae1f00431da5f27cbfbf0f0a4b9748a3b", + "sha256:13445ed45c66f0e149250f4101c95452a74f15e56dbf3b9b271852ff2d058776", AccountJoinDigest.intent("join-request-α", scope, "bootstrap-jti-α")); } @@ -73,12 +80,30 @@ private static VerifiedJoinScope withGameInstance(VerifiedJoinScope scope, long scope.snapshotDigest()); } + private static VerifiedJoinScope withRealm(VerifiedJoinScope scope, UUID realmId) { + return new VerifiedJoinScope( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + realmId, + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.snapshotDigest()); + } + private static VerifiedJoinScope scope(String connectScopeId, String realmSlug) { return new VerifiedJoinScope( connectScopeId, 11L, 7L, - 31L, + REALM_ID, "demo", realmSlug, "namespace-44", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 4ee72fda64..f475c9a892 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -9,6 +9,7 @@ import io.grpc.stub.StreamObserver; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -58,10 +59,14 @@ import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class AccountGrpcServiceTest { private static final String WORKLOAD_NAMESPACE = "test"; + private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; private static final GrpcPeerIdentity GAME_SESSION_PEER = new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/game-session-service", @@ -72,7 +77,7 @@ private static PlayerExecutionContext validPlayerContext() { return PlayerExecutionContext.newBuilder() .setAccountId("10") .setTenantId("20") - .setRealmId("30") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("realm-state-30") .setPlayableStateScope("realm:30") .setGameInstanceId("40") @@ -85,7 +90,7 @@ private static IssueDirectTextConnectScopeRequest validScopeRequest() { return IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(validPlayerContext()) .setTenantId("20") - .setRealmId("30") + .setRealmId(REALM_ID) .setWorldSlug("world") .setRealmSlug("public") .setPlayableStateNamespaceId("realm-state-30") @@ -171,9 +176,24 @@ void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { Mockito.verify(accountService) .issueDirectTextConnectScope( new DirectTextCallerContext( - 10L, 20L, 30L, "realm-state-30", "realm:30", 40L, "session-1", "request-1"), + 10L, + 20L, + UUID.fromString(REALM_ID), + "realm-state-30", + "realm:30", + 40L, + "session-1", + "request-1"), new DirectTextJoinTarget( - 20L, 30L, "world", "public", "realm-state-30", "realm:30", 40L, 5L, 8L)); + 20L, + UUID.fromString(REALM_ID), + "world", + "public", + "realm-state-30", + "realm:30", + 40L, + 5L, + 8L)); } @Test @@ -206,7 +226,14 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { Mockito.verify(accountService) .joinPublicProductionFromGameSession( new DirectTextCallerContext( - 10L, 20L, 30L, "realm-state-30", "realm:30", 40L, "session-1", "request-1"), + 10L, + 20L, + UUID.fromString(REALM_ID), + "realm-state-30", + "realm:30", + 40L, + "session-1", + "request-1"), new JoinPublicProductionRequest("scope-1", "request-1")); } @@ -254,7 +281,7 @@ void directTextMethodsRejectMalformedOrMismatchedTypedContextBeforeServiceCall() new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); IssueDirectTextConnectScopeRequest mismatchedTarget = - validScopeRequest().toBuilder().setRealmId("31").build(); + validScopeRequest().toBuilder().setRealmId(OTHER_REALM_ID).build(); PlayerExecutionContext malformedContext = validPlayerContext().toBuilder().setAccountId("NaN").build(); JoinPublicProductionMembershipRequest mismatchedJoin = @@ -285,6 +312,37 @@ void directTextMethodsRejectMalformedOrMismatchedTypedContextBeforeServiceCall() Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @ValueSource(strings = {"30", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void directTextScopeRejectsNoncanonicalRealmIdsAtBothIngressFields(String realmId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver targetObserver = + new RecordingObserver<>(); + RecordingObserver contextObserver = + new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder().setRealmId(realmId).build(), targetObserver)); + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder() + .setPlayerContext(validPlayerContext().toBuilder().setRealmId(realmId).build()) + .build(), + contextObserver)); + + assertEquals("INVALID_ARGUMENT", targetObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", contextObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void authenticateFailureReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); 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 27e1700bb4..34d5629028 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 @@ -12,6 +12,7 @@ import de.mkammerer.argon2.Argon2Factory; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -70,6 +71,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -79,6 +81,7 @@ class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; + private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; @Mock private AccountRepository accountRepository; @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @@ -150,7 +153,7 @@ void setup() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -169,7 +172,7 @@ void setup() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -327,6 +330,7 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { assertTrue(retried.success()); assertTrue(retried.replayed()); assertNotNull(onboardingToken.connectToken()); + assertEquals(REALM_ID, retainedScope.get().realmId().toString()); assertEquals( first, new JoinPublicProductionResult( @@ -620,7 +624,7 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans connectScopeId, 11L, 7L, - 101L, + UUID.fromString(REALM_ID), "demo", "production", "production-namespace-7", @@ -658,6 +662,7 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans new AccountJoinOperationRepository.JoinOperation( expiredScope.accountId(), expiredScope.tenantId(), + expiredScope.realmId(), callerBinding, net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), expiredScope.snapshotDigest(), @@ -718,6 +723,7 @@ void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { new AccountJoinOperationRepository.JoinOperation( 12L, scope.tenantId(), + scope.realmId(), "different-caller", net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), scope.snapshotDigest(), @@ -822,6 +828,7 @@ private void retainJoinEvidence( new AccountJoinOperationRepository.JoinOperation( scope.accountId(), scope.tenantId(), + scope.realmId(), callerBinding, net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( scope.connectScopeId()), @@ -855,6 +862,7 @@ private void retainJoinEvidence( new AccountJoinOperationRepository.JoinOperation( pending.accountId(), pending.tenantId(), + pending.realmId(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -888,6 +896,7 @@ private void retainJoinEvidence( new AccountJoinOperationRepository.JoinOperation( pending.accountId(), pending.tenantId(), + pending.realmId(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -921,6 +930,7 @@ private void retainJoinEvidence( new AccountJoinOperationRepository.JoinOperation( pending.accountId(), pending.tenantId(), + pending.realmId(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -1463,7 +1473,7 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { .setDisplayName("Broken Realm") .setTenantId("bad") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -1482,6 +1492,43 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); } + @ParameterizedTest + @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { + 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(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(realmId) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + assertThrows( + IllegalArgumentException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + } + @Test void issueConnectTokenRejectsMalformedConnectScopeId() { Account account = new Account(); @@ -1646,6 +1693,59 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); } + @ParameterizedTest + @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { + 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 malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "11", + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", "11"), + Map.entry("tenantId", "7"), + Map.entry("realmId", realmId), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", "production-namespace-7"), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "44"), + Map.entry("catalogRevision", "23"), + Map.entry("pointerVersion", "17"), + Map.entry("evaluatedAt", java.time.Instant.now().toString()), + Map.entry( + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString()), + Map.entry("jti", "invalid-realm-id"))); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-invalid-realm-id"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + @Test void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { Account account = new Account(); @@ -2096,7 +2196,7 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(18L) @@ -2150,7 +2250,7 @@ void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2208,7 +2308,7 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { .setDisplayName("Live Realm") .setTenantId("") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2270,7 +2370,7 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(18L) @@ -2463,7 +2563,7 @@ void issueConnectTokenKeepsGenericMembershipRejectionDistinctFromBillingDenial() .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(19L) @@ -2482,7 +2582,7 @@ void issueConnectTokenKeepsGenericMembershipRejectionDistinctFromBillingDenial() .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(19L) @@ -2556,7 +2656,7 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(18L) @@ -2591,7 +2691,7 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2728,7 +2828,7 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2781,7 +2881,7 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2820,6 +2920,13 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); assertEquals(1, realms.size()); + assertEquals(REALM_ID, realms.getFirst().realmId()); + assertEquals( + REALM_ID, + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(realms.getFirst().connectScopeId()) + .getPayload() + .get("realmId")); assertEquals("SHARED", realms.getFirst().stateScope()); assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); } @@ -2843,7 +2950,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setDisplayName("Broken Realm") .setTenantId("bad") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2859,7 +2966,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2898,7 +3005,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2917,7 +3024,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -2974,7 +3081,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("bad") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -3022,7 +3129,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -3069,7 +3176,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -3088,7 +3195,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -3107,7 +3214,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -3167,7 +3274,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setDisplayName("Tenant Seven") .setTenantId("7") .setGameInstanceId("44") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(17L) @@ -3182,7 +3289,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setDisplayName("Tenant Eight") .setTenantId("8") .setGameInstanceId("45") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-8") .setCatalogRevision(23L) .setPointerVersion(18L) @@ -3249,6 +3356,44 @@ void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { verifyNoInteractions(entityManagementClient); } + @Test + void listBootstrapCharactersRejectsChangedCanonicalRealmId() { + 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))); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + net.firedevops.firemud.gamesession.v1.GameplayRealm changedRealm = + gameSessionClient.listGameplayRealms("demo").getFirst().toBuilder() + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .build(); + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer changedAdmissionPointer = + gameSessionClient.getAdmissionPointer(7L, "demo", "production").toBuilder() + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .build(); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn(changedAdmissionPointer); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + verifyNoInteractions(entityManagementClient); + } + @Test void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { Account account = new Account(); @@ -3273,7 +3418,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(19L) @@ -3321,7 +3466,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(19L) @@ -3340,7 +3485,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(19L) @@ -3384,7 +3529,7 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(19L) @@ -3446,7 +3591,7 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(19L) @@ -3465,7 +3610,7 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-7") .setCatalogRevision(23L) .setPointerVersion(19L) @@ -3920,7 +4065,7 @@ private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer ad .setRealmDisplayName("production".equals(realmSlug) ? "Live Realm" : "Preview Realm") .setTenantId(Long.toString(tenantId)) .setGameInstanceId(gameInstanceId) - .setRealmId("101") + .setRealmId(REALM_ID) .setPlayableStateNamespaceId("production-namespace-" + tenantId) .setCatalogRevision(23L) .setPointerVersion(pointerVersion) 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 646ae51929..9098ae04f9 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 @@ -158,8 +158,7 @@ void telnetLoginAndLookMatchTransportFlowWithoutSession() throws Exception { .anyMatch( request -> request.getEmail().equals(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL) - && request.getPassword().equals(GameplayTelnetScenarios.DEMO_PASSWORD) - && request.getTenantId().equals(String.valueOf(TENANT_ID))); + && request.getPassword().equals(GameplayTelnetScenarios.DEMO_PASSWORD)); } @Test From 2f83d4364c12a1d3736088899264044390f8fa05 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 13:49:36 +1200 Subject: [PATCH 07/55] Clarify frontend JOIN implementation and proof status --- design/architecture/system-architecture-frontend.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 1c61352bf7..88effcd891 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -20,7 +20,7 @@ The first-party browser consumes the existing Account/Gateway APIs and the versi The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output, but the independently released static host, public-site routing and delivery (including the target `/auth/**` rewrite), health/security/cache behavior, rollback, and bounded end-to-end browser proof are not implemented or proved. Those gaps remain target implementation obligations rather than evidence that the supported frontend boundary is live. -Explicit `JOIN`/`Join & Play` is target behavior, not a complete current runtime flow. In the target, `JoinPublicProductionMembership` is the sole membership writer for explicit public-production join, creating missing membership or restoring `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current membership response exposes only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; current connect-token issuance and text `PLAY` proceed only when the two admission fields are true, and an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. The obsolete implicit membership-writer surface has been removed. Explicit `JOIN`/`Join & Play` and the required connect-token `membershipVersion` plus `membershipAuthorityGeneration` reread remain unimplemented/proof gaps, so the current fail-closed result must not be read as an actionable join flow or as proof that the complete target sequence is implemented. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. The frontend availability gate applies to the otherwise eligible current `membershipExists=false` or existing `gameplayAdmissionAllowed=false` cases; the latter cannot be classified as `INACTIVE`, and target lifecycle-specific handling of missing or `INACTIVE` membership remains target-only. Returning members and grant-backed private/playtest flows remain eligible only when the live membership response fields, grant, entitlement, and routing checks pass; target generation/version rereads remain unimplemented. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. +Explicit `JOIN`/`Join & Play` is implemented locally in the stacked Access draft, but the complete target runtime flow is not yet proved. In the target, `JoinPublicProductionMembership` is the sole membership writer for explicit public-production join, creating missing membership or restoring `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current membership response also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current consumers enforce only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; current connect-token issuance and text `PLAY` proceed only when the two admission fields are true, and an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the consumer does not classify the latter specifically as `INACTIVE` despite the emitted lifecycle field. The obsolete implicit membership-writer surface has been removed. The local explicit `JOIN` operation is not a production-ready frontend repair until UUID realm binding, retained-data deployment disposition, and end-to-end proof pass; the required connect-token `membershipVersion` plus `membershipAuthorityGeneration` reread remains an implementation/proof gap. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. The frontend availability gate applies to the otherwise eligible current `membershipExists=false` or existing `gameplayAdmissionAllowed=false` cases; the current consumer does not classify the latter as `INACTIVE`, and target lifecycle-specific handling of missing or `INACTIVE` membership remains incomplete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership response fields, grant, entitlement, and routing checks pass; target generation/version rereads remain unimplemented. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. The explicit `JOIN`/`Join & Play` action and the independent `membershipVersion` plus `membershipAuthorityGeneration` reread at connect-token issuance are both unimplemented/proof gaps. Until both are implemented and proven, the frontend must keep first public-production entry with a missing or non-admitting current membership response fail-closed and unavailable rather than exposing a retry path that can create membership implicitly or issue a token from stale authority. Returning members and private/playtest callers with existing membership remain eligible when the live response fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and the other current admission checks pass; the exact `membershipAuthorityGeneration` and independent issuance-time `membershipVersion` rereads remain target/proof gaps. Target lifecycle-specific handling of missing or `INACTIVE` membership remains unavailable until that target response exists. This status is the frontend summary of the target/current distinction in [Authentication & Authorization](./system-architecture-authentication.md#implementation-status). @@ -98,7 +98,7 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - Target first-party clients use one of two explicit gameplay flows: - **Returning member:** `POST /auth/player-bootstrap` -> bootstrap discovery -> bootstrap-authenticated character discovery/creation -> `POST /auth/connect-token` with the discovery-provided `connectScopeId` -> `/ws/game/**` -> bare `LOGIN` -> `PLAY`. This flow requires the selected existing caller-bound membership and does not call `/auth/bootstrap/join`. - **First join:** `POST /auth/player-bootstrap` -> public-production discovery -> `POST /auth/bootstrap/join` -> rerun public-production realm discovery -> use the new complete `{connectScopeId, tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` snapshot for bootstrap-authenticated character discovery/creation -> `POST /auth/connect-token` with that new snapshot's `connectScopeId` -> `/ws/game/**` -> bare `LOGIN` -> `PLAY`. This public-production, non-grant snapshot intentionally omits both `playtestLifecycleId` and `playtestStateGeneration`; private/playtest snapshots include both fields. `/auth/bootstrap/join` may create missing membership or restore `INACTIVE` membership and must commit it against the exact `{catalogRevision, pointerVersion}` pair before the post-join discovery, character discovery, character creation, or connect-token issuance; no later step may create membership implicitly. The join transition emits one audit/outbox event for create or restore; an `ACTIVE` retry is event-free. - - The first-join, returning-player, reconnect, resume, grant-backed private/playtest, and related gameplay-admission descriptions in this section are target-state contracts, not confirmed current supported behavior. Current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they proceed only when the two admission fields are true and may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. That current `JOIN_REQUIRED` result is non-actionable while explicit `JOIN` / `Join & Play` is unimplemented; the frontend must not expose it as an available repair action. The obsolete implicit membership-writer surface has been removed; the required `membershipAuthorityGeneration` plus `membershipVersion` reread at connect-token issuance remains an unimplemented/proof gap. Current returning-member behavior may proceed when the existing live membership/character checks pass, but it does not prove the target exact generation/version reread; the target requires both independent values from one fresh membership snapshot. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`; the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Returning members and private/playtest callers with existing membership plus the current grant remain eligible only when their current runtime checks pass. The target descriptions remain the behavior to implement. + - The first-join, returning-player, reconnect, resume, grant-backed private/playtest, and related gameplay-admission descriptions in this section are target-state contracts, not confirmed current supported behavior. Current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they proceed only when the two admission fields are true and may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the consumer does not classify the latter specifically as `INACTIVE`. Explicit `JOIN` / `Join & Play` is implemented locally, but the frontend must not advertise `JOIN_REQUIRED` as a production-ready repair until UUID realm binding, retained-data disposition, and end-to-end proof pass. The obsolete implicit membership-writer surface has been removed; enforcement of emitted `membershipAuthorityGeneration` alongside `membershipVersion` at connect-token issuance remains an implementation/proof gap. Current returning-member behavior may proceed when the existing live membership/character checks pass, but it does not prove the target exact generation/version reread; the target requires both independent values from one fresh membership snapshot. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`; the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Returning members and private/playtest callers with existing membership plus the current grant remain eligible only when their current runtime checks pass. The target descriptions remain the behavior to implement. - For every `POST /auth/connect-token` issuance, including the first issuance immediately after explicit join and both returning-member and grant-backed private/playtest flows, the service must independently validate the scalar `membershipVersion` returned by `GetTenantMembershipForRuntime` for the selected `{accountId, tenantId}` and the `membershipAuthorityGeneration` from that same authoritative membership snapshot. It must compare both values independently with the selected admission baseline, bind the scalar `membershipVersion` and generation into the connect-token issuance/binding evidence, and fail closed when either value is missing, stale, mismatched, unavailable, or assembled from another snapshot; a current grant never substitutes for the membership-version validation. - Browser and mobile-browser clients receive the short-lived `Firemud-Connect-Token` HttpOnly cookie used by the `/ws/game/**` handshake; first-party native-mobile clients using a cookie jar remain cookie-only. This protected-cookie path is the current supported path to bare `LOGIN`. Explicitly classified non-first-party/public non-browser clients are target-only and unavailable until their dedicated issuance route is fully registered and proven; the conditional target carrier is protected secure storage plus `X-Firemud-Connect-Token`, not a fallback for the current cookie path. The client then opens `/ws/game/**` and completes gameplay authentication by issuing `LOGIN` over the WebSocket channel using the already-verified bootstrap/connect context; Game Session must validate the complete context, including the direct `realmId`, before using any field for `LOGIN`, `PLAY`, or scope comparison. The browser never prompts for or replays Telnet-style `LOGIN [secret]` credentials, as described in [Authentication & Authorization](./system-architecture-authentication.md#login-and-session-flow). - Browser transport constraints matter: a browser WebSocket cannot set arbitrary custom handshake headers the way Telnet smart clients, Mudlet integrations, or server-side clients can. The first-party browser flow therefore uses the `Firemud-Connect-Token` cookie set by `POST /auth/connect-token` with `HttpOnly`, `Secure`, `SameSite=Strict`, `Path=/ws/game`, and `Max-Age` no longer than the connect-token TTL. The React client must not read or persist the connect token itself; it only consumes non-secret response metadata such as `expiresAt`, `tenantId`, `realmId`, `realmSlug`, and `gameInstanceId`. Query parameters must never carry connect tokens or other authentication credentials; non-secret bootstrap discovery selectors such as `connectScopeId` may be sent as query parameters. Clients must obtain a fresh token after any failed attempt that may have consumed it. After Account has durably committed an issuance result or Gateway has consumed its token, any new token issuance requires a new `requestId`; the old `requestId` may only reconcile that same request while its outcome is `PENDING` or otherwise indeterminate and never mints a replacement token. @@ -108,7 +108,7 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - The target canonical player logout order is: stop reconnect attempts, capture the current `player-bootstrap` token into the pending-revocation slot, ask Account to durably commit the exact-token `PENDING` intent and immediately advance the exact-token issuance fence to `PENDING_LOGOUT` in that same durable step, then send gameplay `LOGOUT` and close the gameplay socket, ask Gateway to deny the gameplay-connect `jti` and clear the HttpOnly cookie, and finally ask Account to invalidate the underlying token and commit the `COMMITTED` tombstone. Account must establish the durable issuance fence before socket closure or any racing `/auth/connect-token` issuance can succeed; every issuance path rejects the fenced lineage rather than returning a usable late credential. Once `PENDING` is durable, Account must reject racing issuance, refresh, rebind, installation, and every unrelated reconciliation for that token lineage; only the exact matching Account lifecycle reconciliation may complete or abort that pending logout operation. `PENDING` is never success and remains resumable through that exact Account operation until terminal completion. If Gateway revoke is unavailable, Account must not report the edge deny/clear outcome as confirmed; clear only local reconnect/client state and rely on the bounded token lifetime; Gateway mitigation must not be reported as full logout when Account is unavailable or its fence is unconfirmed. The browser never directly clears the HttpOnly gameplay cookie; only a server response can clear that cookie. The target Gateway revoke call uses a two-second per-attempt timeout, at most two retries, and 250 ms then 500 ms backoff where time remains, but every request timeout and backoff is capped by the remaining five-second total deadline. This Gateway controller budget is independent and non-nested: it is not shared with or added to Account's revocation budget. Account revocation retains its separate policy of at most five attempts, a five-second timeout per attempt capped by a 30-second overall deadline, and full-jitter exponential backoff starting at 250 ms and capped at four seconds. The controller tracks Account PENDING, Gateway denial/clearing, and Account COMMITTED finalization as separate outcomes. It enters terminal `LOGGED_OUT_REVOKED` only after Account confirms the exact-token fence/Bootstrap-token revocation and Gateway confirms denial/clearing of the gameplay-connect token. Because Gateway gameplay-connect denial and cookie clearing are not currently routable, the current runtime cannot reach `LOGGED_OUT_REVOKED`; current logout flows terminate as `LOGGED_OUT_REVOCATION_UNCONFIRMED`. Account-only confirmation remains `LOGGED_OUT_REVOCATION_UNCONFIRMED` with edge revocation explicitly unconfirmed until Gateway confirms or the known gameplay-connect acceptance window ends; expiry closes that bounded edge risk but is reported as token-window expiry, not confirmed server revocation. Retry exhaustion, an unconfirmed Account result, or bootstrap-token expiry likewise remains `LOGGED_OUT_REVOCATION_UNCONFIRMED`, stays locally logged out, and requires a fresh `POST /auth/player-bootstrap` before any later gameplay flow. The frontend may retry only while the captured credential remains valid and its local retry deadline remains open. At the earlier of signed token expiry or that deadline, it wipes the raw credential and stops frontend retries while retaining only the opaque server-side logout handle and non-secret operation state needed to observe Account's durable reconciliation. Browser or process loss likewise destroys the memory-only credential and ends frontend retries, but neither local expiry nor frontend loss cancels the durable Account `PENDING` operation: Account's persisted operation and opaque logout handle are the authoritative revocation proof, and Account's reconciler continues exact-token revocation without the raw token. A raw credential may never be reused for gameplay/bootstrap calls, and retaining it in memory never extends its signed lifetime. Local clearing or process termination is not confirmed server revocation. - Logout invalidates the local bootstrap/connect-token request epoch and aborts every in-flight bootstrap, discovery, join, character, and connect-token request owned by that epoch. A late response is ignored for all client state transitions, but abort and epoch invalidation cannot guarantee that a late `Set-Cookie` was not already committed by the browser. The server-side logout issuance fence is therefore authoritative: Account rejects bootstrap or connect-token issuance that races a durable `PENDING` or `COMMITTED` logout for the same account/token lineage, and Gateway rejects a connect token whose deny/revocation fence wins before consumption. Where a logout response reaches the browser after the old issuance, the server must also return an explicit clearing or deny response so the late cookie cannot remain usable. The client must never treat ignored local state or local cookie clearing alone as proof of server revocation. - A server must reject an expired `Firemud-Connect-Token` cookie as `CONNECT_TOKEN_EXPIRED`, never fall back to a stale cookie, query parameter, or unapproved header, and return a clearing `Set-Cookie` response where the HTTP surface can do so. The browser cannot inspect the HttpOnly value; it discards the failed handshake attempt and obtains a fresh connect token only from a still-valid bootstrap session. If the bootstrap token is expired or revoked, the client restarts `POST /auth/player-bootstrap` and discovery instead of treating the expired cookie as a recoverable gameplay credential. - - Tenant membership, non-public realm-access-grant checks, and runtime entitlement checks occur after account bootstrap. The `player-bootstrap` token is still a tenant-free, non-gameplay bootstrap credential: it authorizes caller-bound discovery and the explicit join/connect-token APIs, but it does not itself carry or grant gameplay scope. The bounded `gameplay-connect` token is the only edge-admission credential carrying the selected target snapshot. In target behavior, a first public-production join presents an explicit `Join & Play` action that may create missing durable Account-owned membership or restore `INACTIVE` membership, before character creation and `POST /auth/connect-token`; connect-token issuance never creates membership implicitly. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. The obsolete implicit membership-writer surface has been removed, while explicit `JOIN` / `Join & Play` and the membership-authority-generation reread at issuance remain unimplemented/proof gaps. The frontend must mark the current otherwise eligible missing or existing non-admitting membership predicate unavailable/unsafe rather than treating a stale-generation path as a target fallback; existing-member and grant-backed flows remain separately gated by their own current checks. The selected target must come from canonical discovery and may be the public production realm or an explicitly authorized alternate realm such as a playtest fork. + - Tenant membership, non-public realm-access-grant checks, and runtime entitlement checks occur after account bootstrap. The `player-bootstrap` token is still a tenant-free, non-gameplay bootstrap credential: it authorizes caller-bound discovery and the explicit join/connect-token APIs, but it does not itself carry or grant gameplay scope. The bounded `gameplay-connect` token is the only edge-admission credential carrying the selected target snapshot. In target behavior, a first public-production join presents an explicit `Join & Play` action that may create missing durable Account-owned membership or restore `INACTIVE` membership, before character creation and `POST /auth/connect-token`; connect-token issuance never creates membership implicitly. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the consumer does not classify the latter specifically as `INACTIVE` despite Account's emitted lifecycle field. The obsolete implicit membership-writer surface has been removed, while local explicit `JOIN` / `Join & Play` still lacks complete runtime/deployment proof and the membership-authority-generation reread at issuance remains an implementation/proof gap. The frontend must mark the current otherwise eligible missing or existing non-admitting membership predicate unavailable/unsafe rather than treating a stale-generation path as a target fallback; existing-member and grant-backed flows remain separately gated by their own current checks. The selected target must come from canonical discovery and may be the public production realm or an explicitly authorized alternate realm such as a playtest fork. - Gameplay admission has three separate applicability modes. For public-production onboarding, discovery may precede membership, but only explicit `JOIN`/`Join & Play` creates missing membership or restores `INACTIVE` membership; `gameplay-connect`, trusted TCP Proxy admission, and `PLAY` are applicable only after that commit. For returning membership, those transports and `PLAY` require the existing caller-bound membership and current authority checks and do not perform onboarding. For a grant-backed private or playtest realm, missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`; those targets require the applicable grant and the existing caller-bound `ACTIVE` membership plus its current membership authority generation, never use public `JOIN`, and never create membership or treat the grant as a substitute for membership. The trusted TCP Proxy is only a transport trust path and does not replace the mode-specific downstream checks; a `gameplay-connect` token and `PLAY` command likewise do not establish membership or grant eligibility. - The client must treat `connectScopeId` as an opaque short-lived selector, not as a stable saved identifier. For non-grant public production, the discovery snapshot bundle is `{connectScopeId, tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}`; private/playtest snapshots contain the same fields plus the applicable `playtestLifecycleId` and `playtestStateGeneration`. If reconnect or retry reports `CONNECT_SCOPE_MISMATCH`, it must discard the entire bundle and all derived connect-token metadata, rerun bootstrap discovery, complete target-only `Join & Play` and required character discovery/creation when applicable, and obtain a new selector and connect token rather than reusing any old bundle field or guessing a replacement target from cached `tenantId` or `realmSlug`. `ADMISSION_POINTER_UNAVAILABLE` likewise requires fresh discovery before retry rather than substitution from cached target fields. - Returning players with an existing Account-owned membership use browser bootstrap, bootstrap discovery, and `POST /auth/connect-token` before taking the normal `PLAY [realm] [character]` path; the target skips the membership-creation action only after a fresh authoritative check confirms `ACTIVE` membership and its exact authority/version evidence. A valid current character is additionally required only before connect-token issuance or direct `PLAY`; otherwise the player proceeds through realm-scoped character discovery or creation. Target behavior requires an account with missing or `INACTIVE` membership for the selected game, including an otherwise returning account whose membership is no longer active, to take the explicit `Join & Play` path before character creation/connect, and forbids a connect-token or `PLAY` path from creating or restoring that membership implicitly. Current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified as `INACTIVE` because lifecycle state is target-only, and explicit `JOIN` remains unavailable. The obsolete implicit membership-writer surface has been removed; explicit `Join & Play` remains unimplemented, as does the required membership-authority-generation and independent membership-version reread proof at issuance. Current returning-member success therefore reflects the live existing-membership path, not proof of the target reread contract. The resulting membership powers subsequent “my games” and return flows. Game Session resolves world/realm/character identifiers, rechecks membership, routing, and caller-bound entitlements, returns bundle metadata, and binds the socket in Redis. From c38bbbc4a834e0a8ae8244946cb43ae8da9ffe4b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:32:49 +1200 Subject: [PATCH 08/55] Compact Account audit payload after terminal minimized receipt --- .../account-service/runtime-and-data.md | 2 +- .../AccountAuditOutboxRepository.java | 9 +- ...V26__global_registration_join_evidence.sql | 7 +- .../AccountRepositoryIntegrationTest.java | 82 +++++++++++++++++++ .../service/AccountAuditDeliveryJobTest.java | 13 +++ 5 files changed, 108 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9c820d421c..1768603c29 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -41,7 +41,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after Logging & Admin returns matching receipt evidence; failures leave it `PENDING` for retry. Logging & Admin locally implements durable receipt deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipts. These are local implementation facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry resumes a pending intent; an absent terminal readback is reported as retryable unavailable, not as a membership result. No periodic pending-operation reconciler is claimed. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after Logging & Admin returns matching receipt evidence; failures leave it `PENDING` for retry. Logging & Admin locally implements durable receipt deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipts. After an accepted terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local implementation facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry resumes a pending intent; an absent terminal readback is reported as retryable unavailable, not as a membership result. No periodic pending-operation reconciler is claimed. - **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index c1386b48f8..2829a20873 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -60,12 +60,17 @@ public List pending(int limit) { public void markDelivered( UUID auditEventId, String receiptId, String logEventId, boolean minimized) { - int changed = + var update = dsl.update(ACCOUNT_AUDIT_OUTBOX) .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_RECEIPT_ID, receiptId) .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_LOG_EVENT_ID, logEventId) .set(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS, minimized ? "MINIMIZED" : "COMMITTED") - .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())) + .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())); + if (minimized) { + update.set(ACCOUNT_AUDIT_OUTBOX.PAYLOAD, (String) null); + } + int changed = + update .where( ACCOUNT_AUDIT_OUTBOX .AUDIT_EVENT_ID diff --git a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql index dc0f1647d5..7a9d11b724 100644 --- a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql +++ b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql @@ -247,7 +247,7 @@ CREATE TABLE account_audit_outbox ( schema_version INTEGER NOT NULL, payload_digest_version INTEGER NOT NULL, payload_digest VARCHAR(71) NOT NULL, - payload TEXT NOT NULL, + payload TEXT, receiver_receipt_id VARCHAR(128), receiver_log_event_id VARCHAR(128), delivery_status VARCHAR(32) NOT NULL DEFAULT 'PENDING', @@ -259,7 +259,10 @@ CREATE TABLE account_audit_outbox ( CONSTRAINT account_audit_outbox_version_check CHECK (schema_version > 0 AND payload_digest_version = 1), CONSTRAINT account_audit_outbox_delivery_check - CHECK (delivery_status IN ('PENDING', 'COMMITTED', 'MINIMIZED')) + CHECK (delivery_status IN ('PENDING', 'COMMITTED', 'MINIMIZED')), + CONSTRAINT account_audit_outbox_payload_state_check + CHECK ((delivery_status = 'MINIMIZED' AND payload IS NULL) + OR (delivery_status IN ('PENDING', 'COMMITTED') AND payload IS NOT NULL)) ); CREATE INDEX idx_account_audit_outbox_pending 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 6517d4d00a..1b6005e154 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 @@ -6,6 +6,7 @@ import java.nio.file.Path; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; @@ -190,6 +191,87 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { .isEqualTo(1L); } + @Test + void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(dsl); + UUID minimizedEventId = UUID.randomUUID(); + String minimizedPayload = "{\"accountId\":42,\"requestId\":\"join-42\"}"; + String minimizedDigest = AccountAuditDigest.ofPayload(minimizedPayload); + UUID committedEventId = UUID.randomUUID(); + String committedPayload = "{\"accountId\":43}"; + + outbox.append( + minimizedEventId, "tenant", 7L, "ACCOUNT_JOINED_PUBLIC_PRODUCTION", minimizedPayload); + outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", true); + outbox.append(committedEventId, "platform", null, "ACCOUNT_REGISTERED", committedPayload); + outbox.markDelivered(committedEventId, "receipt-committed", "log-committed", false); + + assertThat( + jdbc.queryForObject( + "SELECT payload FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isNull(); + assertThat( + jdbc.queryForObject( + "SELECT scope FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("tenant"); + assertThat( + jdbc.queryForObject( + "SELECT audit_event_id FROM account_audit_outbox WHERE audit_event_id = ?", + UUID.class, + minimizedEventId)) + .isEqualTo(minimizedEventId); + assertThat( + jdbc.queryForObject( + "SELECT tenant_id FROM account_audit_outbox WHERE audit_event_id = ?", + Long.class, + minimizedEventId)) + .isEqualTo(7L); + assertThat( + jdbc.queryForObject( + "SELECT payload_digest FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo(minimizedDigest); + assertThat( + jdbc.queryForObject( + "SELECT receiver_receipt_id FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("receipt-minimized"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_log_event_id FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("log-minimized"); + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("MINIMIZED"); + assertThat( + jdbc.queryForObject( + "SELECT payload FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + committedEventId)) + .isEqualTo(committedPayload); + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + committedEventId)) + .isEqualTo("COMMITTED"); + assertThat(outbox.pending(10)) + .noneMatch(envelope -> envelope.auditEventId().equals(minimizedEventId)) + .noneMatch(envelope -> envelope.auditEventId().equals(committedEventId)); + } + @Test void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java index cf681c7b3d..1e7d2fc860 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java @@ -35,6 +35,19 @@ void marksOnlyAnExactReceiverReceiptDelivered() { verify(outbox, never()).recordAttempt(envelope.auditEventId()); } + @Test + void minimizedReceiverReceiptMarksSameIdentityTerminal() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(50)).thenReturn(List.of(envelope)); + when(client.deliver(envelope)) + .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-2", true)); + + job.deliverPending(); + + verify(outbox).markDelivered(envelope.auditEventId(), "receipt-2", "log-2", true); + verify(outbox, never()).recordAttempt(envelope.auditEventId()); + } + @Test void unavailableReceiverKeepsSameEnvelopePending() { AccountAuditEnvelope envelope = platformRegistration(); From 1711f951fc838a7c4f74185db5d3a33a11409fd8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:34:34 +1200 Subject: [PATCH 09/55] docs: align current explicit JOIN status across access contracts --- ...d-player-authentication-and-gameplay-binding.md | 2 +- .../game-session-service/protocols.md | 8 ++++---- .../microservices/tcp-proxy-service/protocols.md | 8 ++++---- .../system-architecture-authentication.md | 2 +- .../system-architecture-authz-route-matrix.md | 6 +++--- .../system-architecture-authz-route-matrix.yaml | 6 ++---- .../architecture/system-architecture-frontend.md | 12 ++++++------ .../system-architecture-protocol-bridging.md | 14 +++++++------- .../player-access-and-session.md | 8 ++++---- 9 files changed, 32 insertions(+), 34 deletions(-) diff --git a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md index 50424d44fd..c526ac277b 100644 --- a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md +++ b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. Explicit `POST /auth/bootstrap/join` before bootstrap character creation/connect-token work remains a gap. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance and text `PLAY` require the four-field Account admission response, never invoke an implicit membership writer, and may return non-actionable `JOIN_REQUIRED` for an eligible fresh authoritative public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable; the obsolete writer seam has been removed. The current response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains target-only. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven, and explicit `JOIN` remains unimplemented. The target first-party admission gate therefore remains incomplete until explicit `JOIN`, the joining-policy gate, the active-state check, the generation reread, the unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the unimplemented explicit-membership `JOIN` path; its `known_drift` must also explicitly name the missing joining-policy, active-state, membership-generation, and membership-version baseline checks. +Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. The local `POST /auth/bootstrap/join`, `JoinPublicProductionMembership` operation, and Game Session text `JOIN` dispatch now exist. Complete direct-text and first-party runtime/deployment proof remains open, including PostgreSQL execution and pending-operation recovery/reconciliation. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance and text `PLAY` require the four-field Account admission response, never invoke an implicit membership writer, and may return non-actionable `JOIN_REQUIRED` for an eligible fresh authoritative public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`; the obsolete writer seam has been removed. The current response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains unavailable to consumers. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven. The target first-party admission gate therefore remains incomplete until the joining-policy gate, active-state check, generation reread, unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the local JOIN endpoint and operation; its remaining `known_drift` names the unresolved runtime proof and admission snapshot checks. The current `GameplayHandshakeFilter` accepts one cookie or header, rejects simultaneous carriers, and consumes an untagged replay marker through the generic Cache-bound client, but does not implement ADR 0029's tagged Coordination Redis readiness/fence and quarantine contract. Target player-facing admission remains quarantined until that cutover and proof complete. That current parser support does not establish public non-browser issuance or an accepted target non-first-party route/carrier. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 1d14a6758f..25ffbcd0e0 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -39,7 +39,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, `JOIN` is unavailable and `PLAY` applies only the Account-exposed `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` fields plus existing grant checks; it cannot classify `ACTIVE` or `INACTIVE` until Account exposes lifecycle state. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification, and explicit `JOIN` remains unavailable; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. +- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. The local Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path now exist, but current `PLAY` applies only the Account-exposed `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` fields plus existing grant checks; it cannot classify `ACTIVE` or `INACTIVE` until Account lifecycle state is exposed to and consumed by the admission path. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification. Direct-text and first-party end-to-end proof, PostgreSQL execution, and pending-operation recovery remain incomplete; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -64,7 +64,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Target-only; not currently implemented.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | +| `JOIN ` | **Implemented locally; end-to-end/runtime proof remains incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. PostgreSQL execution, pending-operation recovery, and direct text/first-party path proof remain open. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | | `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | @@ -82,7 +82,7 @@ Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable ` The canonical JOIN and membership-admission contract is defined in [Authentication & Authorization](../../system-architecture-authentication.md#normative-target-contract); this section keeps only Game Session's protocol translation and local handling. -The target Account membership operation is `JoinPublicProductionMembership`; a local Account operation and Game Session translation/scope seam now exist, and there is no current implicit membership writer. The local path does not claim complete direct-text/first-party transport proof, PostgreSQL execution, or pending-operation recovery. Game Session translates `JOIN ` to the sole operation; it does not create membership locally or use another join writer. +The target Account membership operation is `JoinPublicProductionMembership`; the local Account operation and Game Session translation/scope seam now exist, and there is no current implicit membership writer. The local path does not claim complete direct-text/first-party transport proof, PostgreSQL execution, or pending-operation recovery. Game Session translates `JOIN ` to the sole operation; it does not create membership locally or use another join writer. - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. - Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the pending transport-local scope and passes the same identity to Account for retries. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. @@ -164,7 +164,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – bootstrap-backed `LOGIN` resolved to an account different from the validated connect-context subject. -- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. In the current runtime this is a fail-closed, non-actionable result because explicit `JOIN` is unavailable, and the existing non-admitting case cannot be classified as `INACTIVE` because Account does not expose lifecycle state. +- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. The local Account route/RPC and Game Session text dispatch now exist, but the current result remains fail-closed and non-actionable to consumers until lifecycle-aware admission and end-to-end/runtime proof are complete. The existing non-admitting case cannot be classified as `INACTIVE` because Account lifecycle state is not yet consumed by the admission path. - `WORLD_ACCESS_DENIED` – current runtime behavior for a private, playtest, or other non-public target whose Account-exposed membership/admission predicate or existing grant check denies access; no public join action is offered. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index fc71097ddc..a7b17de6d8 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -18,7 +18,7 @@ The discovery-snapshot shortcut is restricted to the first-party token-backed We The following are canonical contracts across Telnet and WebSocket paths: -- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. In the current runtime, explicit `JOIN` is unavailable, hidden default routing is bootstrapped, and missing public-production membership does not create membership. Direct text does not use a first-party WebSocket discovery snapshot. +- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped, and current `PLAY` does not create membership when it returns `JOIN_REQUIRED`. Direct text does not use a first-party WebSocket discovery snapshot. - Proxy -> Gateway WebSocket hop is mTLS-authenticated in player-facing environments under [Security](../../system-architecture-security.md#tls-termination--internal-encryption). - Proxy bridge-availability circuit breaker uses deterministic open/half-open/closed admission behavior during sustained upstream unreachability. @@ -30,7 +30,7 @@ These flows describe how Telnet traffic is forwarded into the shared login/sessi - Connect to the TCP Proxy Service. - Perform fresh public-world discovery with `WORLDS`. This direct text flow does not consume a first-party WebSocket discovery snapshot. - Use `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` authenticates immediately. Complete the applicable secret or verified-email-code response before continuing, then perform authenticated `REALMS` discovery as needed. - - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the target-only conditional `JOIN`; current text reconnect stops with non-actionable `JOIN_REQUIRED` when the current response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false` for an eligible public-production request; the latter cannot be classified as `INACTIVE` and performs no membership mutation. Target behavior also returns `JOIN_REQUIRED` for `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, while target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. + - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; its local Account route/RPC and Game Session text dispatch exist, while the full discovery-first sequence and end-to-end proof remain incomplete. Current text reconnect may stop with non-actionable `JOIN_REQUIRED` when the current response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false` for an eligible public-production request; the latter cannot be classified as `INACTIVE`. Target behavior also returns `JOIN_REQUIRED` for `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, while target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. - If no valid selected character exists after the conditional membership step, use `CHARS [realm]` or the character-creation flow to select or create it; then enter gameplay with `PLAY [realm] [character]`. - The Telnet wire never carries `connectScopeId`, `PlayerExecutionContext`, `playableStateScope`, or storage keys. Game Session retains any target-bound scope locally and derives `playableStateScope` for the character query from the exact server-side realm snapshot; Account separately validates the authenticated caller context, and the proxy only forwards the player-facing selectors and commands. - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. @@ -43,7 +43,7 @@ These flows describe how Telnet traffic is forwarded into the shared login/sessi Advanced Telnet tools may open more than one window or pane for the same account. The proxy forwards traffic for every TCP connection independently; visible takeover behavior follows [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). - **Two Telnet windows** - - Window A connects, performs fresh `WORLDS` discovery, issues `LOGIN`, performs authenticated `REALMS` discovery, follows the target-only conditional `JOIN` step if it is first public-production entry, conditionally completes `CHARS`/character creation when no valid selected character exists, and enters gameplay with `PLAY`. + - Target Window A connects, performs fresh `WORLDS` discovery, issues `LOGIN`, performs authenticated `REALMS` discovery, follows the conditional `JOIN` step if it is first public-production entry, conditionally completes `CHARS`/character creation when no valid selected character exists, and enters gameplay with `PLAY`. Local JOIN dispatch exists; the complete discovery-first sequence remains target-only. - Window B connects and repeats `WORLDS`, `LOGIN`, and authenticated `REALMS` discovery for the same character, follows `JOIN` only if required by the Authentication flow, conditionally completes `CHARS`/character creation when no valid selected character exists, then issues `PLAY`. Game Session applies the canonical takeover and the old window is disconnected. - If Window A reconnects and logs in again, it in turn takes over from Window B. There is no concurrent split control even though the proxy forwards traffic from both TCP connections. @@ -110,7 +110,7 @@ Current rules: - any future adapter-carried attach hint must remain advisory and must not bypass either the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` fail-closed path or the target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow; only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. -- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because explicit `JOIN` is unavailable, hidden default routing is bootstrapped instead, and otherwise admitting existing members may use the abbreviated current `LOGIN` -> `PLAY` -> `LOOK` path; the target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). +- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, while otherwise admitting existing members may use the abbreviated current `LOGIN` -> `PLAY` -> `LOOK` path. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Metrics give observability into each Telnet connection while keeping Prometheus label cardinality bounded: diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 2bd550bb6a..0787e92d50 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -731,7 +731,7 @@ First-party gameplay admission and reconnect clients should treat the following | `PLAY` | `STALE_TIMELINE` | The selected region, epoch, or lease fence no longer matches current runtime authority | Keep auth state, create no gameplay binding, rediscover the realm and runtime timeline, and retry admission explicitly; never accept an implicit rebind. | | Gameplay command before `PLAY` | `PLAY_REQUIRED` | Client issued a world-scoped gameplay command before lobby admission completed | Keep auth state and route the client back through `PLAY`, `REALMS`, or `CHARS` as appropriate. | -Reconnect sequencing, snapshot reuse, transport-local scope replacement, and resume/takeover behavior are owned by [Reconnection Strategy](./system-architecture-reconnection.md) and [Session Behavior](./system-architecture-session-behavior.md). Authentication's target-state consequence is that each reconnect re-establishes the exact transport authentication path and then uses fresh routing plus one fresh Account membership snapshot before admission; stale selectors, expired scopes, partial membership evidence, and client-supplied authority never authorize fallback. Current runtime deviations from the target flow are recorded in [Implementation Status](#implementation-status), including the unavailable explicit `JOIN` operation. +Reconnect sequencing, snapshot reuse, transport-local scope replacement, and resume/takeover behavior are owned by [Reconnection Strategy](./system-architecture-reconnection.md) and [Session Behavior](./system-architecture-session-behavior.md). Authentication's target-state consequence is that each reconnect re-establishes the exact transport authentication path and then uses fresh routing plus one fresh Account membership snapshot before admission; stale selectors, expired scopes, partial membership evidence, and client-supplied authority never authorize fallback. Current runtime deviations from the target flow are recorded in [Implementation Status](#implementation-status), including incomplete membership lifecycle/generation reread and end-to-end proof for the local explicit `JOIN` operation. Logical character identity is the canonical `characterId` resolved under the caller's tenant and selected playable-state namespace; it is distinct from active gameplay-binding uniqueness. All Redis key formats and Game Session Service APIs must treat `characterId` as the abstract character identifier so sessions bind sockets to characters rather than raw accounts. Canonical target takeover and resume uniqueness is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; its binding value/evidence retains server-derived `playableStateScope`, `{sessionId, gameInstanceId, bindingGeneration}`, with `gameInstanceId` as the active-runtime fence. The existing `{tenantId, gameInstanceId, characterId}` identity is current implementation drift. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index d6a4831f71..2ddc39ee02 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -215,7 +215,7 @@ For every first public-production text entry, the target command sequence is `LO | Game Session Service | `WORLDS` anonymous browse | `public` | Public-production catalog only; no account-specific membership, grant, or character information | | Game Session Service | `WORLDS` authenticated discovery | `pre_tenant_discovery` | No pre-existing tenant role is required. Tenant visibility is derived server-side from membership or public-production visibility plus entitlement state; global roles do not widen gameplay discovery | | Game Session Service | `REALMS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive branch from the authoritative realm mode: public production permits pre-membership discovery; private/playtest requires caller-bound `membershipLifecycleState=ACTIVE`, current membership authority generation/version, and the current Account-owned grant for the exact target. Private/playtest is never classified as public onboarding, never falls back to public discovery, and never uses a grant to repair membership. Hidden/unauthorized targets are omitted; explicit branch failures use `NON_PUBLIC_ENROLLMENT_REQUIRED`, `REALM_ACCESS_DENIED`, `WORLD_ACCESS_DENIED`, `ADMISSION_POINTER_UNAVAILABLE`, `REALM_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE`, or `AUTH_UNAVAILABLE` as applicable. | -| Game Session Service | `JOIN` | `public_production_onboarding` | **Target-only; not currently implemented.** Explicit caller-bound open-enrollment action for the current public production realm; Account commits durable membership plus audit/outbox idempotently | +| Game Session Service | `JOIN` | `public_production_onboarding` | **Implemented locally; end-to-end runtime/deployment proof remains incomplete.** Game Session dispatches explicit caller-bound open enrollment to Account's `JoinPublicProductionMembership`; Account commits durable membership plus audit/outbox idempotently. PostgreSQL execution, pending-operation recovery after an unknown commit outcome, and direct text/first-party end-to-end proof remain open. | | Game Session Service | `CHARS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Public discovery may lead to `JOIN_REQUIRED` for missing or `INACTIVE` membership; private/playtest requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. It applies the current `admission_pointer` check to the selected catalog realm, but does not apply `PLAY`'s exact-binding admission lease, binding fence, or binding-ownership gate; character discovery and creation do not require a selected character. Policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and unavailable or invalid authority uses the applicable unavailable/invalid-authority outcome. Missing or non-`ACTIVE` private/playtest membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`, and character discovery is not membership repair. | | Game Session Service | `PLAY` | `gameplay_admission` | **Target:** requires an existing caller-bound membership plus any non-public realm grant, current entitlements, and the current admissible realm pointer; `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when the selected target is confirmed as public production and its joining policy denies entry, and only an admissible, publicly visible public-production target whose joining policy permits entry and whose membership is missing or `INACTIVE` returns `JOIN_REQUIRED`; `ACTIVE` membership does not require `JOIN`, and `PLAY` never creates or restores membership. `PLAY` alone performs the final gameplay-binding CAS. First-party `/ws/game/**` also enforces connect-context scope. Unavailable, ambiguous, stale, or otherwise invalid routing returns `ADMISSION_POINTER_UNAVAILABLE`; a deliberately closed realm returns `REALM_UNAVAILABLE`; entitlement authority outage returns `ENTITLEMENT_UNAVAILABLE`. | | Spring Cloud Gateway | `/ws/game/**` (connect-token bootstrap) | `gameplay_admission` | **Implemented but non-promotable until the named Gateway readiness evidence is complete:** carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. This is one canonical WebSocket entry point with mutually exclusive variants. The current `first_party_web` variant accepts exactly the protected cookie for first-party protected-cookie clients, including native or other nonbrowser clients using a cookie jar. The live `GameplayHandshakeFilter` rejects `X-Firemud-Connect-Token` on this public route with `CONNECT_TOKEN_REJECTED` and reason `unsupported_carrier_or_route`, without falling back to the cookie. A future explicitly classified `non_first_party_public` variant may use the header only after its dedicated matrix entry and issuance, replay, signed-context, response, and carrier proof exist; it cannot select or fall back to `first_party_web`. Gateway consumes exactly one supported carrier, strips it, atomically enforces single use using the dedicated replay record/fence, matches the signed connect scope to the request, and emits the signed connect context for Game Session. Non-`101` outcomes use the bounded `CONNECT_TOKEN_MISSING`, `CONNECT_TOKEN_EXPIRED`, `CONNECT_TOKEN_REPLAYED`, `CONNECT_SCOPE_MISMATCH`, `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, `CONNECT_TOKEN_REJECTED`, `POLICY_DENY`, `POLICY_PRESSURE`, `BACKEND_UNAVAILABLE`, `PROTOCOL_MISMATCH`, or `INTERNAL_ERROR` handshake classes. | @@ -225,7 +225,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GET /auth/bootstrap/worlds/{worldSlug}/realms` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Accepts only the caller-bound `player-bootstrap` profile; applies live realm visibility and runtime entitlement checks, with private/playtest additionally requiring caller-bound `ACTIVE` membership and the applicable Account-owned realm-access grant. Private/playtest is not public onboarding. | | Account Service | `GET /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Accepts only the caller-bound `player-bootstrap` profile; this existing-character discovery operation declares `selected_character_requirement: none`, and its target binding and `connect_scope_match` check require the opaque server-issued `connectScopeId` to match the selected route target, alongside live membership, applicable realm-grant, entitlement, and admission-pointer checks. It creates no gameplay binding and does not perform `PLAY`'s final binding CAS. | | Account Service | `POST /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | **Target; not currently routable or implemented.** Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Bootstrap-authenticated Account facade derives `accountId` from the authenticated caller subject, declares `selected_character_requirement: none`, and requires its target binding plus `connect_scope_match` check to match the opaque server-issued discovery `connectScopeId`; existing caller-bound membership, applicable realm visibility/grant, runtime entitlement, and admission-pointer checks precede the retained target delegation to internal Entity Management `CreateCharacter`. Character creation creates no gameplay binding and does not perform `PLAY`'s final binding CAS. | -| Account Service | `POST /auth/bootstrap/join` | `public_production_onboarding` | **Target; not currently implemented.** Accepts only the caller-bound `player-bootstrap` profile, derives `accountId` from the authenticated subject, and its target binding plus `connect_scope_match` check require the opaque server-issued discovery `connectScopeId` to match the selected public-production target before creating membership atomically | +| Account Service | `POST /auth/bootstrap/join` | `public_production_onboarding` | **Implemented locally; runtime/deployment proof remains incomplete.** Accepts only the caller-bound `player-bootstrap` profile, derives `accountId` from the authenticated subject, and requires the opaque server-issued discovery `connectScopeId` to match the selected public-production target before creating membership atomically. PostgreSQL execution and pending-operation recovery after an unknown commit outcome remain unproved. | | Logging & Admin | `POST /feature-flags/toggle`, `POST /tick-remediation/pause`, `POST /tick-remediation/resume` | `tenant_regular` operator ingress | **Target; not currently routable.** Exact `control-ui` profile and current operator role. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Each mutation also requires its action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption before enablement. | | Logging & Admin | `POST /moderation/actions` | `tenant_regular` operator ingress for `gameplay_ban`, `chat_mute`, and `chat_ban`; `account_scoped` platform-jurisdiction ingress for `platform_access_ban` | **Target; unavailable/gated.** The closed `action` selector selects exactly one matrix variant and rejects `account_security_lock`, unknown, and legacy values before branch authorization. Tenant-scoped categories retain the `tenant_regular` branch: `moderator`, `tenantAdmin`, and `platformAdmin` use the existing tenant membership/tenant-generation or global target-tenant-generation consequences. `platform_access_ban` uses the separate `account_scoped` branch: only global `platformAdmin` with `privileged_control`, explicit global target-account binding and platform scope, no `tenantId`, no tenant billing generation, and no membership or tenant-generation checks. Both variants link the root moderation policy-intent authorization contract: Logging & Admin redeems the local Account reference at its receiving boundary; any later owner-enforcement command uses a distinct identity/digest/reference/fingerprint and is redeemed by the selected owner. Target mutation contract: `durable_intent_then_moderation_record_idempotency`. Account remains the enforcement owner for the global restriction; target Game Session and Social & Groups enforcement reads the applicable owner-local durable restriction state or projection. **Current compatibility drift:** both consumers instead call the live `EvaluateModerationPolicy` read at their enforcement boundaries; that read is not a second target moderation authority. Owner-enforcement command coverage remains a recorded gap. | | Logging & Admin | `POST /reports` | `player_bootstrap_tenant` | **Target-only; not currently routable.** Accepts caller-bound `player-bootstrap`, derives `tenantId` and `reporterAccountId` from the authenticated caller and live membership, applies `moderation_report_policy`, and writes a caller-bound durable report record. | @@ -242,7 +242,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `EnterPrivilegedControlWindow` | `account_scoped` | **Target; not currently implemented.** Exact `control-ui` profile plus recent ordinary reauthentication and independent TOTP; this route creates the bounded role-scoped window and does not require an existing elevation window | | Account Service | `IssueHumanOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus a forwarded `control-ui` token with its exact active Account issued-token registry record; Account rereads current account/token generation, operator roles, role-appropriate assurance, the applicable tenant or target-tenant generation, and required `privileged_control` predicate before issuing the bounded reference | | Account Service | `IssueAutomationOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus current versioned automation policy; no end-user JWT or user impersonation. The current branch is tenant-scoped only, binds the exact current tenant generation, and rejects global-role or `privileged_control` action families | -| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Target-only; not currently implemented.** Canonical operation is defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). The local route is called only by the exact Game Session mTLS workload with typed caller-bound player execution context, accepts no end-user token, and requires `verified_connectScopeId_exact_target`. Account revalidates the exact `connectScopeId`, `catalogRevision`, `pointerVersion`, and resolved target immediately before commit; silent retargeting is forbidden. The obsolete implicit membership writer is removed. | +| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Implemented locally; runtime/deployment proof remains incomplete.** Canonical operation is defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). It is called only by the exact Game Session mTLS workload with typed caller-bound player execution context, accepts no end-user token, and requires `verified_connectScopeId_exact_target`. Account revalidates the exact `connectScopeId`, `catalogRevision`, `pointerVersion`, and resolved target immediately before commit; silent retargeting is forbidden. PostgreSQL execution and pending-operation recovery after an unknown commit outcome remain unproved. | | Account Service | `DELETE /tenants/{tenantId}/memberships/me` | `caller_membership_scoped` | Caller-bound membership exit remains available while billing-blocked to any current member role, requires live subject-bound membership, and advances membership authority atomically | | Account Service | `AuthLogout` / `AuthLogoutAll` | `account_scoped` | Accepts `control-ui` (`audience: control-ui`) or `player-bootstrap` (`audience: player-bootstrap`) with registry-backed authenticated account scope. Bounded retries may return no-op success only from a durable committed exact-token tombstone (`AuthLogout`) or durable proof that a prior logout-all superseded the token (`AuthLogoutAll`); registry absence alone is insufficient and the retry exception grants no reusable authorization context | | Account Service | `GET /accounts/{accountId}/deletion` | `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=deletion_status`; the Account-issued credential is bound to the account and deletion workflow and returns deletion status only | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 16ef35c108..a846ec36a5 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -393,7 +393,7 @@ required_live_check_vocabulary: - security_lock_export_action_family implementation_status: known_drift: - - explicit_public_production_JOIN_is_not_implemented; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; the_live_adapter_uses_membershipExists_false_for_missing_and_gameplayAdmissionAllowed_false_for_existing_non_admitting_membership_without_classifying_the_latter_as_INACTIVE; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented + - explicit_public_production_JOIN_route_account_operation_and_text_dispatch_exist_locally; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; the_live_adapter_uses_membershipExists_false_for_missing_and_gameplayAdmissionAllowed_false_for_existing_non_admitting_membership_without_classifying_the_latter_as_INACTIVE; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; lifecycle_and_membership_authority_generation_rereads_remain_unproved; postgresql_execution_and_pending_operation_recovery_remain_incomplete - protected_cookie_ws_game_and_bootstrap_bare_LOGIN_are_implemented_but_non_promotable_until_Gateway_carrier_requirements_replay_marker_durability_replay_quarantine_continuity_and_Account_planned_rotation_compromise_cutover_evidence_are_complete - privileged_control_is_target_only_and_unavailable_in_current_runtime; platformAdmin_and_cross_tenant_billingAdmin_branches_requiring_it_fail_closed_while_the_support_branch_does_not_require_it - operator_mutation_rows_are_normative_target_contracts_not_current_availability; action_schema_mutationDigest_v1_vectors_and_account_issued_authorization_reference_flow_are_required_before_external_support @@ -1929,12 +1929,10 @@ routes: any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED] mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation - route_status: target_not_currently_routable - service: account-service route: JoinPublicProductionMembership scope: tenant classification: internal_workload - route_status: target_not_currently_routable auth_path: exact_mtls_workload issued_token_state: none accepted_token_profiles: [] @@ -1968,7 +1966,7 @@ routes: membership_creation: caller_bound_after_validation implementation_status: known_drift: - - explicit_JOIN_and_Join_And_Play_are_not_currently_implemented; connect_token_and_play_now_require_existing_membership_and_do_not_invoke_this_writer + - pending_operation_recovery_after_unknown_database_outcome_remains_unresolved; direct_text_and_first_party_end_to_end_runtime_deployment_and_postgresql_proof_remain_incomplete; membership_lifecycle_generation_and_connect_token_issuance_baseline_proof_remain_incomplete - service: account-service route: DELETE /tenants/{tenantId}/memberships/me scope: tenant diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 88effcd891..917f492667 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -41,7 +41,7 @@ The frontend keeps the target `PLAY` gate separate from the target `Join & Play` - **`PLAY` gate:** enable only after fresh selected-target routing/pointer evidence, entitlement, caller-bound `membershipLifecycleState=ACTIVE`, any required realm grant, and a valid current character all pass. `PLAY` never creates or restores membership. - **`Join & Play` gate:** enable only for the selected public-production realm when the fresh public-joining policy is `allowPublicJoin=true` and caller-bound membership is missing or `INACTIVE`; it invokes the explicit Account join route and waits for the post-join snapshot before character discovery, creation, connect-token issuance, or `PLAY`. -These are target-only gates. The current frontend must keep missing or non-admitting membership unavailable and must not expose an actionable Join route while the explicit join endpoint and required issuance reread remain unimplemented. A private/playtest target never uses the public `Join & Play` gate; it requires existing `ACTIVE` membership plus the current realm grant. +These are target-only gates. The current frontend must keep missing or non-admitting membership unavailable and must not expose an actionable Join route until the required issuance reread and complete runtime/deployment proof are available. The local explicit join endpoint and Account writer now exist, but their presence does not clear this UI readiness gate. A private/playtest target never uses the public `Join & Play` gate; it requires existing `ACTIVE` membership plus the current realm grant. ## Implementation Notes @@ -108,10 +108,10 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - The target canonical player logout order is: stop reconnect attempts, capture the current `player-bootstrap` token into the pending-revocation slot, ask Account to durably commit the exact-token `PENDING` intent and immediately advance the exact-token issuance fence to `PENDING_LOGOUT` in that same durable step, then send gameplay `LOGOUT` and close the gameplay socket, ask Gateway to deny the gameplay-connect `jti` and clear the HttpOnly cookie, and finally ask Account to invalidate the underlying token and commit the `COMMITTED` tombstone. Account must establish the durable issuance fence before socket closure or any racing `/auth/connect-token` issuance can succeed; every issuance path rejects the fenced lineage rather than returning a usable late credential. Once `PENDING` is durable, Account must reject racing issuance, refresh, rebind, installation, and every unrelated reconciliation for that token lineage; only the exact matching Account lifecycle reconciliation may complete or abort that pending logout operation. `PENDING` is never success and remains resumable through that exact Account operation until terminal completion. If Gateway revoke is unavailable, Account must not report the edge deny/clear outcome as confirmed; clear only local reconnect/client state and rely on the bounded token lifetime; Gateway mitigation must not be reported as full logout when Account is unavailable or its fence is unconfirmed. The browser never directly clears the HttpOnly gameplay cookie; only a server response can clear that cookie. The target Gateway revoke call uses a two-second per-attempt timeout, at most two retries, and 250 ms then 500 ms backoff where time remains, but every request timeout and backoff is capped by the remaining five-second total deadline. This Gateway controller budget is independent and non-nested: it is not shared with or added to Account's revocation budget. Account revocation retains its separate policy of at most five attempts, a five-second timeout per attempt capped by a 30-second overall deadline, and full-jitter exponential backoff starting at 250 ms and capped at four seconds. The controller tracks Account PENDING, Gateway denial/clearing, and Account COMMITTED finalization as separate outcomes. It enters terminal `LOGGED_OUT_REVOKED` only after Account confirms the exact-token fence/Bootstrap-token revocation and Gateway confirms denial/clearing of the gameplay-connect token. Because Gateway gameplay-connect denial and cookie clearing are not currently routable, the current runtime cannot reach `LOGGED_OUT_REVOKED`; current logout flows terminate as `LOGGED_OUT_REVOCATION_UNCONFIRMED`. Account-only confirmation remains `LOGGED_OUT_REVOCATION_UNCONFIRMED` with edge revocation explicitly unconfirmed until Gateway confirms or the known gameplay-connect acceptance window ends; expiry closes that bounded edge risk but is reported as token-window expiry, not confirmed server revocation. Retry exhaustion, an unconfirmed Account result, or bootstrap-token expiry likewise remains `LOGGED_OUT_REVOCATION_UNCONFIRMED`, stays locally logged out, and requires a fresh `POST /auth/player-bootstrap` before any later gameplay flow. The frontend may retry only while the captured credential remains valid and its local retry deadline remains open. At the earlier of signed token expiry or that deadline, it wipes the raw credential and stops frontend retries while retaining only the opaque server-side logout handle and non-secret operation state needed to observe Account's durable reconciliation. Browser or process loss likewise destroys the memory-only credential and ends frontend retries, but neither local expiry nor frontend loss cancels the durable Account `PENDING` operation: Account's persisted operation and opaque logout handle are the authoritative revocation proof, and Account's reconciler continues exact-token revocation without the raw token. A raw credential may never be reused for gameplay/bootstrap calls, and retaining it in memory never extends its signed lifetime. Local clearing or process termination is not confirmed server revocation. - Logout invalidates the local bootstrap/connect-token request epoch and aborts every in-flight bootstrap, discovery, join, character, and connect-token request owned by that epoch. A late response is ignored for all client state transitions, but abort and epoch invalidation cannot guarantee that a late `Set-Cookie` was not already committed by the browser. The server-side logout issuance fence is therefore authoritative: Account rejects bootstrap or connect-token issuance that races a durable `PENDING` or `COMMITTED` logout for the same account/token lineage, and Gateway rejects a connect token whose deny/revocation fence wins before consumption. Where a logout response reaches the browser after the old issuance, the server must also return an explicit clearing or deny response so the late cookie cannot remain usable. The client must never treat ignored local state or local cookie clearing alone as proof of server revocation. - A server must reject an expired `Firemud-Connect-Token` cookie as `CONNECT_TOKEN_EXPIRED`, never fall back to a stale cookie, query parameter, or unapproved header, and return a clearing `Set-Cookie` response where the HTTP surface can do so. The browser cannot inspect the HttpOnly value; it discards the failed handshake attempt and obtains a fresh connect token only from a still-valid bootstrap session. If the bootstrap token is expired or revoked, the client restarts `POST /auth/player-bootstrap` and discovery instead of treating the expired cookie as a recoverable gameplay credential. - - Tenant membership, non-public realm-access-grant checks, and runtime entitlement checks occur after account bootstrap. The `player-bootstrap` token is still a tenant-free, non-gameplay bootstrap credential: it authorizes caller-bound discovery and the explicit join/connect-token APIs, but it does not itself carry or grant gameplay scope. The bounded `gameplay-connect` token is the only edge-admission credential carrying the selected target snapshot. In target behavior, a first public-production join presents an explicit `Join & Play` action that may create missing durable Account-owned membership or restore `INACTIVE` membership, before character creation and `POST /auth/connect-token`; connect-token issuance never creates membership implicitly. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the consumer does not classify the latter specifically as `INACTIVE` despite Account's emitted lifecycle field. The obsolete implicit membership-writer surface has been removed, while local explicit `JOIN` / `Join & Play` still lacks complete runtime/deployment proof and the membership-authority-generation reread at issuance remains an implementation/proof gap. The frontend must mark the current otherwise eligible missing or existing non-admitting membership predicate unavailable/unsafe rather than treating a stale-generation path as a target fallback; existing-member and grant-backed flows remain separately gated by their own current checks. The selected target must come from canonical discovery and may be the public production realm or an explicitly authorized alternate realm such as a playtest fork. + - Tenant membership, non-public realm-access-grant checks, and runtime entitlement checks occur after account bootstrap. The `player-bootstrap` token is still a tenant-free, non-gameplay bootstrap credential: it authorizes caller-bound discovery and the explicit join/connect-token APIs, but it does not itself carry or grant gameplay scope. The bounded `gameplay-connect` token is the only edge-admission credential carrying the selected target snapshot. In target behavior, a first public-production join presents an explicit `Join & Play` action that may create missing durable Account-owned membership or restore `INACTIVE` membership, before character creation and `POST /auth/connect-token`; connect-token issuance never creates membership implicitly. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the consumer does not classify the latter specifically as `INACTIVE` despite Account's emitted lifecycle field. The obsolete implicit membership-writer surface has been removed. The local explicit `JOIN` route/writer and Game Session text dispatch now exist, but complete runtime/deployment proof and the membership-authority-generation reread at issuance remain open. The frontend must mark the current otherwise eligible missing or existing non-admitting membership predicate unavailable/unsafe rather than treating a stale-generation path as a target fallback; existing-member and grant-backed flows remain separately gated by their own current checks. The selected target must come from canonical discovery and may be the public production realm or an explicitly authorized alternate realm such as a playtest fork. - Gameplay admission has three separate applicability modes. For public-production onboarding, discovery may precede membership, but only explicit `JOIN`/`Join & Play` creates missing membership or restores `INACTIVE` membership; `gameplay-connect`, trusted TCP Proxy admission, and `PLAY` are applicable only after that commit. For returning membership, those transports and `PLAY` require the existing caller-bound membership and current authority checks and do not perform onboarding. For a grant-backed private or playtest realm, missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`; those targets require the applicable grant and the existing caller-bound `ACTIVE` membership plus its current membership authority generation, never use public `JOIN`, and never create membership or treat the grant as a substitute for membership. The trusted TCP Proxy is only a transport trust path and does not replace the mode-specific downstream checks; a `gameplay-connect` token and `PLAY` command likewise do not establish membership or grant eligibility. - The client must treat `connectScopeId` as an opaque short-lived selector, not as a stable saved identifier. For non-grant public production, the discovery snapshot bundle is `{connectScopeId, tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}`; private/playtest snapshots contain the same fields plus the applicable `playtestLifecycleId` and `playtestStateGeneration`. If reconnect or retry reports `CONNECT_SCOPE_MISMATCH`, it must discard the entire bundle and all derived connect-token metadata, rerun bootstrap discovery, complete target-only `Join & Play` and required character discovery/creation when applicable, and obtain a new selector and connect token rather than reusing any old bundle field or guessing a replacement target from cached `tenantId` or `realmSlug`. `ADMISSION_POINTER_UNAVAILABLE` likewise requires fresh discovery before retry rather than substitution from cached target fields. - - Returning players with an existing Account-owned membership use browser bootstrap, bootstrap discovery, and `POST /auth/connect-token` before taking the normal `PLAY [realm] [character]` path; the target skips the membership-creation action only after a fresh authoritative check confirms `ACTIVE` membership and its exact authority/version evidence. A valid current character is additionally required only before connect-token issuance or direct `PLAY`; otherwise the player proceeds through realm-scoped character discovery or creation. Target behavior requires an account with missing or `INACTIVE` membership for the selected game, including an otherwise returning account whose membership is no longer active, to take the explicit `Join & Play` path before character creation/connect, and forbids a connect-token or `PLAY` path from creating or restoring that membership implicitly. Current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified as `INACTIVE` because lifecycle state is target-only, and explicit `JOIN` remains unavailable. The obsolete implicit membership-writer surface has been removed; explicit `Join & Play` remains unimplemented, as does the required membership-authority-generation and independent membership-version reread proof at issuance. Current returning-member success therefore reflects the live existing-membership path, not proof of the target reread contract. The resulting membership powers subsequent “my games” and return flows. Game Session resolves world/realm/character identifiers, rechecks membership, routing, and caller-bound entitlements, returns bundle metadata, and binds the socket in Redis. + - Returning players with an existing Account-owned membership use browser bootstrap, bootstrap discovery, and `POST /auth/connect-token` before taking the normal `PLAY [realm] [character]` path; the target skips the membership-creation action only after a fresh authoritative check confirms `ACTIVE` membership and its exact authority/version evidence. A valid current character is additionally required only before connect-token issuance or direct `PLAY`; otherwise the player proceeds through realm-scoped character discovery or creation. Target behavior requires an account with missing or `INACTIVE` membership for the selected game, including an otherwise returning account whose membership is no longer active, to take the explicit `Join & Play` path before character creation/connect, and forbids a connect-token or `PLAY` path from creating or restoring that membership implicitly. Current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified as `INACTIVE` because lifecycle state is not consumed by the admission path. The local explicit `JOIN` route/writer and Game Session text dispatch now exist; the required membership-authority-generation and independent membership-version reread proof at issuance remains incomplete, as do full runtime/deployment, PostgreSQL, and pending-operation recovery proof. Current returning-member success therefore reflects the live existing-membership path, not proof of the target reread contract. The resulting membership powers subsequent “my games” and return flows. Game Session resolves world/realm/character identifiers, rechecks membership, routing, and caller-bound entitlements, returns bundle metadata, and binds the socket in Redis. - After connectivity loss while the in-memory `player-bootstrap` token survives, the client may request a fresh connect token, reconnect the WebSocket, then replay `LOGIN` and `PLAY` without prompting for credentials again only when the complete discovery snapshot is present and unexpired, and a fresh authoritative read confirms `membershipLifecycleState=ACTIVE`, the exact current `membershipAuthorityGeneration`, the independently current `membershipVersion`, and a valid current character for the selected target. A full page reload loses that memory-only token and must restart at `POST /auth/player-bootstrap`, then rerun discovery before requesting a connect token; the architecture defines no hidden refresh credential. `WORLDS`, `REALMS `, and `CHARS [realm]` remain optional discovery helpers only while the complete snapshot remains unexpired and those current membership, generation, version, and character checks pass; otherwise the client must rerun the full discovery/join/character path. Shared state restores session context only. Game Session must revalidate continuation authorization, the active binding and its fence, revocation state, and the current server-resolved target authority before resuming; Redis key presence or fresh backend-token rebinding is not authorization. First-party reconnects must not prompt the browser to replay Telnet-style `LOGIN [secret]` credentials after bootstrap has been re-established. - **Admin and creator UIs** @@ -127,14 +127,14 @@ All new frontend features that interact with protected APIs should reuse the sha - `AUTH_TOKEN_EXPIRED` – Clear in-memory auth state, redirect to login, and show a “Session expired” message. - `AUTH_SESSION_REVOKED` – Clear in-memory auth state, redirect to login, and show a security-focused message (for example, “You were signed out because your account security changed.”). - - `JOIN_REQUIRED` – Preserve in-memory authentication when an otherwise eligible public-production request does not admit because `membershipExists=false` or existing `gameplayAdmissionAllowed=false`, mark the affected admission unavailable, and do not expose an actionable `Join & Play` retry while explicit `JOIN` and the required membership reread are unimplemented. The latter response cannot be classified specifically as `INACTIVE` or used as a lifecycle-state result. Keep character discovery/creation, connect-token issuance, and `PLAY` blocked; do not retry those operations automatically or create membership implicitly. When implemented, explicit `JOIN`/`Join & Play` creates missing membership or restores target-only `INACTIVE`; private/playtest text `PLAY` currently returns `WORLD_ACCESS_DENIED` for missing or non-admitting membership, while the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Target `PLAY` behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED`, remains separately gated by the current grant, and never uses public `JOIN` as a fallback; keep the current endpoint outcomes distinct in the UI. + - `JOIN_REQUIRED` – Preserve in-memory authentication when an otherwise eligible public-production request does not admit because `membershipExists=false` or existing `gameplayAdmissionAllowed=false`, mark the affected admission unavailable, and do not expose an actionable `Join & Play` retry until the required membership reread and runtime/deployment proof are complete. The local Account join route/writer and Game Session text dispatch exist, but their presence alone does not make the frontend flow ready. The existing non-admitting response cannot be classified specifically as `INACTIVE` or used as a lifecycle-state result. Keep character discovery/creation, connect-token issuance, and `PLAY` blocked; do not retry those operations automatically or create membership implicitly. The implemented local `JOIN` operation creates missing membership; target lifecycle restoration of `INACTIVE` remains gated on complete lifecycle-aware admission and proof. Private/playtest text `PLAY` currently returns `WORLD_ACCESS_DENIED` for missing or non-admitting membership, while the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Target `PLAY` behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED`, remains separately gated by the current grant, and never uses public `JOIN` as a fallback; keep the current endpoint outcomes distinct in the UI. - `AUTH_UNAVAILABLE` – Keep in-memory auth state and show a retriable authentication-service availability message for ordinary API calls when authority availability is `UNAVAILABLE` for live membership, registry, or another required non-routing, non-entitlement authority. Reachable invalid pointer evidence uses `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out pointer authority uses `AUTH_UNAVAILABLE`; entitlement authority outage uses `ENTITLEMENT_UNAVAILABLE`. None may be relabeled as a billing block. An unavailable authority is not equivalent to missing or non-admitting membership and must not produce `JOIN_REQUIRED`. Block only the affected authority-dependent or billing-unsafe mutation, including gameplay-admission mutations, until authority recovers; billing-safe operations that remain permitted under `TENANT_BILLING_BLOCKED` remain available unless they independently require the unavailable authority. Retry only idempotent reads, or mutations carrying the same stable request idempotency key that the service durably deduplicates, with at most one automatic retry inside a five-second total deadline and bounded backoff. The dedicated logout controller uses its separate bounded logout/revocation budget and is excluded from this generic retry rule. Never replay an unkeyed or non-idempotent mutation, and do not convert this infrastructure failure into logout. - `ENTITLEMENT_UNAVAILABLE` – Preserve authentication state and show a retriable entitlement-availability message when entitlement authority is `UNAVAILABLE` or the required fresh Account entitlement evaluation cannot be established. Block only the affected admission, capacity, or other entitlement-dependent operation; retry under the same idempotency and bounded-backoff rules as `AUTH_UNAVAILABLE`. Do not relabel the outage as `TENANT_BILLING_BLOCKED`, `AUTH_UNAVAILABLE`, or `JOIN_REQUIRED`, and do not use stale entitlement state unless the exact bounded same-binding continuity contract applies. - `TENANT_BILLING_BLOCKED` – Keep the user logged in, mark the denied admission, capacity, or mutation operation as billing-blocked in UI state, and show a prominent billing banner. This is not a blanket tenant gameplay shutdown: preserve connected sessions, eligible same-session resume, permitted `past_due` gameplay, and billing-safe operations such as viewing invoices or updating payment details; `grace` preserves connected sessions and same-session resume but denies first-time public join, first/new gameplay bindings, new instances, scale-out, and quota growth. Apply this code only when authoritative Account evidence explicitly denies that operation; `ENTITLEMENT_UNAVAILABLE` takes precedence when entitlement authority cannot be obtained, while `AUTH_UNAVAILABLE` remains the corresponding non-entitlement authority outage. Neither unavailable result may be converted into a billing block. - `ADMISSION_POINTER_UNAVAILABLE` – Keep the current auth state for reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid catalog/pointer evidence, show a retriable gameplay-admission unavailable message, rerun bootstrap discovery or reconciliation, and only then retry lobby admission with bounded backoff; never substitute a cached tenant or runtime target. Unreachable or timed-out pointer authority is `AUTH_UNAVAILABLE` instead. - Target-state `REALM_UNAVAILABLE` – Keep the current auth state when the resolved realm pointer is complete and `CLOSED`, create no gameplay binding, and wait for fresh discovery or an authoritative availability change rather than fast-looping retries. This is distinct from reachable invalid pointer evidence (`ADMISSION_POINTER_UNAVAILABLE`) and unreachable or timed-out pointer authority (`AUTH_UNAVAILABLE`). - `CONNECT_CONTEXT_INVALID` – Keep the current auth state, force gameplay reconnect flow (`connect-token` refresh + new socket + `LOGIN`), and block `PLAY` retries on the current socket. -- `CONNECT_SCOPE_MISMATCH` – Keep the current auth state, discard the entire discovery snapshot bundle and all connect-token metadata derived from it, including `realmId` and `catalogRevision`, rerun bootstrap discovery, and do not expose an actionable current repair because explicit join is unimplemented. Target behavior additionally completes `Join & Play` when the newly selected public target requires membership, performs required character discovery/creation, requests a fresh connect token only from the newly returned bundle, and retries on a new socket. +- `CONNECT_SCOPE_MISMATCH` – Keep the current auth state, discard the entire discovery snapshot bundle and all connect-token metadata derived from it, including `realmId` and `catalogRevision`, and rerun bootstrap discovery. Do not expose an actionable current repair until the required issuance reread and runtime/deployment proof are complete; the local join route/writer and text dispatch already exist. Target behavior additionally completes `Join & Play` when the newly selected public target requires membership, performs required character discovery/creation, requests a fresh connect token only from the newly returned bundle, and retries on a new socket. Client rule for discovery-issued selectors: @@ -156,7 +156,7 @@ These handshake classes are edge-handshake outcomes, not gameplay text-protocol ### Current Implemented Browser Reconnect Behavior -Current first-party reconnect proof is limited to the protected-cookie path. When an unexpired in-memory `player-bootstrap` token remains, the client may request a fresh connect token for the current discovery scope, open a new `/ws/game/**` socket with the HttpOnly cookie, send bare `LOGIN`, and issue `PLAY` only when the current Account membership/admission fields and the other implemented checks pass. A page reload or expired bootstrap token restarts `POST /auth/player-bootstrap` and discovery. Current `CONNECT_SCOPE_MISMATCH` handling discards the stale bundle and reruns discovery, but missing or non-admitting membership remains unavailable/non-actionable because explicit `JOIN`/`Join & Play` and the target issuance reread are not implemented. A fresh edge reconnect never replays client input, raw bytes, WebSocket frames, unsent Telnet output, or a prior prompt; it may receive bounded semantic recent context, then a fresh authoritative `LOOK`. Target behavior emits exactly one current prompt only when both effective `firemud.presentation.prompt.enabled` and `firemud.presentation.prompt.emit-after-reconnect-restore` are enabled, or zero reconnect prompts if either is disabled. Current handler composition gates only `firemud.presentation.prompt.emit-after-reconnect-restore`, not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one. This structured-prompt discrepancy is a target-blocking implementation/proof gap: the frontend must not claim the complete two-setting behavior is implemented or proven. This behavior does not prove the target lifecycle, grant, generation, or independent membership-version reconnect contract. +Current first-party reconnect proof is limited to the protected-cookie path. When an unexpired in-memory `player-bootstrap` token remains, the client may request a fresh connect token for the current discovery scope, open a new `/ws/game/**` socket with the HttpOnly cookie, send bare `LOGIN`, and issue `PLAY` only when the current Account membership/admission fields and the other implemented checks pass. A page reload or expired bootstrap token restarts `POST /auth/player-bootstrap` and discovery. Current `CONNECT_SCOPE_MISMATCH` handling discards the stale bundle and reruns discovery, but missing or non-admitting membership remains unavailable/non-actionable until the required issuance reread and runtime/deployment proof are complete. The local explicit join route/writer and Game Session text dispatch now exist. A fresh edge reconnect never replays client input, raw bytes, WebSocket frames, unsent Telnet output, or a prior prompt; it may receive bounded semantic recent context, then a fresh authoritative `LOOK`. Target behavior emits exactly one current prompt only when both effective `firemud.presentation.prompt.enabled` and `firemud.presentation.prompt.emit-after-reconnect-restore` are enabled, or zero reconnect prompts if either is disabled. Current handler composition gates only `firemud.presentation.prompt.emit-after-reconnect-restore`, not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one. This structured-prompt discrepancy is a target-blocking implementation/proof gap: the frontend must not claim the complete two-setting behavior is implemented or proven. This behavior does not prove the target lifecycle, grant, generation, or independent membership-version reconnect contract. ### Target-Only First-Party Browser Reconnect Sequence diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index aa68c015bb..32fec0c4c9 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or `JOIN`. Explicit `JOIN`/`Join & Play` and the required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance remain unimplemented/proof gaps in the current runtime. On its fresh Account-authority path, current connect-token issuance and text `PLAY` consume the Account membership response fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. However, the live Account connect-token path checks the Session Redis replay/result cache before calling fresh entitlement or membership authority, so a replay-cache hit can return the stored success or failure without re-evaluating current entitlement or membership. That cache-hit bypass is current implementation drift; it does not satisfy the target fresh authority and durable replay revalidation contract. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. The obsolete implicit membership-writer surface has been removed. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains the non-actionable `JOIN_REQUIRED` outcome. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`. Current private/playtest text `PLAY` also requires the current realm grant, while current connect-token issuance validates pointer/visibility but not the private/playtest grant; target-only connect-token grant validation remains implementation drift. A connect token or returning shortcut must not be treated as authorization proof. Returning members may proceed through the current existing-membership path, but that behavior does not prove the target generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. +The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet runtime-complete; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or end-to-end `JOIN`. The local Account `POST /auth/bootstrap/join` route and `JoinPublicProductionMembership` operation, plus Game Session text `JOIN` dispatch, now exist; PostgreSQL execution, pending-operation recovery, and direct-text/first-party end-to-end proof remain gaps. The required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance also remains unimplemented/unproved. On its fresh Account-authority path, current connect-token issuance and text `PLAY` consume the Account membership response fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`. However, the live Account connect-token path checks the Session Redis replay/result cache before calling fresh entitlement or membership authority, so a replay-cache hit can return the stored success or failure without re-evaluating current entitlement or membership. That cache-hit bypass is current implementation drift; it does not satisfy the target fresh authority and durable replay revalidation contract. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. The obsolete implicit membership-writer surface has been removed. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains the non-actionable `JOIN_REQUIRED` outcome. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`. Current private/playtest text `PLAY` also requires the current realm grant, while current connect-token issuance validates pointer/visibility but not the private/playtest grant; target-only connect-token grant validation remains implementation drift. A connect token or returning shortcut must not be treated as authorization proof. Returning members may proceed through the current existing-membership path, but that behavior does not prove the target generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. --- @@ -42,7 +42,7 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The current implementation caveat remains: explicit join is unimplemented, current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The local Account JOIN route/RPC and Game Session text dispatch now exist, but current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Direct-text and first-party end-to-end proof and the required membership reread remain incomplete. For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current runtime has no lifecycle-state predicate: its current admission fields are `membershipExists` and `gameplayAdmissionAllowed`; `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current runtime validates pointer/visibility for this flow but not the private/playtest realm grant, so current shortcut and token behavior do not prove authorization. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: an eligible public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable while explicit `JOIN` is unimplemented. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains `JOIN_REQUIRED`. The separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from the Account endpoint's same-named current error. +The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: an eligible public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`. The local Account JOIN route/RPC and Game Session text dispatch now exist, but the full direct-text and first-party path and membership lifecycle/generation reread remain incomplete and unproved. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains `JOIN_REQUIRED`. The separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from the Account endpoint's same-named current error. Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. @@ -67,7 +67,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. - `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. - `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - Current public-production membership is missing or `INACTIVE` in the target-only Authentication flow. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action; current text reconnect instead stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation because explicit `JOIN` is unavailable. Private/playtest membership or grant failure is not a public join fallback. +- `JOIN_REQUIRED` - Current public-production membership is missing or non-admitting in the current consumer evidence; lifecycle-specific `INACTIVE` classification remains target-only. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. The local Account route/RPC and Game Session text dispatch now exist, but end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. @@ -80,7 +80,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - Clients connect using TCP/Telnet and are handled by a dedicated **TCP Proxy Service**. - For local development and explicitly private compatibility networks, the TCP Proxy Service listens on port `2323` by default. This plaintext/default port is not a public player-facing contract; public deployments must select one of the TLS modes below. The port and the Spring Cloud Gateway WebSocket URL can be adjusted with the `TCP_PROXY_PORT` and `GATEWAY_WS_URL` environment variables described in the [TCP Proxy Service configuration](./microservices/tcp-proxy-service/configuration.md#environment-variables). `GATEWAY_WS_URL` should always be set explicitly by deployment config; local Compose smoke also sets it explicitly to the canonical in-stack target. See [Environment Variables & Secrets Management](./infrastructure/environment-and-secrets.md) for general configuration guidance. Direct text/Telnet clients must issue fresh anonymous `WORLDS` before credential-bearing `LOGIN`, then follow the authenticated `REALMS`-to-`JOIN` procedure in [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The bridge carries the resulting text flow and does not create or restore membership; Game Session retains pending JOIN transport state under the contract below. Reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`; a complete `CLOSED` realm remains `REALM_UNAVAILABLE`. -Direct text/Telnet reconnect is a fresh transport and discovery path described in [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour). The proxy does not reuse a browser/WebSocket bootstrap snapshot or prior transport-local scope. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; explicit-join and membership-reread gaps remain those recorded in [Authentication](./system-architecture-authentication.md#implementation-status). +Direct text/Telnet reconnect is a fresh transport and discovery path described in [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour). The proxy does not reuse a browser/WebSocket bootstrap snapshot or prior transport-local scope. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite. The local Account JOIN route/RPC and Game Session text dispatch exist; lifecycle/generation reread and end-to-end runtime/deployment proof gaps remain those recorded in [Authentication](./system-architecture-authentication.md#implementation-status). Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` retains `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on these non-public (private/playtest) targets; an eligible public-production request remains `JOIN_REQUIRED`. It also requires the current realm grant, while connect-token grant validation remains implementation drift. The separate current Account connect-token mappings are recorded in the implementation status above and are not text-protocol outcomes. @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The explicit `JOIN` step is target-only while current text reconnect stops with non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production target because membership repair is unavailable; private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete; the current path can still stop with non-actionable `JOIN_REQUIRED` when membership/admission evidence is not admitting. Private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces and explicit `Join & Play` remains unavailable, so an eligible public-production membership that is missing (`membershipExists=false`) or existing but non-admitting (`gameplayAdmissionAllowed=false`) remains non-actionable `JOIN_REQUIRED` with no mutation; the latter cannot be classified specifically as `INACTIVE`; an existing non-admitting response cannot be classified as `INACTIVE` by the live adapter. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients stop with the same non-actionable `JOIN_REQUIRED` fallback when repair is required. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. The local `Join & Play` endpoint and Account writer exist, but lifecycle-aware admission, the required issuance reread, and complete runtime/deployment proof remain incomplete; an eligible public-production membership that is missing (`membershipExists=false`) or existing but non-admitting (`gameplayAdmissionAllowed=false`) therefore remains non-actionable `JOIN_REQUIRED` with no mutation; the latter cannot be classified specifically as `INACTIVE` by the live adapter. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients may still stop with the same non-actionable `JOIN_REQUIRED` outcome when membership evidence is not admitting, despite the local join dispatch existing. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. 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 4308aaf9de..4c5e6e7063 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -29,12 +29,12 @@ 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. 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.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. The durable recovery/reconciliation seam for JOIN left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision and ADR 0025; do not mark ADR 0025 complete. PostgreSQL runtime proof 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.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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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 payment scaffolds still retain provider-mutating drift. 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. Explicit JOIN exists locally through Account's public-production writer, but this does not prove the direct text-client path; the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains 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; 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, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains 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, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. 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 first-party post-logout replay cleanup are absent. | @@ -152,7 +152,7 @@ Account authority proof covers account-first tenantless bootstrap authentication - Account authentication has no stable attempt identity or replayable result contract. Game Session now avoids automatically retrying an ambiguous credential-consuming transport failure, but Account still needs durable request identity and idempotent result lookup before authentication itself is safely retryable. - Signup-time login-mode selection and authenticator-app TOTP enrollment/management are not implemented; the live credential contract remains password plus email OTP. Richer MFA policy for elevated users is also future work. - Tenant membership currently persists admission permission rather than the designed tenant-role set; Account JWT issuance does not emit tenant `scopedRoles`, and realm grants have no expiry or tenant-admin management surface. -- The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; `past_due` is currently gameplay-available and public-join-eligible. Durable `purchase_entitlement` fulfillment/revocation is also absent. +- The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; Current `past_due` gameplay/public-join eligibility matches the accepted policy; the missing snapshot fields and freshness gates above, not this allowance, are the gaps. Durable `purchase_entitlement` fulfillment/revocation is also absent. - Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam currently accept parameterized credentials, while public non-proxy `/ws/game/**` requires a verified connect-token context and bare `LOGIN`. - Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. - The first-party post-logout path still replays retained transcript context even though generic fresh login does not; that replay-projection mismatch must converge without treating durable transcript retention as reconnect eligibility. @@ -173,7 +173,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; local JOIN RPC is implemented, while leave and the public bootstrap join REST facade remain target-only | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; local `JoinPublicProductionMembership` RPC and `POST /auth/bootstrap/join` facade are implemented, while leave remains target-only | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted proxy/first-party handshake validation, signed connect context, stable edge socket/session id, upstream gameplay bridge and rebind | `/ws/game/**`; `TrustedTcpProxyIdentity`; connect-token and first-party context headers | From 67cd46266a9564174df3b49595ebe1bf7df2921c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:38:50 +1200 Subject: [PATCH 10/55] test: keep target-only route fixture on unroutable endpoint --- dev-tools/validation/test_check_authz_route_matrix.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index ae9d805c22..d9195fbc63 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -7031,7 +7031,7 @@ def test_role_assurance_rejects_legacy_vocabulary_shape(self): def test_legacy_target_only_route_declaration_is_rejected(self): document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) - route = route_for(document, "account-service", "POST /auth/bootstrap/join") + route = route_for(document, "account-service", "BillingArtifactsTenant") route.pop("route_status") route.setdefault("implementation_status", {})["target_only"] = True errors = validate_document(self.validator, document) From 965d4570a0caccfa38dc5329bb4144460abaa0df Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:44:23 +1200 Subject: [PATCH 11/55] docs: advance live Unit 1A index through Cycle 20 --- design/project-management/design-alignment/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 1973f82001..14701ed074 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Cycle 18 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–18 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and recorded the unresolved exact-binding reconnect token/lease handoff for Overseer without authorizing an LKG fallback. Cycle 17 exposed the concrete public-registration membership bypass of disabled public joining. Cycle 18 corrected stale corpus status: global-only registration, the local explicit `JOIN` operation, and the Account audit-ingress seam are implemented locally, while PostgreSQL execution, retained-data deployment disposition, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, lifecycle/authority-generation snapshot completion, and full billing evidence remain open. Drafts #2846, #2847, and #2848 are correction evidence only and do not establish corpus taper. The optional external-provider product summary now matches ADR 0049. Cycle 18 routed non-public realm-discovery leakage and stale join guidance to Unit 1B; those are not discarded. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 retains the target decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 20 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–20 were productive. Cycle 13 corrected fail-open empty/ambiguous subscription-row entitlement projection. Cycle 14 confirmed the full authority/consolidation lens and routed public `PLAY` admission-outcome ordering to Unit 1B. Cycle 15 corrected billing status/registration schema and classified retryable entitlement outages. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and routed exact-binding reconnect token/lease to Unit 1B without an LKG fallback. Cycle 17 exposed public-registration membership bypass; #2847 converged registration to global-only identity and explicit policy-bound JOIN, while #2848 supplies the durable audit receiver. Cycle 18 corrected current/target status and routed non-public realm-discovery/CHARS disclosure to Unit 1B. Cycle 19 fixed Account's canonical UUID realm binding and stale membership-response status. Cycle 20 corrected local JOIN availability claims, `past_due` status precision, and Account producer audit-payload compaction after verified receiver minimization. Drafts #2846–#2848 are correction evidence, not taper or merge readiness. PostgreSQL execution, retained-data deployment disposition, pending-operation recovery, direct text-to-Logging proof, lifecycle/generation snapshot completion, finite `COMMITTED` audit retention, and full billing evidence remain open. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 tracks the decision; explicit free/trial state, current-row authority, and strict new-binding controls remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | From 3fa6fd3941ff5b6230b1de0d4ea09283fd65bea9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:09:05 +1200 Subject: [PATCH 12/55] Make definitive JOIN policy conflicts terminal --- .../account-service/runtime-and-data.md | 2 +- .../service/impl/AccountServiceImpl.java | 8 +- .../service/impl/AccountServiceImplTest.java | 75 ++++++++++++++++++- 3 files changed, 76 insertions(+), 9 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1768603c29..744e01fc1e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,7 +16,7 @@ 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 or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A changed policy digest on a still-pending operation returns `IDEMPOTENCY_CONFLICT` without replacing its bound evidence or terminalizing that operation. 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. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. 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 or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. 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. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. 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. 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. 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 018319b58b..b403a19629 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 @@ -634,9 +634,7 @@ private JoinPublicProductionResult executeJoinAttempt( if (operation.requestDigest() != null && (!Integer.valueOf(1).equals(operation.requestDigestVersion()) || !operation.requestDigest().equals(requestDigest))) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, "AVAILABLE", "IDEMPOTENCY_CONFLICT"); - return pendingJoinFailure(scope, "IDEMPOTENCY_CONFLICT"); + return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); } if (operation.requestDigest() == null) { accountJoinOperationRepository.bindPolicyEvidence( @@ -670,9 +668,7 @@ private JoinPublicProductionResult executeJoinAttempt( commitEvaluation.allowPublicJoin(), commitEvaluation.entitlementVersion()); if (!requestDigest.equals(commitDigest)) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, "AVAILABLE", "IDEMPOTENCY_CONFLICT"); - return pendingJoinFailure(scope, "IDEMPOTENCY_CONFLICT"); + return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); } if (!commitEvaluation.gameplayAvailable()) { return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); 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 34d5629028..0de1da7673 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 @@ -540,10 +540,13 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { assertFalse(result.success()); assertEquals("IDEMPOTENCY_CONFLICT", result.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().lastAttemptFailureCode()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(1, retainedOperation.get().requestDigestVersion()); assertNotNull(retainedOperation.get().requestDigest()); + assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); @@ -551,6 +554,74 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { .findByTenantIdForUpdate(7L); } + @Test + void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription initialPolicy = new Subscription(); + initialPolicy.setId(22L); + initialPolicy.setTenantId(7L); + initialPolicy.setStatus("active"); + initialPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn( + java.util.List.of(initialPolicy), + java.util.List.of(), + java.util.List.of(changedPolicy)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-policy-retry-1"); + + JoinPublicProductionResult pending = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + String boundDigest = retainedOperation.get().requestDigest(); + String intentDigest = retainedOperation.get().intentDigest(); + + assertFalse(pending.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", pending.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + + JoinPublicProductionResult changedPolicyRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(changedPolicyRetry.success()); + assertEquals("IDEMPOTENCY_CONFLICT", changedPolicyRetry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); + assertEquals(intentDigest, retainedOperation.get().intentDigest()); + assertEquals(boundDigest, retainedOperation.get().requestDigest()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + } + @Test void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { Account account = new Account(); From a5a8af9af356f6c4a4abdee94fbf4c327567689a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:11:52 +1200 Subject: [PATCH 13/55] docs: align JOIN availability across access consumers --- .../microservices/tcp-proxy-service/README.md | 2 +- .../architecture/system-architecture-frontend.md | 4 ++-- .../system-architecture-multi-tenancy.md | 2 +- .../architecture/system-architecture-overview.md | 2 +- .../system-architecture-reconnection.md | 14 +++++++------- ...player-experience-commands-and-communication.md | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/design/architecture/microservices/tcp-proxy-service/README.md b/design/architecture/microservices/tcp-proxy-service/README.md index 0990b364a8..21929ea379 100644 --- a/design/architecture/microservices/tcp-proxy-service/README.md +++ b/design/architecture/microservices/tcp-proxy-service/README.md @@ -24,7 +24,7 @@ When code, tests, and docs diverge, align implementation to this doc set and the | Area | Target behaviour | Current status | Tracked in | | --- | --- | --- | --- | -| Telnet login-first flow | All Telnet clients must issue anonymous `WORLDS` before credential-bearing `LOGIN [secret]`; `LOGIN ` starts the email challenge. For public production, missing or `INACTIVE` membership must issue `JOIN` before `PLAY`; only an existing `ACTIVE` public-production member skips `JOIN`. Telnet shares the same admission pipeline as WebSocket clients. Any future classic-client semantic adapter is optional and cannot replace the plain-text flow or carry authority. `LOGIN` / `LOGON` semantics remain canonical in the Authentication & Authorization doc; this row only describes how Telnet traffic is forwarded into that flow. | `LOGIN [secret]` and `PLAY` are implemented with focused proof for currently supported, already-authorized admission. The current proxy still bootstraps a hidden default and does not enforce `WORLDS` before `LOGIN`; that is an implementation gap. For a publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED` without invoking the membership writer; other targets retain their own visibility and grant checks. Explicit `JOIN` remains unimplemented, and the connect-token membership-authority-generation reread remains a gap. Manual end-to-end QA also remains. | [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) | +| Telnet login-first flow | All Telnet clients must issue anonymous `WORLDS` before credential-bearing `LOGIN [secret]`; `LOGIN ` starts the email challenge. For public production, missing or `INACTIVE` membership must issue `JOIN` before `PLAY`; only an existing `ACTIVE` public-production member skips `JOIN`. Telnet shares the same admission pipeline as WebSocket clients. Any future classic-client semantic adapter is optional and cannot replace the plain-text flow or carry authority. `LOGIN` / `LOGON` semantics remain canonical in the Authentication & Authorization doc; this row only describes how Telnet traffic is forwarded into that flow. | `LOGIN [secret]` and `PLAY` are implemented with focused proof for currently supported, already-authorized admission. The current proxy still bootstraps a hidden default and does not enforce `WORLDS` before `LOGIN`; that is an implementation gap. For a publicly visible public-production target whose joining policy permits entry, missing or non-admitting membership returns `JOIN_REQUIRED` from `PLAY` without implicit membership mutation; other targets retain their own visibility and grant checks. The Account JOIN RPC and direct-text REALMS-scope/JOIN dispatch now exist locally, but PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and membership lifecycle/generation rereads remain unproved. The connect-token membership-authority-generation reread also remains a gap. Manual end-to-end QA remains outstanding. | [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) | | Proxy -> Gateway WebSocket mTLS | TCP Proxy is the WebSocket mTLS client: it presents the dedicated `FIREMUD_GATEWAY_WS_CLIENT_CERT_CHAIN_PATH` and `FIREMUD_GATEWAY_WS_CLIENT_PRIVATE_KEY_PATH` identity to the Gateway server, with `FIREMUD_GATEWAY_WS_CA_CERT_PATH` for trust, while Gateway verifies the exclusive environment-bound identity required by [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). This client identity is distinct from TCP Proxy's internal gRPC server mTLS identity and from the separate Telnet server-TLS identity. | TCP Proxy now loads and rotates the dedicated PEM client identity and Gateway CA into one hostname-verifying client shared by gameplay bridges and Gateway readiness, rejects plaintext unless an explicit local/dev/test profile is active, and fails new admission closed after an invalid reload. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with the dedicated authenticated Gateway listener, separate Gateway-server/TCP-Proxy-client Secret mounts, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending; controller-owned certificate issuance/projection and live peer-handshake, rotation/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. | [Platform Operations and Delivery](../../../project-management/implementation-tracking/platform-operations-and-delivery.md) | | Optional classic-client semantic extensions | Plain text remains universal. MCP/GMCP/Telnet semantic negotiation and package support are deferred, unadvertised, and unsupported in shared, player-facing, and prod-like profiles; an explicit local/development/test profile may enable only the legacy marker/greeting seam for bounded development use. If a future adapter is selected, Game Session owns semantics while TCP Proxy remains a generic bounded bridge. | The current `TCP_PROXY_MCP_ENABLED` marker/greeting seam is implementation drift, not semantic support. Target startup rejects it in shared, player-facing, and prod-like profiles; only explicit local/development/test profiles may enable the marker, and the profile rejection is not yet proved. No interoperability or end-to-end extension proof exists. | [MCP-01](../../decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | | Connection limits and abuse protection | Connection caps, idle timeouts, input size limits, buffering, and generic opaque-marker safety protect the DMZ boundary. TCP Proxy does not parse or maintain classic-client semantic state. Accepted input that exceeds a generic limit or cannot be forwarded under backpressure receives an explicit error/close rather than a keep-open silent discard. | Core limit handling is implemented; tuning and additional metrics may evolve as production behaviour is observed. | [Platform Operations and Delivery](../../../project-management/implementation-tracking/platform-operations-and-delivery.md) | diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 917f492667..fa69528497 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -20,9 +20,9 @@ The first-party browser consumes the existing Account/Gateway APIs and the versi The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output, but the independently released static host, public-site routing and delivery (including the target `/auth/**` rewrite), health/security/cache behavior, rollback, and bounded end-to-end browser proof are not implemented or proved. Those gaps remain target implementation obligations rather than evidence that the supported frontend boundary is live. -Explicit `JOIN`/`Join & Play` is implemented locally in the stacked Access draft, but the complete target runtime flow is not yet proved. In the target, `JoinPublicProductionMembership` is the sole membership writer for explicit public-production join, creating missing membership or restoring `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current membership response also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current consumers enforce only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; current connect-token issuance and text `PLAY` proceed only when the two admission fields are true, and an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the consumer does not classify the latter specifically as `INACTIVE` despite the emitted lifecycle field. The obsolete implicit membership-writer surface has been removed. The local explicit `JOIN` operation is not a production-ready frontend repair until UUID realm binding, retained-data deployment disposition, and end-to-end proof pass; the required connect-token `membershipVersion` plus `membershipAuthorityGeneration` reread remains an implementation/proof gap. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. The frontend availability gate applies to the otherwise eligible current `membershipExists=false` or existing `gameplayAdmissionAllowed=false` cases; the current consumer does not classify the latter as `INACTIVE`, and target lifecycle-specific handling of missing or `INACTIVE` membership remains incomplete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership response fields, grant, entitlement, and routing checks pass; target generation/version rereads remain unimplemented. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. +The Account explicit `JOIN` RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch exist locally, but this does not establish the complete target runtime flow or production readiness. In the target, `JoinPublicProductionMembership` is the sole membership writer for explicit public-production join, creating missing membership or restoring `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current membership response and consumers remain incomplete for the target lifecycle contract: consumers enforce only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; eligible public-production `PLAY` with either non-admitting boolean may fail closed with non-actionable `JOIN_REQUIRED`, without classifying the latter specifically as `INACTIVE`. PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, retained-data deployment disposition, and the independent connect-token `membershipVersion` plus `membershipAuthorityGeneration` reread remain unproved. The obsolete implicit membership-writer surface has been removed. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. The frontend availability gate applies to otherwise eligible current missing or non-admitting membership; target lifecycle-specific handling and full first-join UX remain incomplete. Returning members and grant-backed private/playtest flows remain eligible only when current membership response fields, grant, entitlement, and routing checks pass; target generation/version rereads remain unproved. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. -The explicit `JOIN`/`Join & Play` action and the independent `membershipVersion` plus `membershipAuthorityGeneration` reread at connect-token issuance are both unimplemented/proof gaps. Until both are implemented and proven, the frontend must keep first public-production entry with a missing or non-admitting current membership response fail-closed and unavailable rather than exposing a retry path that can create membership implicitly or issue a token from stale authority. Returning members and private/playtest callers with existing membership remain eligible when the live response fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and the other current admission checks pass; the exact `membershipAuthorityGeneration` and independent issuance-time `membershipVersion` rereads remain target/proof gaps. Target lifecycle-specific handling of missing or `INACTIVE` membership remains unavailable until that target response exists. This status is the frontend summary of the target/current distinction in [Authentication & Authorization](./system-architecture-authentication.md#implementation-status). +The local browser bootstrap join facade is present, while the complete frontend first-join action and the independent `membershipVersion` plus `membershipAuthorityGeneration` reread at connect-token issuance remain unproved. Until the full path is implemented and proven, the frontend must keep first public-production entry fail-closed when current membership evidence is missing or non-admitting; it must not issue a token from stale authority. Returning members and private/playtest callers with existing membership remain eligible when the live response fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and the other current admission checks pass; the exact `membershipAuthorityGeneration` and independent issuance-time `membershipVersion` rereads remain proof gaps. Target lifecycle-specific handling of missing or `INACTIVE` membership remains incomplete. This status is the frontend summary of the target/current distinction in [Authentication & Authorization](./system-architecture-authentication.md#implementation-status). ### Persisted actor entry UX boundary (PLAYER-01) diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 43b67cfcbf..6651f2d97b 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -14,7 +14,7 @@ The complete playtest initialization and lifecycle contract is owned by [ADR 013 ## Implementation Status -The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the membership-generation live reread at connect-token issuance is not implemented; pointer updates still use a read-then-write check with separate pointer/audit/prepared-execution writes; scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Explicit `JOIN`/`Join & Play` remains unimplemented, so the first-join flow remains target-state only. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` contract. +The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the Account explicit JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch exist locally. The complete first-join path is not yet proved: PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and the membership-generation live reread at connect-token issuance remain gaps. Pointer updates still use a read-then-write check with separate pointer/audit/prepared-execution writes; scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` contract. --- diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index 24d7824cf3..7ae77bec21 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -529,7 +529,7 @@ Gameplay authentication is transport-specific. Credential-bearing Telnet and oth The receiver token is the exact `game-session-account-delegation` JWT profile with audience `account-service`; it is an Account-issued private backend credential, never a client gameplay credential. Its registry and rotation rules do not define the active gameplay-session lifetime or the bounded continuity/reconnect cache lifetime. If the Account response is lost during credential-bearing text login, Game Session retries with the same `requestId` and exact request digest. Account resumes matching pending work or returns the stored committed result/terminal outcome; it must not mint a second token merely because the first response was not observed. A confirmed binding-CAS conflict or superseded binding causes Game Session to keep the candidate unusable and issue Account's idempotent retire request for that exact operation and token identity. An ambiguous timeout instead remains fail-closed and provisional while Game Session reconciles the expected binding generation plus operation identity against the authoritative binding: it retires the candidate only after proving that the CAS did not commit, and completes installation or the canonical superseded outcome when the committed operation is found. Account performs bounded orphan cleanup after the operation's lease/expiry horizon; an orphan registry record is never sufficient to make a gameplay binding admissible. Proof must cover Account success followed by response loss, confirmed binding-CAS conflict, ambiguous CAS reconciliation for both committed and uncommitted outcomes, retry with the same request ID, retry with a conflicting digest, and cleanup/reconciliation after each cross-service failure window. The protocol uses ordered durable evidence, idempotent owner-side operations, and fail-closed provisional state; it does not claim a cross-store transaction. -After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Current eligible public missing or existing non-admitting membership instead returns non-actionable `JOIN_REQUIRED` because explicit `JOIN` is unimplemented, while the target additionally requires the exact fresh membership generation/version reread. Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). +After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Current eligible public missing or existing non-admitting membership still returns non-actionable `JOIN_REQUIRED` from `PLAY`. The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch now exist locally, but this does not establish frontend or production readiness: PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and membership lifecycle/generation rereads remain unproved. Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Session recovery/takeover is authorized by the gameplay binding plus current Account identity, membership, entitlement, and revocation authority; it does not require the previous backend token registry record to remain valid. When transport-specific reauthentication is required, the client must complete the applicable fresh credential/bootstrap and connect-context steps before backend calls resume. A missing or expired prior token therefore causes replacement or reauthentication, not acceptance of stale token state. > 🔗 See [Authentication & Authorization](./system-architecture-authentication.md) and [Reconnection Strategy](./system-architecture-reconnection.md) for detailed JWT format and session flow. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 1b1125c071..bc5dda1145 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,7 +10,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current first-party connect-token issuance and text `PLAY` use the fresh current Account fields `membershipExists` and `gameplayAdmissionAllowed` and admit only when both are true; an otherwise eligible public-production request with `membershipExists=false` fails closed with non-actionable `JOIN_REQUIRED`, while an existing response with `gameplayAdmissionAllowed=false` remains the established denial. The current response has no lifecycle state, so current admission is not classified as `ACTIVE` or `INACTIVE`; this boolean predicate is not proof of the target `ACTIVE` lifecycle requirement. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. Explicit `JOIN`/`Join & Play` and the required connect-token membership-authority/version rereads remain unimplemented/proof gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current first-party connect-token issuance and text `PLAY` use the fresh current Account fields `membershipExists` and `gameplayAdmissionAllowed` and admit only when both are true; an otherwise eligible public-production request with `membershipExists=false` fails closed with non-actionable `JOIN_REQUIRED`, while an existing response with `gameplayAdmissionAllowed=false` remains the established denial. The current response has no lifecycle state, so current admission is not classified as `ACTIVE` or `INACTIVE`; this boolean predicate is not proof of the target `ACTIVE` lifecycle requirement. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch exist locally; PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and the required connect-token membership-authority/version rereads remain unproved. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. - **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -78,8 +78,8 @@ A retained-edge upstream rebind, including a qualifying hidden Game Session rest Reconnection uses two distinct client flows: -- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its target-only `JOIN` procedure; ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Current text reconnect instead stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation because explicit `JOIN` is unavailable. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. -- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the explicit join endpoint remains unimplemented in the current runtime. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. +- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its `JOIN` procedure; local direct-text REALMS-scope/JOIN dispatch and the Account JOIN RPC exist, while PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and lifecycle/generation rereads remain unproved. Ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Current text `PLAY` still returns non-actionable `JOIN_REQUIRED` when eligible public membership is missing or non-admitting; completion of the local JOIN path does not establish the whole flow. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. +- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the browser bootstrap join facade exists locally, but the complete frontend/runtime flow and proof remain incomplete. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. @@ -89,7 +89,7 @@ A client must not infer current membership or target identity from a stale Redis ### Public membership repair during reconnect (normative) -Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. Current text reconnect stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation; first-party browser/mobile bootstrap/connect-token surfaces remain partial and the complete flow is target-only. +Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete; text `PLAY` still returns non-actionable `JOIN_REQUIRED` until explicit membership is joined. Redis-backed session state allows resumable recovery when the gameplay binding is still logically valid, or a fresh login when it is not. The canonical continuity anchor, resume episode, physical TTL rules, token refresh, and transcript authority are defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Reconnection retains only this transport consequence: Redis key presence alone never authorizes resume, and a new transport never replays prior bytes. @@ -211,14 +211,14 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Current text clients stop with non-actionable `JOIN_REQUIRED` and no membership mutation when an otherwise eligible public-production request reports `membershipExists=false` and target-only public repair would be required. An existing response with `gameplayAdmissionAllowed=false` remains the established denial. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. -- Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. Current first-party browser/mobile bootstrap/connect-token surfaces are partial and the complete flow, including `Join & Play`, remains target-only. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). +- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Text `PLAY` still returns non-actionable `JOIN_REQUIRED` when otherwise eligible public-production membership is missing or non-admitting; local direct-text REALMS-scope/JOIN dispatch and Account RPC exist, but PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. An existing non-admitting response is not classified specifically as `INACTIVE`. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. +- Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. The local browser bootstrap join facade exists, while full first-party browser/mobile flow and proof remain incomplete. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/target-only conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text stops with non-actionable `JOIN_REQUIRED` and no membership mutation only when an otherwise eligible public-production request reports `membershipExists=false` and explicit `JOIN` is required. An existing response with `gameplayAdmissionAllowed=false` remains the established denial. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text `PLAY` returns non-actionable `JOIN_REQUIRED` when otherwise eligible public-production membership is missing or non-admitting. The local direct-text dispatch and Account JOIN RPC exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index dfa5d621ff..6a5faac8cc 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -51,7 +51,7 @@ This section records implementation and proof status only. The target command, p Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the direct gameplay-binding path for existing members. Realm and character discovery helpers are currently not required ceremony. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. An unambiguous eligible `PLAY` enters directly; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The current admission gaps are explicit `JOIN`, realm-scoped discovery/character ceremony, and the connect-token membership-authority-generation reread. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings are implemented and covered by focused `PlayCommandHandlerTest` and `AccountServiceImplTest` cases; canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch now exist locally. Remaining admission gaps include PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, realm-scoped discovery/character ceremony, and the connect-token membership-authority-generation reread; the current membership lifecycle/generation snapshot is also incomplete. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings are implemented and covered by focused `PlayCommandHandlerTest` and `AccountServiceImplTest` cases; that focused proof does not establish the complete JOIN flow. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation From cde86415522f5f21b7e995535c6023a8d7259841 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:14:42 +1200 Subject: [PATCH 14/55] docs: align historical JOIN status and Unit 1A Cycle 21 index --- design/project-management/design-alignment/README.md | 2 +- .../design-alignment/consequential-decision-inventory.md | 2 +- .../design-alignment/decision-inventory-cross-cutting.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 14701ed074..ab2912532a 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Cycle 20 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–20 were productive. Cycle 13 corrected fail-open empty/ambiguous subscription-row entitlement projection. Cycle 14 confirmed the full authority/consolidation lens and routed public `PLAY` admission-outcome ordering to Unit 1B. Cycle 15 corrected billing status/registration schema and classified retryable entitlement outages. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and routed exact-binding reconnect token/lease to Unit 1B without an LKG fallback. Cycle 17 exposed public-registration membership bypass; #2847 converged registration to global-only identity and explicit policy-bound JOIN, while #2848 supplies the durable audit receiver. Cycle 18 corrected current/target status and routed non-public realm-discovery/CHARS disclosure to Unit 1B. Cycle 19 fixed Account's canonical UUID realm binding and stale membership-response status. Cycle 20 corrected local JOIN availability claims, `past_due` status precision, and Account producer audit-payload compaction after verified receiver minimization. Drafts #2846–#2848 are correction evidence, not taper or merge readiness. PostgreSQL execution, retained-data deployment disposition, pending-operation recovery, direct text-to-Logging proof, lifecycle/generation snapshot completion, finite `COMMITTED` audit retention, and full billing evidence remain open. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 tracks the decision; explicit free/trial state, current-row authority, and strict new-binding controls remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 21 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–21 were productive. Cycle 13 corrected fail-open empty/ambiguous subscription-row entitlement projection. Cycle 14 confirmed the full authority/consolidation lens and routed public `PLAY` admission-outcome ordering to Unit 1B. Cycle 15 corrected billing status/registration schema and classified retryable entitlement outages. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and routed exact-binding reconnect token/lease to Unit 1B without an LKG fallback. Cycle 17 exposed public-registration membership bypass; #2847 converged registration to global-only identity and explicit policy-bound JOIN, while #2848 supplies the durable audit receiver. Cycle 18 corrected current/target status and routed non-public realm-discovery/CHARS disclosure to Unit 1B. Cycle 19 fixed Account's canonical UUID realm binding and stale membership-response status. Cycle 20 corrected local JOIN availability claims, `past_due` status precision, and Account producer audit-payload compaction after verified receiver minimization. Cycle 21 terminalized deterministic changed-policy JOIN conflicts in #2847 and corrected further stale local-JOIN status in #2848 consumer docs and historical decision inventories. Drafts #2846–#2848 are correction evidence, not taper or merge readiness. PostgreSQL execution, retained-data deployment disposition, unknown-commit recovery, direct text-to-Logging proof, lifecycle/generation snapshot completion, finite `COMMITTED` audit retention, and full billing evidence remain open. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 tracks the decision; explicit free/trial state, current-row authority, and strict new-binding controls remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 1b743c7f3d..ac88bf60ac 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -149,7 +149,7 @@ No implementation-blocking import override is active. Record an override here wi ### Packet 2: Identity, Authority, And Security -Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`, but `POST /auth/bootstrap/join` is target-state and not implemented; current text `PLAY` and connect-token issuance require existing caller-bound membership and return canonical `JOIN_REQUIRED` for eligible missing or `INACTIVE` public-production membership, while the obsolete implicit membership-writer RPC/client/service seam has been removed. The target admission contract retains `JOIN_REQUIRED` for policy-permitted missing or `INACTIVE` membership. `WORLD_ACCESS_DENIED` is reserved for another reachable authoritative world/tenant denial and is mutually exclusive with `JOIN_REQUIRED`. A realm grant never substitutes for membership, and the connect-token membership-version plus membership-authority-generation reread remains a gap. The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices, not proof claims: the owning [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status) records the missing tenant-scoped roles, switching controls, and implementation state, while its [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof) section records focused evidence and remaining proof gaps. +Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`; the Account explicit `JOIN` path, including browser `POST /auth/bootstrap/join`, and direct-text REALMS-scope/JOIN dispatch now exist locally. Current text `PLAY` and connect-token issuance require existing caller-bound membership and return canonical `JOIN_REQUIRED` for eligible missing or `INACTIVE` public-production membership, while the obsolete implicit membership-writer RPC/client/service seam has been removed. Full workflow/deployment/PostgreSQL/direct text-to-Logging proof, pending unknown-outcome reconciliation, and membership lifecycle/generation rereads remain open. The target admission contract retains `JOIN_REQUIRED` for policy-permitted missing or `INACTIVE` membership. `WORLD_ACCESS_DENIED` is reserved for another reachable authoritative world/tenant denial and is mutually exclusive with `JOIN_REQUIRED`. A realm grant never substitutes for membership, and the connect-token membership-version plus membership-authority-generation reread remains a gap. The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices, not proof claims: the owning [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status) records the missing tenant-scoped roles, switching controls, and implementation state, while its [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof) section records focused evidence and remaining proof gaps. Packet 2 count reconciliation: the 31 reviewed decisions are covered by the checked dispositions for ADRs 0020-0050, excluding the historical service-scan alias. The Packet 2 disposition contains exactly those 31 reviewed decisions; the alias is navigation-only and is not a checked disposition row. diff --git a/design/project-management/design-alignment/decision-inventory-cross-cutting.md b/design/project-management/design-alignment/decision-inventory-cross-cutting.md index 4886445561..8a01c45a99 100644 --- a/design/project-management/design-alignment/decision-inventory-cross-cutting.md +++ b/design/project-management/design-alignment/decision-inventory-cross-cutting.md @@ -94,11 +94,11 @@ The first 22 source-index entries are the counted cross-cutting partition. `WE`, | Key | Primary capability | Secondary capabilities | Question -> current choice | Status | I/R | Sources / explicit ADR | Strongest alternative | ADR recommendation | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `AUTH-01` | `AA-3.1` | `AA-2.1`, `AA-3.3`, `SF-1.2` | What identifies gameplay selection/admission and controller ownership? Stable `worldSlug`/`realmSlug` and snapshot-bound ordinals are lobby selectors. Selection/admission resolves the authoritative gameplay binding `{tenantId, realmId, gameInstanceId, characterId}` plus the applicable pointer/fence, `playableStateNamespaceId`, and server-derived scope evidence; `gameInstanceId` remains the active-runtime fence/value, and slugs and ordinals never grant authority. Separately, the single-controller uniqueness key is exactly `{tenantId, playableStateNamespaceId, characterId}`; `gameInstanceId` is not part of controller uniqueness. | `accepted-explicit` | H/hard | `AU § Contract Decisions (Normative)`; `MT § Identity & Tenant Model`; [ADR 0168](../../architecture/decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [Session Behavior](../../architecture/system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) | Opaque handles for every selection, durable slug authority, fresh-catalog ordinal reuse, or per-instance controller identity. | Human review revised and superseded ADR 0005 on 2026-07-21. ADRs 0122 and 0132 continue to own stable playable-state namespaces and namespace-scoped controller transfer. | -| `AUTH-02` | `AA-2.1` | `PO-2.2`, `PO-2.1`, `SF-1.3`, `EA-3.1` | What is the player authentication sequence? Public `WORLDS` remains a browse-only pre-authentication mode. The target authenticated WebSocket flow is player bootstrap -> membership-aware discovery -> conditional explicit `JOIN` for first public-production entry -> character selection or creation -> single-use connect token -> WebSocket -> bare `LOGIN` -> `PLAY`. Browsers carry the token in the protected cookie; explicitly classified non-browser WebSocket clients use the dedicated handshake header. Returning members skip the public-production `JOIN` step only after the target current `ACTIVE` membership and exact reread evidence pass. Grant-backed admission requires existing durable `membershipLifecycleState=ACTIVE` membership and separately validates the applicable realm grant; a grant never creates or substitutes for membership. A nonmember must use the Account-owned membership lifecycle, such as explicit `JOIN`/`Join & Play` for eligible public production, before admission. Telnet and other non-WebSocket text clients retain credential-bearing protocol `LOGIN`. Ordinary gameplay supports `PASSWORD` or verified-email `EMAIL_OTP` without mandatory TOTP. **Current state:** the dedicated non-browser WebSocket handshake header is target-only and unavailable; unsupported header use is rejected as `CONNECT_TOKEN_REJECTED` without cookie fallback or carrier inference. Both text `PLAY` and `POST /auth/connect-token` admit only when `membershipExists && gameplayAdmissionAllowed`; neither response classifies `ACTIVE` versus `INACTIVE`. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a public-production target when either boolean is false and `WORLD_ACCESS_DENIED` for a non-public target. Connect-token issuance returns `JOIN_REQUIRED` for a non-admitting public-production target when `allowPublicJoin=true`, `PUBLIC_PRODUCTION_ADMISSION_DENIED` when public joining is disabled, `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership, and `CONNECT_TOKEN_REJECTED` for existing but non-admitting non-public membership. Explicit `JOIN` remains unimplemented, so that text `PLAY` result is not an actionable recovery flow. | `accepted-explicit` | H/hard | [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0029](../../architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md); `AU § Login and Session Flow`; `GW § Tenant-Aware Edge Connect Token (Gameplay Handshake)`; `RC § When Reauthentication Is Required` | Complete WebSocket login at the handshake, replay credentials in WebSocket `LOGIN`, or require TOTP/WebAuthn for every gameplay connection. | Revised and accepted by human decision; ADR 0021 records the sequence and factors, while ADR 0029 subsequently standardizes connect-token carriage for every public non-proxy WebSocket. | +| `AUTH-02` | `AA-2.1` | `PO-2.2`, `PO-2.1`, `SF-1.3`, `EA-3.1` | What is the player authentication sequence? Public `WORLDS` remains a browse-only pre-authentication mode. The target authenticated WebSocket flow is player bootstrap -> membership-aware discovery -> conditional explicit `JOIN` for first public-production entry -> character selection or creation -> single-use connect token -> WebSocket -> bare `LOGIN` -> `PLAY`. Browsers carry the token in the protected cookie; explicitly classified non-browser WebSocket clients use the dedicated handshake header. Returning members skip the public-production `JOIN` step only after the target current `ACTIVE` membership and exact reread evidence pass. Grant-backed admission requires existing durable `membershipLifecycleState=ACTIVE` membership and separately validates the applicable realm grant; a grant never creates or substitutes for membership. A nonmember must use the Account-owned membership lifecycle, such as explicit `JOIN`/`Join & Play` for eligible public production, before admission. Telnet and other non-WebSocket text clients retain credential-bearing protocol `LOGIN`. Ordinary gameplay supports `PASSWORD` or verified-email `EMAIL_OTP` without mandatory TOTP. **Current state:** the dedicated non-browser WebSocket handshake header is target-only and unavailable; unsupported header use is rejected as `CONNECT_TOKEN_REJECTED` without cookie fallback or carrier inference. Both text `PLAY` and `POST /auth/connect-token` admit only when `membershipExists && gameplayAdmissionAllowed`; neither response classifies `ACTIVE` versus `INACTIVE`. Text `PLAY` returns `JOIN_REQUIRED` for a public-production target when either boolean is false and `WORLD_ACCESS_DENIED` for a non-public target; direct-text REALMS-scope/JOIN dispatch now exists locally. Connect-token issuance returns `JOIN_REQUIRED` for a non-admitting public-production target when `allowPublicJoin=true`, `PUBLIC_PRODUCTION_ADMISSION_DENIED` when public joining is disabled, `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership, and `CONNECT_TOKEN_REJECTED` for existing but non-admitting non-public membership. The Account explicit `JOIN` path, including browser `POST /auth/bootstrap/join`, also exists locally. Full workflow/deployment/PostgreSQL/direct text-to-Logging proof, pending unknown-outcome reconciliation, and membership lifecycle/generation rereads remain open. | `accepted-explicit` | H/hard | [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0029](../../architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md); `AU § Login and Session Flow`; `GW § Tenant-Aware Edge Connect Token (Gameplay Handshake)`; `RC § When Reauthentication Is Required` | Complete WebSocket login at the handshake, replay credentials in WebSocket `LOGIN`, or require TOTP/WebAuthn for every gameplay connection. | Revised and accepted by human decision; ADR 0021 records the sequence and factors, while ADR 0029 subsequently standardizes connect-token carriage for every public non-proxy WebSocket. | | `AUTH-03` | `AA-1.3` | `AA-1.2`, `AA-1.5`, `AA-2.3`, `SF-1.3`, `SF-2.2` | Who owns identity, revocation, entitlements, and gameplay bindings? Account owns durable account, token, revocation, membership, entitlement, and the single issued-token registry authority; JWT-presenting registry-backed control-plane, bootstrap, and admission operations perform exactly one registry lookup, while Game Session owns gameplay bindings and derives typed execution context and Gateway has only bounded edge checks. The dedicated `gameplay-connect` artifact remains outside the issued-token registry and uses its own single-use replay fence. | `accepted-explicit` | H/hard | [ADR 0022](../../architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); `AU § Responsibility Split`; `OV § Authentication Modes and Boundaries`; `RM § Notes on Movement and Moderation Contracts` | Introduce a dedicated IAM service, make Gateway the general identity authority, or use TTL-only tokens. | Affirmed by human decision; ADR 0022 records one writer per authority and separates accepted design from revocation/session implementation gaps. | | `AUTH-04` | `SF-1.3` | `AA-1.2`, `PO-1.1`, `PO-2.1`, `PO-4.4` | How are protected routes authorized? One machine-readable route policy governs strict token profiles, explicit tenant/cross-tenant scopes, generated completeness checks, and runtime denial of unclassified routes; services retain domain checks. | `accepted-explicit` | H/hard | [ADR 0023](../../architecture/decisions/adr-0023-central-route-authorization-governance.md); `AU § Auth Middleware Algorithm (Normative)`; `AU § Global Role to Route-Class Matrix (Normative)`; `OV § Admin Entry Points and Traffic Surfaces` | Service-local role checks, Gateway-only authorization, or a general-purpose external policy engine. | Revised and accepted by human decision; policy/proof upkeep is an accepted security tradeoff and current enforcement gaps are explicit. | | `AUTH-05` | `SF-1.3` | `SF-1.2`, `SF-1.1`, `GR-1.1`, `PO-3.2` | How is internal player delegation trusted? Concrete mTLS workload identity and exact method caller allowlists authorize the trusted gameplay service; unsigned typed `PlayerExecutionContext` carries validated scope, while mutations retain operation-specific idempotency. | `accepted-explicit` | H/hard | [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md); `AU § Gameplay Player Execution Context Contract (Normative)`; `SE § Gameplay Workload Trust`; `GR § TLS Requirements` | Per-RPC signed/replay-guarded attestations, signed attestations without replay storage, or generic backend JWTs carrying player identity. | Revised and accepted by human decision after two-sided adversarial review; the current first-party trust domain explicitly accepts allowlisted-intermediary impersonation risk to avoid universal hot-path attestation cost. | -| `AUTH-06` | `AA-1.2` | `AA-1.1`, `AA-3.2`, `AA-2.1`, `EA-3.1` | What does first public-production join mean? **Target:** one explicit `JOIN`/`Join & Play` action creates the durable Account-owned player membership used for the player's game library and future return; token issuance and `PLAY` never create it implicitly. **Current state:** both text `PLAY` and `POST /auth/connect-token` admit only when `membershipExists && gameplayAdmissionAllowed`; neither response classifies `ACTIVE` versus `INACTIVE`. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a public-production target when either boolean is false and `WORLD_ACCESS_DENIED` for a non-public target. Connect-token issuance returns `JOIN_REQUIRED` for a non-admitting public-production target when `allowPublicJoin=true`, `PUBLIC_PRODUCTION_ADMISSION_DENIED` when public joining is disabled, `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership, and `CONNECT_TOKEN_REJECTED` for existing but non-admitting non-public membership. The obsolete implicit membership-writer seam has been removed, explicit `JOIN` is not implemented, and the connect-token membership-authority-generation reread remains a gap. For private/playtest targets, target text behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED` and requires existing `ACTIVE` membership plus the applicable grant. | `accepted-explicit` | H/hard | [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); `AU § Login and Session Flow`; `MT § Account-to-Game Relationships` | Implicit membership during connect/`PLAY`, invitation/approval, or ephemeral visitors. | Revised and accepted by human decision; durable membership is a product feature, with explicit intent, transactional audit/outbox, leave lifecycle, and abuse controls. | +| `AUTH-06` | `AA-1.2` | `AA-1.1`, `AA-3.2`, `AA-2.1`, `EA-3.1` | What does first public-production join mean? **Target:** one explicit `JOIN`/`Join & Play` action creates the durable Account-owned player membership used for the player's game library and future return; token issuance and `PLAY` never create it implicitly. **Current state:** both text `PLAY` and `POST /auth/connect-token` admit only when `membershipExists && gameplayAdmissionAllowed`; neither response classifies `ACTIVE` versus `INACTIVE`. Text `PLAY` returns `JOIN_REQUIRED` for a public-production target when either boolean is false and `WORLD_ACCESS_DENIED` for a non-public target; direct-text REALMS-scope/JOIN dispatch now exists locally. Connect-token issuance returns `JOIN_REQUIRED` for a non-admitting public-production target when `allowPublicJoin=true`, `PUBLIC_PRODUCTION_ADMISSION_DENIED` when public joining is disabled, `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership, and `CONNECT_TOKEN_REJECTED` for existing but non-admitting non-public membership. The obsolete implicit membership-writer seam has been removed, and the Account explicit `JOIN` path, including browser `POST /auth/bootstrap/join`, exists locally. Full workflow/deployment/PostgreSQL/direct text-to-Logging proof, pending unknown-outcome reconciliation, and membership lifecycle/generation rereads remain open. For private/playtest targets, target text behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED` and requires existing `ACTIVE` membership plus the applicable grant. | `accepted-explicit` | H/hard | [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); `AU § Login and Session Flow`; `MT § Account-to-Game Relationships` | Implicit membership during connect/`PLAY`, invitation/approval, or ephemeral visitors. | Revised and accepted by human decision; durable membership is a product feature, with explicit intent, transactional audit/outbox, leave lifecycle, and abuse controls. | | `AUTH-07` | `AA-1.2` | `AA-2.1`, `PO-1.1`, `PO-1.2`, `EA-3.3` | Can global roles grant gameplay authority? No: global roles cannot admit or elevate gameplay, staff join as ordinary players unless given explicit tenant-scoped gameplay capabilities, and the target has no impersonation or hidden observation. | `accepted-explicit` | H/hard | [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); `AU § Role Model`; `AU § Global Role to Route-Class Matrix (Normative)`; `OV § Moderation, Restriction, and Appeal Authority (Canonical)` | Global-role gameplay bypass, audited time-bounded impersonation, or read-only live observation. | Revised and accepted by human decision; current global `platformAdmin` to in-game `ADMIN` classification is implementation drift, while support remains on purpose-built control-plane and diagnostic surfaces. | | `TENANT-01` | `AA-3.3` | `AA-3.1`, `AA-3.2`, `AR-3.2`, `GR-2.1`, `GR-1.1` | How is a realm admitted? A Game Session-owned route is `OPEN` on exactly one instance or explicitly `CLOSED`; atomic pointer versions govern new/renewed bindings, while active source sessions end through bounded drain rather than per-action revalidation. | `accepted-explicit` | H/hard | [ADR 0027](../../architecture/decisions/adr-0027-single-realm-admission-target.md); `MT § Realm Catalog and Admission-Pointer Contract`; `VR § Realm Routing Contract For Player-Addressable Realms`; `OV § Design-Time vs Runtime World Data` | An instance-placement pool behind one realm, mutable latest-version lookup, or client-selected instance. | Revised and accepted by human decision; one shared world scales inside one instance, while explicit realms represent separate worlds and implementation must converge on tenant-qualified atomic CAS and cutover bookkeeping. | | `TENANT-02` | `AA-1.5` | `PO-3.1`, `PO-3.2`, `SF-2.2`, `GR-1.3` | Shared services, PostgreSQL, Coordination Redis, Cache/Rate-Limit Redis, and cluster capacity are the only supported normal multi-tenant topology; logical tenant scoping, authorization, quotas, and service ownership provide isolation. The environment-wide incident and recovery blast radius is accepted. A demonstrated future hard-isolation requirement uses a separately reviewed complete environment, not a hybrid selectively dedicated tenant data plane. | `accepted-explicit` | H/med | [ADR 0041](../../architecture/decisions/adr-0041-shared-tenant-infrastructure-with-full-environment-isolation-gate.md); `MT § Data Separation per Service`; `MT § Tenant Configuration & Scaling`; `OV § Multi-Tenancy Enforcement` | Dedicated tenant clusters, databases, Redis partitions, or a hybrid shared/dedicated routing tier. | Human review completed 2026-07-19; `revised`. | From c1120f1995407b70c327d440e5c916294155158b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 16:34:06 +1200 Subject: [PATCH 15/55] Contain unproven hosted creator writes at Game Design edge --- .../game-design-service/api-contracts.md | 6 ++--- .../game-design-service/asset-storage.md | 2 +- .../spring-cloud-gateway/client-behavior.md | 4 ++-- .../spring-cloud-gateway/configuration.md | 2 +- .../design-alignment/README.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 ++ .../platform-operations-and-delivery.md | 2 ++ .../CanonicalGatewayRoutesConfiguration.java | 14 +++++++++--- .../config/GatewayRouteTestSupport.java | 22 +++++++++++++++++++ .../GatewayRoutesConfigurationProdTest.java | 17 +++++++++++--- .../GatewayRoutesConfigurationTest.java | 17 +++++++++++--- ...wayRoutesConfigurationTestProfileTest.java | 17 +++++++++++--- 12 files changed, 87 insertions(+), 20 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 510e7f4b80..cd9dabf847 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -12,7 +12,7 @@ For official hosted deployments, every creator-intent content-bearing mutation e Game Design records only the local committed evidence-binding tuple `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` for a covered operation, where `generation` is Account's material-acceptance generation; it does not copy the Account terms/party catalog. The exact Account party, evidence, and generation authority must remain valid through Game Design's commit linearization point; a preflight read alone is insufficient, and the boundary requires commit-bound authority/fence or equivalent validation without selecting its mechanism. Missing, stale, mismatched, ambiguous, unavailable, or uncertain authority fails closed by aborting the local transaction before any creator mutation or staged artifact becomes authoritative or externally reachable; staged bytes are cleanup/quarantine state, not success. An exact durably committed retry replays its stored outcome and local evidence. An uncertain or not-durably-committed attempt first reconciles the original stable identity and obtains durable no-commit proof; it is not blindly redispatched or mutated while indeterminate. Only a permitted fresh attempt performs a fresh commit-bound currentness check. Reusing the same identity with changed normalized payload returns the target application outcome `IDEMPOTENCY_CONFLICT` before mutation. Game Design does not infer signer authority or materiality. -Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway still publishes a coarse `/api/design/**` family, so `/api/design/assets` is forwarded through `StripPrefix=2` to the live `POST /assets` controller. Game Design currently checks only its privileged JWT/tenant access boundary; it does not evaluate Account hosted-terms/currentness authority. Official-hosted asset-upload readiness is therefore blocked until that route is denied or the exact Account-owned gate is implemented and proved. +Changed-term stale acceptance and the separate non-authoring continuity/lifecycle-reduction paths are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current proto/OpenAPI, routes, storage, UI/status, and focused proof do not implement this gate; no future route or schema is selected here. **Current route consequence:** the implemented Gateway exposes only `GET /api/design/ping` and `GET /api/design/templates`, not the service-local `POST /assets` or `POST /templates` controllers. Those creator writes currently check only privileged JWT/tenant access and do not evaluate Account hosted-terms/currentness authority. Official-hosted creator-write readiness remains blocked until the exact Account-owned gate is implemented and proved; the Gateway restriction is containment, not a substitute for the owner-side gate. ## Draft Commit and Proposal Semantics (Target State) @@ -104,11 +104,11 @@ Default ports: REST on `8080`, gRPC on `6565`. ### REST - `GET /ping` – basic health check returning `"pong"`. -- `POST /assets` – upload a binary asset for a tenant; the current implementation persists the asset row, including its bytes in `game_assets.data`, in PostgreSQL. Publication later exports those bytes to version-scoped object-storage prefixes; direct content-addressed object-storage upload is target-only. The Gateway-exposed `/api/design/assets` route is currently reachable but is not readiness-approved for official-hosted use until the hosted-content gate is implemented and its required proof is validated. Once readiness is established, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. +- `POST /assets` – upload a binary asset for a tenant; the current implementation persists the asset row, including its bytes in `game_assets.data`, in PostgreSQL. Publication later exports those bytes to version-scoped object-storage prefixes; direct content-addressed object-storage upload is target-only. The current Gateway catalog does not expose `/api/design/assets`; this does not make the service-local controller ready for official-hosted use. Once the hosted-content gate and its required proof are implemented, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any byte or metadata side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `POST /templates` – create a new game template. Its external official-hosted exposure is target-only and must remain unavailable until the hosted-content gate is implemented and its required proof is validated. Once enabled there, it is a bypass-safe Game Design creator write when routed externally through Gateway because it is tenant-scoped, domain-local to Game Design, guarded by tenant access checks, and does not depend on Logging & Admin-owned policy or cross-domain write orchestration. Bypass-safe bypasses Logging & Admin only: before any persistence side effect, Game Design must obtain current Account hosted-terms/currentness authority and record `{tenantId, creatorPartyId, acceptanceEvidenceId, generation}` locally. - `GET /templates` – list templates for a tenant. -Externally routed Game Design REST paths use the Gateway allowlist prefix (for example `/api/design/assets` and `/api/design/templates`) and are stripped to the service-local paths above before reaching Game Design. Game Design owns validation and authoritative domain/publishing audit behavior for these creator workflows, while Account remains authoritative for hosted-terms/currentness evidence. Logging & Admin may receive a non-authoritative operator-audit projection for actions that enter its ingress; that projection does not transfer publishing-audit ownership. Operator writes for moderation, quota overrides, runtime feature-flag overrides, and tick remediation remain Logging & Admin ingress only and are not part of this bypass-safe creator-write class. +Externally routed Game Design REST paths use the Gateway allowlist prefix and are stripped to the service-local paths above before reaching Game Design. The current inventory contains only `GET /api/design/ping` and `GET /api/design/templates`; future `/api/design/assets` and template-write exposure requires an explicit catalog entry after the owner-side gate is implemented and proved. Game Design owns validation and authoritative domain/publishing audit behavior for these creator workflows, while Account remains authoritative for hosted-terms/currentness evidence. Logging & Admin may receive a non-authoritative operator-audit projection for actions that enter its ingress; that projection does not transfer publishing-audit ownership. Operator writes for moderation, quota overrides, runtime feature-flag overrides, and tick remediation remain Logging & Admin ingress only and are not part of this bypass-safe creator-write class. ```bash curl http://localhost:8080/ping diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 8e9aada97c..5ab0aa0821 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -8,7 +8,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b - **Current first slice:** Ordinary uploaded bytes are persisted in `game_assets.data`, which is the retained repair source selected by the process-local snapshot for Published/Active binary assets. This source is not database-enforced immutable: the repository can update `data` for an existing row, even though no current REST update route is exposed. Publication currently exports the bytes to version-scoped object storage and exposes the numeric `GameAssetDto.id`; the target private-candidate/content-addressed publication and opaque logical asset identifier are not live. - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. -- **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route nevertheless forwards `/api/design/assets` (after `StripPrefix=2`) to the live `POST /assets` controller, whose Game Design boundary checks only privileged JWT/tenant access. Official-hosted asset-upload readiness is blocked until Gateway denies that route or the exact Account-owned gate is implemented and proved. +- **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The Gateway's explicit read-only Game Design routes do not forward `/api/design/assets` to the live `POST /assets` controller, whose service-local boundary still checks only privileged JWT/tenant access. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved; edge containment is not the owner-side gate. - **Current lifecycle proof:** `version_asset_artifact` records the exported version-number prefix and manifest asset keys, but it does not yet freeze the target exact immutable object-key/digest set or implement the target global publication/purge fence. Repair writes those live prefix objects and the manifest before its exact release-bundle comparison, so pre-write verification is target-only. - **Current lifecycle concurrency gap:** `stateEpoch` comparisons and increments currently occur in service memory, while both `VersionAssetArtifactRepository` and `VersionRepository` update rows by `id` without an epoch predicate or affected-row check. `VersionService.compareAndSetVersionState` therefore has the same gap as artifact lifecycle writes: the live path lacks a database CAS fence for both artifact and Version lifecycle state. The target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation is blocked until both saves use a durable predicate/lock and prove the affected row. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. diff --git a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md index be9c9b0eac..d1718c1a24 100644 --- a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md +++ b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md @@ -35,7 +35,7 @@ Unless explicitly described as current behavior, the sections below define the target Gateway contract. Current implementation facts and gaps are: - Java `CanonicalGatewayRoutesConfiguration` is the current route authority, with environment overrides; the target route catalog and deny-by-default exposure rules still require convergence proof. It currently has no `/assets/**` route or asset-store route ID; published asset delivery remains target-only pending a separate approved public origin/provisioner, and private MinIO is not public delivery. -- **Current Game Design route consequence:** the current coarse `/api/design/**` route forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. That controller currently checks only privileged JWT/tenant access and has no Account hosted-terms/currentness gate, so official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. +- **Current Game Design route consequence:** the Java route catalog forwards only `GET /api/design/ping` and `GET /api/design/templates` through `StripPrefix=2`. It does not forward `POST /api/design/assets` or `POST /api/design/templates`; their service-local controllers still lack the Account hosted-terms/currentness gate. Official-hosted creator-write readiness remains blocked until that exact owner-side gate and proof exist. - The current edge implements bounded connect-token handshake classes and replay handling, but this does not prove the complete target replay durability, rotation, or reconnect contract. - **Current drift:** the protected admin `JwtAuthFilter` parses shared-HMAC JWTs through `JwtUtil`. This is current implementation behavior only, is not a player-facing asymmetric-validation capability, and must not be confused with the target receiving-service boundary. - **Target boundary:** On protected admin routes, Gateway requires an `Authorization` header at ingress and forwards it without parsing or validating ordinary JWT contents; consuming services own asymmetric JWKS validation under [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). @@ -57,7 +57,7 @@ Unless explicitly described as current behavior, the sections below define the t - `/ws/game/**` -> Game Session Service. - `/api/admin/**` -> Logging & Admin Service. -- `/api/design/**` -> Game Design Service. +- `GET /api/design/ping` and `GET /api/design/templates` -> Game Design Service in the current Java catalog; additional `/api/design/**` exposure requires an explicit reviewed entry. - `/api/account/**` -> Account Service. - `/api/session/**` -> Game Session Service HTTP control-plane family. - `/api/social/**` -> Social Groups Service. diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index 4135413074..736a4bf568 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -62,7 +62,7 @@ An explicit certificate-instance revocation, identity removal, or emergency trus - Spring Cloud Gateway is stateless and sits in the DMZ alongside the TCP Proxy Service. - Target route configuration lives in `routes.yml`, imported by `application.yml` and reloaded on startup. Current code remains Java-owned until that convergence lands. -- **Current hosted-route consequence:** the Java route catalog's coarse `/api/design/**` entry forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. Because Game Design has no Account hosted-terms/currentness gate, official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. +- **Current hosted-route consequence:** the Java route catalog exposes only `GET /api/design/ping` and `GET /api/design/templates` to Game Design, with `StripPrefix=2`. It does not expose `POST /api/design/assets` or `POST /api/design/templates`; their service-local controllers still lack the Account hosted-terms/currentness gate, so official-hosted creator-write readiness remains blocked until that exact owner-side gate and proof exist. - The target files define the baseline route set for each environment. - Explicitly enabled dev/test route APIs may overlay bounded in-memory changes on one disposable runtime; player-facing environments use only the version-controlled baseline and must fail startup if mutation is enabled. - The default route configuration defines the core service routes required for local Docker Compose environments. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index ab2912532a..34c168a96b 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Cycle 21 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–21 were productive. Cycle 13 corrected fail-open empty/ambiguous subscription-row entitlement projection. Cycle 14 confirmed the full authority/consolidation lens and routed public `PLAY` admission-outcome ordering to Unit 1B. Cycle 15 corrected billing status/registration schema and classified retryable entitlement outages. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and routed exact-binding reconnect token/lease to Unit 1B without an LKG fallback. Cycle 17 exposed public-registration membership bypass; #2847 converged registration to global-only identity and explicit policy-bound JOIN, while #2848 supplies the durable audit receiver. Cycle 18 corrected current/target status and routed non-public realm-discovery/CHARS disclosure to Unit 1B. Cycle 19 fixed Account's canonical UUID realm binding and stale membership-response status. Cycle 20 corrected local JOIN availability claims, `past_due` status precision, and Account producer audit-payload compaction after verified receiver minimization. Cycle 21 terminalized deterministic changed-policy JOIN conflicts in #2847 and corrected further stale local-JOIN status in #2848 consumer docs and historical decision inventories. Drafts #2846–#2848 are correction evidence, not taper or merge readiness. PostgreSQL execution, retained-data deployment disposition, unknown-commit recovery, direct text-to-Logging proof, lifecycle/generation snapshot completion, finite `COMMITTED` audit retention, and full billing evidence remain open. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 tracks the decision; explicit free/trial state, current-row authority, and strict new-binding controls remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 22 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–22 were productive. Cycle 13 corrected fail-open empty/ambiguous subscription-row entitlement projection. Cycle 14 confirmed the full authority/consolidation lens and routed public `PLAY` admission-outcome ordering to Unit 1B. Cycle 15 corrected billing status/registration schema and classified retryable entitlement outages. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and routed exact-binding reconnect token/lease to Unit 1B without an LKG fallback. Cycle 17 exposed public-registration membership bypass; #2847 converged registration to global-only identity and explicit policy-bound JOIN, while #2848 supplies the durable audit receiver. Cycle 18 corrected current/target status and routed non-public realm-discovery/CHARS disclosure to Unit 1B. Cycle 19 fixed Account's canonical UUID realm binding and stale membership-response status. Cycle 20 corrected local JOIN availability claims, `past_due` status precision, and Account producer audit-payload compaction after verified receiver minimization. Cycle 21 terminalized deterministic changed-policy JOIN conflicts in #2847 and corrected further stale local-JOIN status in #2848 consumer docs and historical decision inventories. Cycle 22 contained the previously exposed Game Design creator writes at Gateway with explicit read-only routes; the Account-owned hosted-content gate remains unimplemented and unproved. Drafts #2846–#2848 are correction evidence, not taper or merge readiness. PostgreSQL execution, retained-data deployment disposition, unknown-commit recovery, direct text-to-Logging proof, lifecycle/generation snapshot completion, finite `COMMITTED` audit retention, and full billing evidence remain open. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 tracks the decision; explicit free/trial state, current-row authority, and strict new-binding controls remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index ae4be8a220..29a46606b9 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 @@ -12,6 +12,8 @@ Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, b 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. +The Gateway Java catalog now omits external Game Design asset and template writes, containing the previously reachable service-local controllers at that edge. Those controllers still lack Account currentness/evidence binding, and direct service-local or future creator ingress is not ready for official-hosted use. The route restriction is not Game Design gate proof. + ### Script and plugin transition reconciliation Game Design's script-patch and plugin transition implementation remains partial: design-time publication metadata and bounded local activation-preflight seams exist, but dedicated Game Logic ability-schema compatibility, tenant runtime readiness, exact instance pin/epoch propagation, rollout/rollback history, and end-to-end recovery proof remain absent or unproved. The ownership and lifecycle contracts for these gaps are recorded in [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md), [ADR 0108](../../architecture/decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md), [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 30e991e1bf..42dcc9042c 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -152,6 +152,8 @@ The fixed `develop` environment is a separate `dev-demo-cluster`, not a PR previ Gateway is a curated public edge with explicit route inventory and deny-by-default behavior, not permissive service fan-out. Canonical route families include `/api/session/**`, `/api/admin/**`, `/assets/**`, WebSocket gameplay, Telnet, and `gateway.v1` management. The current public session HTTP inventory is only `GET /api/session/ping`; remaining session/admin routes are privileged external contracts. Gateway blocks `/api/{public-family}/internal/**`, and undocumented paths under the explicit families are denied rather than forwarded by a coarse family matcher. The canonical namespace is `/api/{service}/**`, not the obsolete `/admin/...` examples. +The current Java catalog narrows Game Design's external inventory to `GET /api/design/ping` and `GET /api/design/templates`; it does not forward creator `POST /api/design/assets` or `POST /api/design/templates`. Focused route-predicate tests cover this static containment across profiles. This does not implement the Account-owned hosted-content gate in Game Design or prove full route-catalog/matrix convergence. + Owner-side enforcement is part of the boundary: Game Session enforces the documented public/internal/operator split, and Logging & Admin exposes only published privileged routes behind its own authorization. Gateway route configuration, route predicates/filters, owner controllers, fixtures, and docs are intended to describe the same inventory. Gateway management uses the canonical `gateway.v1` package and shared in-band application-error conventions; it does not replicate service authorization policy locally. New public routes must be added to the explicit inventory with owner-side enforcement. Spring Cloud Gateway's current dynamic route-management surfaces remain ephemeral overrides layered over the Java-owned baseline in `CanonicalGatewayRoutesConfiguration`; the released declarative catalog/import, complete mutation-profile gating, private-listener/mTLS/network-policy proof, shared persistence, multi-pod convergence, route-change auditing, readiness enforcement, route-input allowlists, and restart persistence remain unimplemented or unproven. Hosted Helm renders `prod` without dynamic-mutation configuration, but the Java-owned player-facing routes remain. This route-management lifecycle is not a production control plane; target ownership and protocol remain in [Gateway Configuration](../../architecture/microservices/spring-cloud-gateway/configuration.md) and [Gateway Architecture](../../architecture/system-architecture-gateway.md). diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java index cc92e60dae..1eb72e99dd 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java @@ -70,11 +70,19 @@ public GatewayProperties canonicalGatewayProperties(Environment environment) { 2, "GET"), route( - "design", + "design-ping", environment.getProperty( "FIREMUD_GATEWAY_ROUTE_DESIGN_URI", "http://game-design-service:8080"), - "/api/design/**", - 2), + "/api/design/ping", + 2, + "GET"), + route( + "design-templates-read", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_DESIGN_URI", "http://game-design-service:8080"), + "/api/design/templates", + 2, + "GET"), route( "account-auth", environment.getProperty( diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java index d980fa953c..f85f946417 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java @@ -65,6 +65,28 @@ static void assertNoConfiguredPath(GatewayProperties gatewayProperties, String p assertThat(configuredPaths).doesNotContain(path); } + static void assertNoRouteWithPathAndMethod( + GatewayProperties gatewayProperties, String path, String method) { + assertThat( + gatewayProperties.getRoutes().stream() + .noneMatch( + route -> + route.getPredicates().stream() + .filter(predicate -> "Path".equalsIgnoreCase(predicate.getName())) + .flatMap(predicate -> predicate.getArgs().values().stream()) + .anyMatch(path::equals) + && (route.getPredicates().stream() + .noneMatch( + predicate -> "Method".equalsIgnoreCase(predicate.getName())) + || route.getPredicates().stream() + .filter( + predicate -> "Method".equalsIgnoreCase(predicate.getName())) + .flatMap(predicate -> predicate.getArgs().values().stream()) + .anyMatch(method::equals)))) + .as("route %s %s must not be configured", method, path) + .isTrue(); + } + static void assertSocialChatAndFriendsAreEdgeGated(GatewayProperties gatewayProperties) { assertThat(gatewayProperties.getRoutes().stream().map(RouteDefinition::getId)) .doesNotContain("social-chat", "social-friends"); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java index 38e63fb9a4..989f145e1b 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefixTwo; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.route; import static org.assertj.core.api.Assertions.assertThat; @@ -47,7 +49,8 @@ class GatewayRoutesConfigurationProdTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth", "account-accounts", "account-profiles", @@ -120,13 +123,21 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertHasPath(gatewayProperties, "admin-remote-followups", "/api/admin/remote-followups/**"); assertHasPath(gatewayProperties, "admin-tick-remediation", "/api/admin/tick-remediation/**"); assertHasMethod(gatewayProperties, "admin-tick-remediation", "GET"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); assertHasStripPrefixTwo(gatewayProperties, "admin-ping"); assertHasStripPrefixTwo(gatewayProperties, "admin-admission-pointers"); assertHasStripPrefixTwo(gatewayProperties, "admin-remote-followups"); assertHasStripPrefixTwo(gatewayProperties, "admin-tick-remediation"); - assertHasStripPrefixTwo(gatewayProperties, "design"); + assertHasStripPrefixTwo(gatewayProperties, "design-ping"); + assertHasStripPrefixTwo(gatewayProperties, "design-templates-read"); assertHasStripPrefixTwo(gatewayProperties, "account-auth"); } } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java index a15d8e7c9b..519c031387 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefixTwo; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.route; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +48,8 @@ class GatewayRoutesConfigurationTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth", "account-accounts", "account-profiles", @@ -130,8 +133,16 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertHasStripPrefixTwo(gatewayProperties, "admin-sagas"); assertHasStripPrefixTwo(gatewayProperties, "admin-tick-remediation"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); - assertHasStripPrefixTwo(gatewayProperties, "design"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasStripPrefixTwo(gatewayProperties, "design-ping"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertHasStripPrefixTwo(gatewayProperties, "design-templates-read"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); assertHasPath(gatewayProperties, "account-auth", "/api/account/auth/**"); assertHasPath(gatewayProperties, "account-accounts", "/api/account/accounts/**"); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java index 84656b3137..e6dec07fda 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefix; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +48,8 @@ class GatewayRoutesConfigurationTestProfileTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth", "account-accounts", "account-profiles", @@ -111,7 +114,14 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasPath(gatewayProperties, "admin-tick-remediation", "/api/admin/tick-remediation/**"); assertHasMethod(gatewayProperties, "admin-tick-remediation", "GET"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); assertHasPath(gatewayProperties, "session-ping", "/api/session/ping"); @@ -133,7 +143,8 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasStripPrefix(gatewayProperties, "admin-remote-followups", "2"); assertHasStripPrefix(gatewayProperties, "admin-sagas", "2"); assertHasStripPrefix(gatewayProperties, "admin-tick-remediation", "2"); - assertHasStripPrefix(gatewayProperties, "design", "2"); + assertHasStripPrefix(gatewayProperties, "design-ping", "2"); + assertHasStripPrefix(gatewayProperties, "design-templates-read", "2"); assertHasStripPrefix(gatewayProperties, "account-auth", "2"); assertHasStripPrefix(gatewayProperties, "account-accounts", "2"); assertHasStripPrefix(gatewayProperties, "account-profiles", "2"); From db16f42ac082b5a5e97ad91bec47b08771ae4af6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 17:07:54 +1200 Subject: [PATCH 16/55] Guard Account credential gRPC and defer unsupported currency calls --- .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 6 +- .../game-design-service/README.md | 2 +- .../game-session-service/protocols.md | 8 +- .../system-architecture-authentication.md | 2 +- .../system-architecture-gateway.md | 2 +- .../system-architecture-protocol-bridging.md | 8 +- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 2 + .../realm-routing-and-playable-state.md | 4 +- ...hared-runtime-contracts-and-persistence.md | 2 +- .../service/impl/AccountGrpcService.java | 20 ++ .../impl/VirtualCurrencyGrpcService.java | 99 ++------- .../service/impl/AccountGrpcServiceTest.java | 196 +++++++++++++----- .../impl/VirtualCurrencyGrpcServiceTest.java | 182 ++++++---------- 15 files changed, 269 insertions(+), 268 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 45ff2a4ecb..44f08c5285 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -58,6 +58,8 @@ Explicit playtest grants remain partial: current Account persistence and interna The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. +The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile, presence, export, account-ID verification, and external-link gRPC handlers still lack complete method/workload and caller-subject binding; their bearer requirement does not establish that authorization. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. + `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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain 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. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 744e01fc1e..3fcae8a374 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -24,9 +24,11 @@ The live runtime membership response carries `accountId`, `tenantId`, `membershi The current `application.yml` and `application-prod.yml` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. +The credential-granting gRPC `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` methods now require the verified exact Game Session peer before invoking Account credential/challenge operations, with focused missing/wrong-peer denial tests. The broader internal gRPC boundary is not converged: legacy `GetProfile`, `UpdateProfile`, `ListPresenceVisibilityPolicies`, `ExportAccount`, `ExportTenantData`, `LinkExternalAccount`, and account-ID `RequestEmailVerification` still accept request-selected subjects with only bearer authentication, not exact method/workload and caller-subject authorization. The public REST guards do not protect direct gRPC calls. This is a current cross-account read, mutation, export, and verification side-effect gap, not evidence that every internal caller can bypass mTLS. + The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The live legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes instead admit the broad shared global-privileged-role helper (including `moderator`), accept caller-supplied `grantedBy`/`grantReason`, and do not apply the target lifecycle identity, revision, digest, or request-replay contract. They must be removed or fail closed until the canonical owner transport and its authenticated attribution and replay proof are implemented; this route is not an additional grant authority. -Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; atomic single-use consumption and concurrent-reuse proof remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). +Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; email-verification token consumption has the same read/update/delete race. Atomic single-use consumption and concurrent-reuse proof for both paths remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). The local direct-text `REALMS`-to-`JOIN` path issues a short-lived Account-owned scope for an authenticated caller and validates the retained target snapshot and caller binding at `JoinPublicProductionMembership`; Game Session supplies a server-generated join-attempt identity. A committed policy-independent intent survives entitlement outages and can be resumed by an exact request retry; when the second transaction outcome is uncertain, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). @@ -276,6 +278,8 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit Billing provider integration, instrument ownership, payment reconciliation, and the reserved future-marketplace entitlement substrate are canonical in [Stripe Integration Design](./stripe-integration.md). Subscription status lifecycle and plan-change timing are canonical in [Subscription Management Design](./subscription-management.md). +The current virtual-currency gRPC facade returns `FAILED_PRECONDITION` for `GetBalance`, `AddCurrency`, and `SpendCurrency` before touching its existing storage/service substrate. This is fail-closed containment of unsupported v1 operations, not a completed economy or an entitlement source. Generic payment and donation/refund provider mutations remain separately open under the Stripe owner contract. + Runtime and data consequences remain local to this document: `payment_transaction` is the financial/provider audit record, while `purchase_entitlement` is reserved for a separately accepted future marketplace and is not a v1 hosting-billing authority. Account must not infer gameplay value from payment status alone; a future paid-but-unfulfilled grant would remain non-active and therefore non-authorizing, and its durable operation state would remain visible to reconciliation and deletion guards. Existing donation rows and virtual-currency/premium-hosting code remain implementation substrate unless a supported product contract explicitly admits them; creator donations/tips are deferred. ### Deferred Creator Monetization diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 69447e9bea..41b0929f69 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -23,7 +23,7 @@ Current capability and proof gaps remain: Game Session's exact pin/epoch persist - Track revision history for rollback - Orchestrate cross-service publish workflows and notify downstream services when new versions are available. - Accept branding uploads into the current Game Design persistence boundary and, during publish, export a `manifest.json` and version-scoped objects. No public asset `GET`/download route exists; the target private-candidate/content-addressed export and approved public `/assets/**` delivery let runtime clients load themes and logos without calling this service. -- **Current hosted-route consequence:** the Gateway's coarse `/api/design/**` route currently forwards `/api/design/assets` through `StripPrefix=2` to the live `POST /assets` controller. Because Game Design has no Account hosted-terms/currentness gate, official-hosted asset-upload readiness remains blocked until Gateway denies the route or the exact Account-owned gate is implemented and proved. +- **Current hosted-route consequence:** Gateway currently exposes only `GET /api/design/ping` and `GET /api/design/templates`; it has no coarse `/api/design/**` or `/api/design/assets` mutation route, so edge asset writes are denied. The Game Design owner-side Account hosted-terms/currentness gate is still absent. This route restriction makes no readiness claim; official-hosted asset-upload readiness remains unproved pending the exact Account-owned gate and its proof. - Act as the sole owner of game asset publishing to the S3-compatible object store; **target state:** downstream services and clients read published assets via approved configured delivery URLs and do not write directly to the asset store. In the current first slice, private MinIO/object-store URLs are not public client delivery. Logical world and entity templates remain in PostgreSQL schemas owned by World Management, Entity Management, and related domain services and are not stored as blobs in the asset store. - When publish workflows need to expose derived domain artifacts outside their owning service storage (for example world navmesh/path graph bundles), Game Design remains the sole object-store writer. Owning domain services hand those artifacts to the publish workflow as explicit inputs; they do not bypass the publish workflow with direct object-store writes. - **Target state:** Runtime discovery of derived artifacts uses the version `manifest.json` attested by `published_release_bundle`. The target canonical attestation shape includes `artifactDigests[]`, `requiredManifestAssetKeys[]`, and `manifestHash`; the current persisted bundle is narrower and lacks those complete target fields, so consumers must not treat current output as complete release proof or depend on undocumented bucket key conventions. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 25ffbcd0e0..a2a0ef2562 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. The local Account `JoinPublicProductionMembership` operation and Game Session translation/scope seam now exist, but complete direct-text and first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and the Account lifecycle/authority-generation snapshot needed by final admission remain incomplete. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account does not yet expose `membershipLifecycleState`, so an `ACTIVE` or `INACTIVE` classification is target-only until Account exposes that field. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. The local Account `JoinPublicProductionMembership` operation and Game Session translation/scope seam now exist, but complete direct-text and first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and the Account lifecycle/authority-generation snapshot needed by final admission remain incomplete. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; the Account proto/producer now also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current Game Session and connect-token consumers do not enforce lifecycle or generation. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). @@ -39,7 +39,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. The local Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path now exist, but current `PLAY` applies only the Account-exposed `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` fields plus existing grant checks; it cannot classify `ACTIVE` or `INACTIVE` until Account lifecycle state is exposed to and consumed by the admission path. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification. Direct-text and first-party end-to-end proof, PostgreSQL execution, and pending-operation recovery remain incomplete; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. +- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. The local Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path now exist, but the Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration` alongside the four admission fields; current `PLAY` applies only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus existing grant checks, so it cannot enforce or classify `ACTIVE` or `INACTIVE`. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification. Direct-text and first-party end-to-end proof, PostgreSQL execution, and pending-operation recovery remain incomplete; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -114,7 +114,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. It also does not expose `membershipLifecycleState`, so it uses the four-field Account adapter response (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and cannot classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; the latter cannot currently be classified specifically as `INACTIVE` because the adapter does not expose lifecycle state. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration` alongside the four admission fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`), but the current Game Session consumer does not enforce lifecycle or generation and therefore cannot classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; the latter cannot currently be classified specifically as `INACTIVE` because lifecycle state is not consumed by the admission path. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. @@ -164,7 +164,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – bootstrap-backed `LOGIN` resolved to an account different from the validated connect-context subject. -- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. The local Account route/RPC and Game Session text dispatch now exist, but the current result remains fail-closed and non-actionable to consumers until lifecycle-aware admission and end-to-end/runtime proof are complete. The existing non-admitting case cannot be classified as `INACTIVE` because Account lifecycle state is not yet consumed by the admission path. +- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. The local Account route/RPC and Game Session text dispatch now exist, but the current result remains fail-closed and non-actionable to consumers until lifecycle-aware admission and end-to-end/runtime proof are complete. Account now emits lifecycle state and authority generation, but the existing non-admitting case cannot be classified as `INACTIVE` because those fields are not yet consumed by the admission path. - `WORLD_ACCESS_DENIED` – current runtime behavior for a private, playtest, or other non-public target whose Account-exposed membership/admission predicate or existing grant check denies access; no public join action is offered. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 0787e92d50..2ff68c571c 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The adapter response has no `membershipLifecycleState` field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result remains a fail-closed admission denial until the caller completes the local explicit join operation; it is not proof of the target lifecycle snapshot or final admission flow. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains partial and its PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof remain open. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with the four admission-evidence fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, plus the producer-emitted `membershipLifecycleState` and `membershipAuthorityGeneration`; current connect-token and Game Session consumers enforce only the four admission fields, and the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current consumers do not enforce either field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result remains a fail-closed admission denial until the caller completes the local explicit join operation; it is not proof of the target lifecycle snapshot or final admission flow. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains partial and its PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof remain open. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 7aecc752f0..0a53ef88a4 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -11,7 +11,7 @@ Gateway does not validate ordinary REST or admin JWTs; the consuming Account, ad Unless otherwise noted, this document describes target-state gateway behavior. Current rollout and implementation boundaries are: - The target-state declarative `routes.yml` catalog has not yet converged as the implemented route authority. The current authority is the Java `CanonicalGatewayRoutesConfiguration`, with route-specific environment overrides `FIREMUD_GATEWAY_ROUTE_SESSION_URI`, `FIREMUD_GATEWAY_ROUTE_ADMIN_URI`, `FIREMUD_GATEWAY_ROUTE_DESIGN_URI`, `FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI`, and `FIREMUD_GATEWAY_ROUTE_SOCIAL_URI`. These are distinct from the `FIREMUD_SERVICES_*` service-discovery variables used by other microservices. See [Environment Variables & Secrets Management](./infrastructure/environment-and-secrets.md#service-discovery). -- **Current Game Design route consequence:** the Java route catalog's coarse `/api/design/**` entry forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. The controller currently checks only privileged JWT/tenant access and has no Account hosted-terms/currentness gate; official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. +- **Current Game Design route consequence:** the Java route catalog exposes only `GET /api/design/ping` and `GET /api/design/templates`; it has no coarse `/api/design/**` or `/api/design/assets` mutation route, so edge asset writes are denied. The Game Design owner-side Account hosted-terms/currentness gate is still absent. This route restriction makes no readiness claim; official-hosted asset-upload readiness remains unproved pending the exact Account-owned gate and its proof. - Published `/assets/**` delivery is target-only pending a separate approved public origin/provisioner. The current Gateway route catalog has no `/assets/**` route or asset-store route ID, and private MinIO is not public delivery. The reserved `/assets/**` family remains separate from the first-party static-host `/frontend-assets/**` family. - The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. Gateway listener TLS is loaded at startup and does not support live listener reload. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. - The target replay domain is a Gateway-owned Coordination Redis contract defined by the Redis ownership and recovery documents. Gateway carries its non-secret domain pin in `FIREMUD_GATEWAY_REPLAY_DOMAIN`, which must equal exactly `gateway-connect-token-replay-v1` and is rendered as the fixed `{gateway-connect-token-replay-v1}` hash tag. Startup, target preflight, and migration/reset tooling must reject any other value and prove the same tag across Gateway instances and shared Coordination Redis readback. The current `GameplayHandshakeFilter` still writes only a legacy replay marker through the generic Cache-bound client; it has no browser-deny, readiness, or replay-fence writer. This is migration-only drift: before target admission, the named Coordination client/ACL must be cut over, the legacy state must be inventoried and read back under quarantine, the target contract must be verified, and legacy markers must be retained or explicitly cleaned only after their original acceptance windows expire. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 32fec0c4c9..f6a8d6a221 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet runtime-complete; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or end-to-end `JOIN`. The local Account `POST /auth/bootstrap/join` route and `JoinPublicProductionMembership` operation, plus Game Session text `JOIN` dispatch, now exist; PostgreSQL execution, pending-operation recovery, and direct-text/first-party end-to-end proof remain gaps. The required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance also remains unimplemented/unproved. On its fresh Account-authority path, current connect-token issuance and text `PLAY` consume the Account membership response fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`. However, the live Account connect-token path checks the Session Redis replay/result cache before calling fresh entitlement or membership authority, so a replay-cache hit can return the stored success or failure without re-evaluating current entitlement or membership. That cache-hit bypass is current implementation drift; it does not satisfy the target fresh authority and durable replay revalidation contract. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. The obsolete implicit membership-writer surface has been removed. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains the non-actionable `JOIN_REQUIRED` outcome. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`. Current private/playtest text `PLAY` also requires the current realm grant, while current connect-token issuance validates pointer/visibility but not the private/playtest grant; target-only connect-token grant validation remains implementation drift. A connect token or returning shortcut must not be treated as authorization proof. Returning members may proceed through the current existing-membership path, but that behavior does not prove the target generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. +The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet runtime-complete; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or end-to-end `JOIN`. The local Account `POST /auth/bootstrap/join` route and `JoinPublicProductionMembership` operation, plus Game Session text `JOIN` dispatch, now exist; PostgreSQL execution, pending-operation recovery, and direct-text/first-party end-to-end proof remain gaps. The required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance also remains unimplemented/unproved. On its fresh Account-authority path, current connect-token issuance and text `PLAY` consume the Account membership response fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but these consumers do not enforce lifecycle or generation. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`. However, the live Account connect-token path checks the Session Redis replay/result cache before calling fresh entitlement or membership authority, so a replay-cache hit can return the stored success or failure without re-evaluating current entitlement or membership. That cache-hit bypass is current implementation drift; it does not satisfy the target fresh authority and durable replay revalidation contract. `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE` because current consumers do not enforce the producer's lifecycle field. The obsolete implicit membership-writer surface has been removed. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains the non-actionable `JOIN_REQUIRED` outcome. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`. Current private/playtest text `PLAY` also requires the current realm grant, while current connect-token issuance validates pointer/visibility but not the private/playtest grant; target-only connect-token grant validation remains implementation drift. A connect token or returning shortcut must not be treated as authorization proof. Returning members may proceed through the current existing-membership path, but that behavior does not prove the target generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. --- @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The local Account JOIN route/RPC and Game Session text dispatch now exist, but current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Direct-text and first-party end-to-end proof and the required membership reread remain incomplete. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The local Account JOIN route/RPC and Game Session text dispatch now exist, but current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but these consumers do not enforce lifecycle or generation. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Direct-text and first-party end-to-end proof and the required membership reread remain incomplete. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current runtime has no lifecycle-state predicate: its current admission fields are `membershipExists` and `gameplayAdmissionAllowed`; `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current runtime validates pointer/visibility for this flow but not the private/playtest realm grant, so current shortcut and token behavior do not prove authorization. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current runtime has no lifecycle-state predicate and its admission consumers enforce only `membershipExists` and `gameplayAdmissionAllowed`; `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current runtime validates pointer/visibility for this flow but not the private/playtest realm grant, so current shortcut and token behavior do not prove authorization. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. The local `Join & Play` endpoint and Account writer exist, but lifecycle-aware admission, the required issuance reread, and complete runtime/deployment proof remain incomplete; an eligible public-production membership that is missing (`membershipExists=false`) or existing but non-admitting (`gameplayAdmissionAllowed=false`) therefore remains non-actionable `JOIN_REQUIRED` with no mutation; the latter cannot be classified specifically as `INACTIVE` by the live adapter. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients may still stop with the same non-actionable `JOIN_REQUIRED` outcome when membership evidence is not admitting, despite the local join dispatch existing. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. The local `Join & Play` endpoint and Account writer exist, but lifecycle-aware admission, the required issuance reread, and complete runtime/deployment proof remain incomplete; the Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`, while current consumers do not enforce those fields. An eligible public-production membership that is missing (`membershipExists=false`) or existing but non-admitting (`gameplayAdmissionAllowed=false`) therefore remains non-actionable `JOIN_REQUIRED` with no mutation; the latter cannot be classified specifically as `INACTIVE` by the current admission path. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients may still stop with the same non-actionable `JOIN_REQUIRED` outcome when membership evidence is not admitting, despite the local join dispatch existing. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 34c168a96b..fe096909ca 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Cycle 22 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–22 were productive. Cycle 13 corrected fail-open empty/ambiguous subscription-row entitlement projection. Cycle 14 confirmed the full authority/consolidation lens and routed public `PLAY` admission-outcome ordering to Unit 1B. Cycle 15 corrected billing status/registration schema and classified retryable entitlement outages. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and routed exact-binding reconnect token/lease to Unit 1B without an LKG fallback. Cycle 17 exposed public-registration membership bypass; #2847 converged registration to global-only identity and explicit policy-bound JOIN, while #2848 supplies the durable audit receiver. Cycle 18 corrected current/target status and routed non-public realm-discovery/CHARS disclosure to Unit 1B. Cycle 19 fixed Account's canonical UUID realm binding and stale membership-response status. Cycle 20 corrected local JOIN availability claims, `past_due` status precision, and Account producer audit-payload compaction after verified receiver minimization. Cycle 21 terminalized deterministic changed-policy JOIN conflicts in #2847 and corrected further stale local-JOIN status in #2848 consumer docs and historical decision inventories. Cycle 22 contained the previously exposed Game Design creator writes at Gateway with explicit read-only routes; the Account-owned hosted-content gate remains unimplemented and unproved. Drafts #2846–#2848 are correction evidence, not taper or merge readiness. PostgreSQL execution, retained-data deployment disposition, unknown-commit recovery, direct text-to-Logging proof, lifecycle/generation snapshot completion, finite `COMMITTED` audit retention, and full billing evidence remain open. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 tracks the decision; explicit free/trial state, current-row authority, and strict new-binding controls remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 23 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–23 were productive. Cycle 13 corrected fail-open empty/ambiguous subscription-row entitlement projection. Cycle 14 confirmed the full authority/consolidation lens and routed public `PLAY` admission-outcome ordering to Unit 1B. Cycle 15 corrected billing status/registration schema and classified retryable entitlement outages. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and routed exact-binding reconnect token/lease to Unit 1B without an LKG fallback. Cycle 17 exposed public-registration membership bypass; #2847 converged registration to global-only identity and explicit policy-bound JOIN, while #2848 supplies the durable audit receiver. Cycle 18 corrected current/target status and routed non-public realm-discovery/CHARS disclosure to Unit 1B. Cycle 19 fixed Account's canonical UUID realm binding and stale membership-response status. Cycle 20 corrected local JOIN availability claims, `past_due` status precision, and Account producer audit-payload compaction after verified receiver minimization. Cycle 21 terminalized deterministic changed-policy JOIN conflicts in #2847 and corrected further stale local-JOIN status in #2848 consumer docs and historical decision inventories. Cycle 22 contained the previously exposed Game Design creator writes at Gateway with explicit read-only routes; the Account-owned hosted-content gate remains unimplemented and unproved. Cycle 23 guarded Account credential-granting gRPC methods by exact Game Session peer, contained deferred currency RPCs, and corrected stale route, membership-evidence, and registration status; other legacy gRPC subject binding remains open. Drafts #2846–#2848 are correction evidence, not taper or merge readiness. PostgreSQL execution, retained-data deployment disposition, unknown-commit recovery, direct text-to-Logging proof, lifecycle/generation snapshot completion, finite `COMMITTED` audit retention, and full billing evidence remain open. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 tracks the decision; explicit free/trial state, current-row authority, and strict new-binding controls remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | 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 4c5e6e7063..bf55ad3f8a 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,8 @@ Official-hosted creator-content acceptance remains an unimplemented target gap; Account runtime admission reads remain a security/proof blocker: both `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are currently configured as public gRPC methods, and handlers accept caller-selected identifiers without exact Game Session/World Management workload or tenant binding. The target internal-workload boundary and required negative proof are 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). +Account's credential-granting gameplay gRPC methods now enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Other internal gRPC profile, presence, export, external-link, and account-ID verification handlers remain bearer-only and trust request-selected account/tenant IDs; direct calls bypass the current REST subject guards. The Account API/runtime owner retains method allowlisting and subject-binding convergence. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls now 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. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` path provides read-only baseline evidence only. Namespace-aware shared-versus-isolated playable-state persistence exists for current state families, but the Account-owned restricted-synthetic identity/isolation verifier and corresponding persistent/shared mutation proof remain unavailable; independent two-transport mutation parity remains unimplemented and unproved. Run-owned Compose mutation and teardown remain implemented and proved at their bounded scope. See the [canonical testing owner](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). 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 64acb919cc..0954e557e4 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 @@ -55,7 +55,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current connect-token issuance and text-client `PLAY` consume an Account membership response identified by `accountId` and `tenantId` with four admission-evidence fields, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they admit only when the two admission fields are true, and an eligible public-production request with `membershipExists=false` may return non-actionable `JOIN_REQUIRED`. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. The local Account `JOIN` operation and Game Session transport seam now exist; PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, the target membership-authority-generation reread, and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current connect-token issuance and text-client `PLAY` consume an Account membership response identified by `accountId` and `tenantId` with the four admission-evidence fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current connect-token and text-client consumers enforce only the four admission fields. They admit only when the two admission fields are true, and an eligible public-production request with `membershipExists=false` may return non-actionable `JOIN_REQUIRED`. `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE` because lifecycle state is not consumed. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. The local Account `JOIN` operation and Game Session transport seam now exist; PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, the target membership-authority-generation reread, and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. @@ -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 connect-token issuance and `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and never create membership; an eligible public-production response with `membershipExists=false` may return `JOIN_REQUIRED`. For non-public membership, connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED`. An existing non-admitting response cannot be classified as `INACTIVE` because the live adapter does not expose lifecycle state. 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. +- Explicit `JOIN`/`Join & Play` now has a local Account operation and Game Session scope/translation seam, but the complete bridge remains unproved. Current connect-token issuance and `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and never create membership; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but these consumers do not enforce lifecycle or generation. An eligible public-production response with `membershipExists=false` may return `JOIN_REQUIRED`. For non-public membership, connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is not consumed by the admission path. 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. - 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/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index d230b522e3..6ff6d7509d 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 @@ -37,7 +37,7 @@ These links add decision provenance and shared-runtime consequences only; capabi The following current-state findings refine the existing partial/drift status; owner documents retain the target contract details: -- `SF-1.2` / `SF-2.1`: Account creation requires a caller-provided tenant and writes an admission-enabled membership, while legacy defaults/backfill fabricated tenant membership. Global registration and explicit public-membership joining are not implemented; retained-data disposition/mapping and focused migration proof remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). +- `SF-1.2` / `SF-2.1`: Account's current implementation includes global registration and explicit public-membership `JOIN` locally (see #2847). PostgreSQL execution, pending-operation recovery, retained-row disposition, and direct text-to-Logging end-to-end proof for the registration/JOIN path remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-1.2` / `SF-2.1`: Account V25 enforces one live profile per `(tenant_id, account_id)` while allowing the same global account to have one profile in each tenant. Its named preflight fails closed on retained duplicate tuples without rewriting them. The PostgreSQL cases for cross-tenant reuse, same-tenant rejection, and retained-duplicate migration failure compile but were Docker-skipped, so runtime database proof and any required retained-row disposition remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-1.2` / `SF-2.1`: Account's live `subscription` table has neither a current/non-superseded tenant uniqueness invariant nor provider subscription identity/history. Current subscription creation fails closed before mutation, while retained/local subscription rows still lack current-row uniqueness and provider identity/history, and entitlement reads accept any matching available row. The target retained-history, replacement, webhook, and provider-reconciliation lifecycle is not implemented. A partial index or provider-ID backfill cannot be invented without that owner lifecycle and retained-row disposition. This concrete gap is routed to Player Access capability `AA-1.4`, with `AA-1.5` as a consumer consequence; see [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#implementation-status) and [Player Access and Session](./player-access-and-session.md#capability-status). - `SF-2.1`: Account V22/V23 canonicalize retained `accounts.email` values and validate a new check without proven rolling- or rollback-compatibility with older binaries. Before affected deployment, Account needs service- and environment-specific no-overlap and retained-data evidence or a forward-compatible rollout path, plus old-era and mixed-binary proof. No existing deployment state is inferred; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 769e404424..41d91d554e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -278,6 +278,7 @@ public void createAccount( public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); net.firedevops.firemud.accountservice.dto.AuthenticationResult result = accountService.authenticateForGameplay(request.getEmail(), request.getPassword()); AuthenticateResponse response = @@ -287,6 +288,13 @@ public void authenticate( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + AuthenticateResponse response = + AuthenticateResponse.newBuilder() + .setError(appError("Authenticate", "PERMISSION_DENIED", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { AuthenticateResponse response = AuthenticateResponse.newBuilder() @@ -317,8 +325,14 @@ public void requestEmailLoginOtp( RequestEmailLoginOtpRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); accountService.requestEmailLoginOtp(request.getEmail()); responseObserver.onNext(RequestEmailLoginOtpResponse.newBuilder().setAccepted(true).build()); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + RequestEmailLoginOtpResponse.newBuilder() + .setError(appError("RequestEmailLoginOtp", "PERMISSION_DENIED", ex.getMessage())) + .build()); } catch (InvalidRequestException ex) { responseObserver.onNext( RequestEmailLoginOtpResponse.newBuilder() @@ -333,12 +347,18 @@ public void requestEmailLoginOtp( public void verifyEmailLoginOtp( VerifyEmailLoginOtpRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); var result = accountService.verifyEmailLoginOtp(request.getEmail(), request.getCode()); responseObserver.onNext( AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) .setAccountId(String.valueOf(result.accountId())) .build()); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + AuthenticateResponse.newBuilder() + .setError(appError("VerifyEmailLoginOtp", "PERMISSION_DENIED", ex.getMessage())) + .build()); } catch (InvalidRequestException ex) { responseObserver.onNext( AuthenticateResponse.newBuilder() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java index 1adc30f9a8..54c76c2bfb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java @@ -13,7 +13,7 @@ import net.firedevops.firemud.account.v1.VirtualCurrencyServiceGrpc; import net.firedevops.firemud.accountservice.service.VirtualCurrencyService; import net.firedevops.firemud.common.grpc.GrpcAppErrors; -import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -49,98 +49,33 @@ public VirtualCurrencyGrpcService( @Timed(value = "currencyGrpc.getBalance") public void getBalance( GetBalanceRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.getBalance( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode()); - GetBalanceResponse response = GetBalanceResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetBalanceResponse response = - GetBalanceResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "GetBalance", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - GetBalanceResponse response = - GetBalanceResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "GetBalance", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + GetBalanceResponse.newBuilder().setError(unavailable("GetBalance")).build()); + responseObserver.onCompleted(); } @Override @Timed(value = "currencyGrpc.addCurrency") public void addCurrency( AddCurrencyRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.addCurrency( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode(), - request.getAmount()); - AddCurrencyResponse response = AddCurrencyResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - AddCurrencyResponse response = - AddCurrencyResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "AddCurrency", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - AddCurrencyResponse response = - AddCurrencyResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "AddCurrency", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + AddCurrencyResponse.newBuilder().setError(unavailable("AddCurrency")).build()); + responseObserver.onCompleted(); } @Override @Timed(value = "currencyGrpc.spendCurrency") public void spendCurrency( SpendCurrencyRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.spendCurrency( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode(), - request.getAmount()); - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "SpendCurrency", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "SpendCurrency", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + SpendCurrencyResponse.newBuilder().setError(unavailable("SpendCurrency")).build()); + responseObserver.onCompleted(); + } + + private ErrorDetail unavailable(String operation) { + String message = operation + " is unavailable"; + return meterRegistry == null + ? ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build() + : GrpcAppErrors.error(meterRegistry, logger, operation, "FAILED_PRECONDITION", message); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index f475c9a892..22ad57156d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -353,50 +353,87 @@ void authenticateFailureReturnsErrorDetail() { .thenThrow( new AuthenticationException( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.authenticate( - AuthenticateRequest.newBuilder().setEmail("demo@example.com").setPassword("bad").build(), - new StreamObserver() { - @Override - public void onNext(AuthenticateResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("bad") + .build(), + new StreamObserver() { + @Override + public void onNext(AuthenticateResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, ref.get().getError().getCode()); Mockito.verify(accountService).authenticateForGameplay("demo@example.com", "bad"); } + @Test + void authenticateReturnsAuthenticatedSessionForExactGameSessionPeer() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.authenticateForGameplay("demo@example.com", "password")) + .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer)); + + assertEquals("9", observer.response().getAccountId()); + assertEquals("jwt", observer.response().getAuthToken()); + assertTrue(observer.completed()); + Mockito.verify(accountService).authenticateForGameplay("demo@example.com", "password"); + } + @Test void requestEmailLoginOtpDispatchesNeutralChallengeRequest() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.requestEmailLoginOtp( - RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), - new StreamObserver() { - @Override - public void onNext(RequestEmailLoginOtpResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.requestEmailLoginOtp( + RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), + new StreamObserver() { + @Override + public void onNext(RequestEmailLoginOtpResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertTrue(ref.get().getAccepted()); @@ -409,26 +446,30 @@ void verifyEmailLoginOtpReturnsAuthenticatedSession() { AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setEmail("demo@example.com") - .setCode("123456") - .build(), - new StreamObserver() { - @Override - public void onNext(AuthenticateResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + new StreamObserver() { + @Override + public void onNext(AuthenticateResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("9", ref.get().getAccountId()); @@ -443,15 +484,19 @@ void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { .thenThrow( new AuthenticationException( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setEmail("demo@example.com") - .setCode("123456") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + observer)); assertNotNull(observer.response()); assertEquals( @@ -460,6 +505,59 @@ void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { assertFalse(observer.receivedTransportError()); } + @Test + void credentialMethodsRejectAbsentAndWrongGameSessionPeersBeforeServiceCall() { + List rejectedPeers = + java.util.Arrays.asList( + null, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/world-management-service", + WORKLOAD_NAMESPACE, + "world-management-service")); + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver authenticateObserver = new RecordingObserver<>(); + RecordingObserver requestObserver = new RecordingObserver<>(); + RecordingObserver verifyObserver = new RecordingObserver<>(); + + withPeer( + peer, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + authenticateObserver)); + withPeer( + peer, + () -> + service.requestEmailLoginOtp( + RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), + requestObserver)); + withPeer( + peer, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + verifyObserver)); + + assertEquals("PERMISSION_DENIED", authenticateObserver.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", requestObserver.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", verifyObserver.response().getError().getCode()); + assertTrue(authenticateObserver.completed()); + assertTrue(requestObserver.completed()); + assertTrue(verifyObserver.completed()); + Mockito.verifyNoInteractions(accountService); + } + } + @Test void createAccountValidationErrorReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java index 93c652916c..6d21109aae 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java @@ -5,7 +5,8 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.util.concurrent.atomic.AtomicReference; +import java.util.ArrayList; +import java.util.List; import net.firedevops.firemud.account.v1.AddCurrencyRequest; import net.firedevops.firemud.account.v1.AddCurrencyResponse; import net.firedevops.firemud.account.v1.GetBalanceRequest; @@ -18,162 +19,101 @@ class VirtualCurrencyGrpcServiceTest { @Test - void getBalanceReturnsResponse() { + void getBalanceFailsClosedForRepeatedValidRequestsWithoutReadingBalance() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - Mockito.when(currencyService.getBalance(1L, 2L, "GOLD")).thenReturn(123L); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.getBalance( + StreamObserver observer = collecting(responses); + GetBalanceRequest request = GetBalanceRequest.newBuilder() .setTenantId("1") .setAccountId("2") .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } + .build(); + service.getBalance(request, observer); + service.getBalance(request, observer); - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertEquals(123L, ref.get().getBalance()); - } - - @Test - void getBalanceRuntimeFailureReturnsInternalErrorDetail() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - Mockito.when(currencyService.getBalance(1L, 2L, "GOLD")) - .thenThrow(new IllegalStateException("boom")); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.getBalance( - GetBalanceRequest.newBuilder() - .setTenantId("1") - .setAccountId("2") - .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INTERNAL", ref.get().getError().getCode()); - } - - @Test - void getBalanceRejectsZeroTenantIdBeforeLookup() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.getBalance( - GetBalanceRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertUnavailable(responses, "GetBalance is unavailable"); Mockito.verifyNoInteractions(currencyService); } @Test - void addCurrencyRejectsZeroAccountIdBeforeMutation() { + void addCurrencyFailsClosedForRepeatedValidRequestsWithoutAddingCurrency() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.addCurrency( + StreamObserver observer = collecting(responses); + AddCurrencyRequest request = AddCurrencyRequest.newBuilder() .setTenantId("1") - .setAccountId("0") + .setAccountId("2") .setCurrencyCode("GOLD") .setAmount(10) - .build(), - new StreamObserver<>() { - @Override - public void onNext(AddCurrencyResponse value) { - ref.set(value); - } + .build(); + service.addCurrency(request, observer); + service.addCurrency(request, observer); - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertUnavailable(responses, "AddCurrency is unavailable"); Mockito.verifyNoInteractions(currencyService); } @Test - void spendCurrencyRejectsZeroTenantIdBeforeSpend() { + void spendCurrencyFailsClosedForRepeatedValidRequestsWithoutSpendingCurrency() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.spendCurrency( + StreamObserver observer = collecting(responses); + SpendCurrencyRequest request = SpendCurrencyRequest.newBuilder() - .setTenantId("0") + .setTenantId("1") .setAccountId("2") .setCurrencyCode("GOLD") .setAmount(5) - .build(), - new StreamObserver<>() { - @Override - public void onNext(SpendCurrencyResponse value) { - ref.set(value); - } + .build(); + service.spendCurrency(request, observer); + service.spendCurrency(request, observer); - @Override - public void onError(Throwable t) {} + assertUnavailable(responses, "SpendCurrency is unavailable"); + Mockito.verifyNoInteractions(currencyService); + } - @Override - public void onCompleted() {} - }); + private static StreamObserver collecting(List responses) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + responses.add(value); + } - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(currencyService); + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }; + } + + private static void assertUnavailable(List responses, String message) { + assertEquals(2, responses.size()); + for (Object response : responses) { + assertNotNull(response); + if (response instanceof GetBalanceResponse getBalanceResponse) { + assertEquals("FAILED_PRECONDITION", getBalanceResponse.getError().getCode()); + assertEquals(message, getBalanceResponse.getError().getMessage()); + } else if (response instanceof AddCurrencyResponse addCurrencyResponse) { + assertEquals("FAILED_PRECONDITION", addCurrencyResponse.getError().getCode()); + assertEquals(message, addCurrencyResponse.getError().getMessage()); + } else if (response instanceof SpendCurrencyResponse spendCurrencyResponse) { + assertEquals("FAILED_PRECONDITION", spendCurrencyResponse.getError().getCode()); + assertEquals(message, spendCurrencyResponse.getError().getMessage()); + } else { + throw new AssertionError("Unexpected response type: " + response.getClass()); + } + } } } From abdf44389f07ec744f1c6401d0eafc0e16e78e3e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 18:57:46 +1200 Subject: [PATCH 17/55] Contain Account ingress and reconcile pending JOIN evidence --- .../microservices/account-service/README.md | 2 +- .../account-service/api-contracts.md | 43 +- .../account-service/runtime-and-data.md | 22 +- .../account-service/stripe-integration.md | 10 +- .../system-architecture-authz-route-matrix.md | 6 +- .../design-alignment/README.md | 2 +- .../whole-corpus-authority-review-plan.md | 2 + .../player-access-and-session.md | 43 +- .../controller/AccountController.java | 10 +- .../AccountAuditOutboxRepository.java | 20 + .../AccountConnectScopeRepository.java | 50 + .../AccountJoinOperationRepository.java | 114 ++- .../AccountTenantMembershipRepository.java | 42 + .../EmailVerificationTokenRepository.java | 16 + .../PasswordResetTokenRepository.java | 16 + .../service/AccountJoinReconciliationJob.java | 34 + .../AccountJoinReconciliationService.java | 462 ++++++++++ .../service/impl/AccountGrpcService.java | 382 ++++---- .../service/impl/AccountServiceImpl.java | 74 +- .../service/impl/PaymentGrpcService.java | 113 +-- .../src/main/resources/application-prod.yml | 7 +- .../src/main/resources/application.yml | 7 +- .../V27__account_join_reconciliation.sql | 25 + .../AccountApplicationIntegrationTest.java | 245 +++++ .../AccountJoinPostgresIntegrationTest.java | 383 ++++++++ ...ReconciliationPostgresIntegrationTest.java | 435 +++++++++ .../controller/AccountControllerTest.java | 27 +- .../security/GrpcJwtAuthInterceptorTest.java | 27 +- .../AccountJoinReconciliationServiceTest.java | 500 ++++++++++ .../service/impl/AccountGrpcServiceTest.java | 866 ++++++++++++------ .../service/impl/AccountServiceImplTest.java | 337 ++++++- .../service/impl/PaymentGrpcServiceTest.java | 280 ++---- 32 files changed, 3602 insertions(+), 1000 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationJob.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java create mode 100644 services/account-service/src/main/resources/db/migration/V27__account_join_reconciliation.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 8b76454984..3baa4d7a85 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -34,7 +34,7 @@ Manages user accounts and authentication for the platform. It stores profile dat - Profiles store a display name, bio, game history, and achievements. - Password reset and verification flows. - Subscription tracking with ban management. -- Owns the target **Stripe** hosting-plan billing and recurring hosting-subscription boundary; current provider lifecycle and entitlement proof remain partial. Incomplete `CreateSubscription` fails closed before mutation until caller-bound billing ownership, durable request identity, instrument selection, and provider-confirmed activation exist. The target containment contract also requires generic PaymentIntent, refund, donation, and creator-share surfaces to reject before any provider mutation, but the current implementation retains provider-mutating drift; see [Operations](./operations.md#saga-participation) and [Configuration](./configuration.md#implementation-status) for the current status. These surfaces are not advertised product paths. One-time and creator/player commerce remain future-gated under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). +- Owns the target **Stripe** hosting-plan billing and recurring hosting-subscription boundary; current provider lifecycle and entitlement proof remain partial. Incomplete `CreateSubscription` fails closed before mutation until caller-bound billing ownership, durable request identity, instrument selection, and provider-confirmed activation exist. The target containment contract also requires generic PaymentIntent, refund, donation, and creator-share surfaces to reject before any provider mutation, and the current generic gRPC handlers now return `FAILED_PRECONDITION` before service/provider calls; the underlying provider-mutating service and non-exposed purchase-workflow substrate remain unsupported; see [Operations](./operations.md#saga-participation) and [Configuration](./configuration.md#implementation-status) for the current status. These surfaces are not advertised product paths. One-time and creator/player commerce remain future-gated under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). - Expose Account relationship/projection data for actor discovery and access checks; do not create or own persisted gameplay actors. - gRPC APIs cover authentication, account lifecycle, export/delete, runtime/admission, membership, realm-grant, entitlement, profile, and hosting-billing operations; generic payment scaffolds do not widen that capability boundary. The canonical API inventory is [API Contracts](./api-contracts.md). diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 44f08c5285..bcb352d769 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -58,15 +58,15 @@ Explicit playtest grants remain partial: current Account persistence and interna The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. -The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile, presence, export, account-ID verification, and external-link gRPC handlers still lack complete method/workload and caller-subject binding; their bearer requirement does not establish that authorization. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. +The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile GET/PUT now require the exact Social Groups peer and a non-internal caller subject matching the requested account; presence-policy batch reads require the exact Social Groups peer and read only tenant-scoped profiles. The account-ID export, external-link, and verification gRPC handlers deny before data access or mutation because no authorized caller contract exists. Runtime membership, grant, and entitlement methods deny before Account reads until typed player/target binding is available; these local guards are not complete admission proof. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. `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` and `ExportAccount` implementation is Account/profile-local; 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 current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. 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. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain 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. 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. ### Current vs Target Export Lifecycle -The current `GET /accounts/{accountId}/export` route and current `ExportAccount` implementation are synchronous Account/profile-local exports. They return only the Account-owned local result, have no cross-service required-owner fan-in, and do not satisfy ADR 0050; neither the route nor the current implementation may be described as a complete portable-data export. +The current `GET /accounts/{accountId}/export` route is a synchronous Account/profile-local read. Direct account-ID `ExportAccount` gRPC and the legacy account-targeted tenant-export REST/service and gRPC entries deny before data access. The local Account read has no cross-service required-owner fan-in and does not satisfy ADR 0050; none of these current surfaces may be described as a complete portable-data or tenant-admin export. The target lifecycle is the asynchronous `POST /accounts/{accountId}/exports` operation followed by its stable status and content resources. Target `ExportAccount` gRPC behavior is the protocol equivalent of that lifecycle: Account durably creates or replays one export job, gathers every required owning-service contribution, exposes a versioned manifest with explicit owner outcomes, and makes content available only after the required fan-in reaches its terminal contract. Each initiation uses the already established caller `requestId`; Account computes a canonical, versioned `requestDigest` from the normalized export operation and persists one `export_operation` before fan-in, assigning its stable `exportId`. A retry with the same request identity and matching digest replays that operation and `exportId`, including after a lost response; reusing the request identity with a different digest is an idempotency conflict and cannot create another export. The current local implementation is known drift from this target. @@ -88,20 +88,20 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `IssueAutomationOperatorAuthorizationReference` – target Account-owned typed issuance RPC for the exact Logging & Admin workload mTLS identity and a versioned automation policy. It is a separate automation-specific tenant-scoped authority path, not a human membership or `control-ui` path; until a published schema registry exists, its target-not-routable contract explicitly selects only the `non_moderation` branch, requires schema-declared `action_category` absence, and rejects moderation schemas before issuance. Account validates the `automation_operator` issuance kind, exact authenticated workload binding, policy identity/version, `tenant_generation`, target/scope, action-family schema pair, typed request fields, `controlPlaneRequestId`, canonical `mutationDigest`, `reservationOwnerId`, and positive `reservationClaimFence`, and issues no user or global-role authority. `controlPlaneRequestId` and `mutationDigest/v1` are the mutation identity and digest only for that non-moderation branch; a future moderation automation path must use dedicated moderation identities, digests, and idempotency and must treat `controlPlaneRequestId` as correlation-only. - `RedeemOperatorAuthorization` – target Account-owned redemption RPC used only by the exact owner workload named in the issued record. The owner presents the exact opaque reference plus the Account-returned `authorizationReferenceFingerprint` transported unchanged through Logging & Admin, its independently derived action family, schema pair, typed target/scope/request fields, `controlPlaneRequestId`, canonical `mutationDigest`, `reservationOwnerId`, and positive `reservationClaimFence`; Account authenticates the exact mTLS caller and returns the authenticated authority projection, a fresh Account recomputation of `authorizationReferenceFingerprint`, and immutable `authorityEvidenceBundle` only when every value and current authority state still match. The owner compares the forwarded fingerprint with that fresh Account value before treating redemption as successful or authorizing the mutation. Account consumes the reference atomically on successful redemption and durably records the redemption result. Before successful redemption, an exact same-tuple retry may replay that durable result; after consumption, any replayed result is evidence for the same completed redemption only and cannot authorize a new owner attempt. Owner rearm after a terminal result requires fresh Account authorization and a new opaque reference. - `RecoverOperatorAuthorizationReference` – target Account-owned read-only recovery RPC for the exact authenticated Logging & Admin workload. The request repeats the complete immutable typed issuance tuple, actor or automation-policy evidence, and current reservation owner/claim fence; Account returns only the original issuance response or original terminal outcome from its durable record. Durable `NOT_FOUND` is read-only lookup evidence that no matching record was found, never proof for `NOT_EXECUTED_BEFORE_AUTHORIZATION`; that terminal state requires durable phase evidence that Account authorization cannot complete and durable dispatch evidence that no owner-forward call occurred and no owner-forward call can still occur. Until both proofs exist, the operation remains `AUTHORIZATION_PENDING`, non-replayable and non-rearmable. It never issues, extends, rotates, redeems, or semantically recreates a reference. -- `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. -- `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails and permits account holders to select `PUBLIC`, `FRIENDS_ONLY`, or `PRIVATE`, while `HIDDEN_STAFF` remains reserved for the staff-visibility owner. The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. +- `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. The current direct gRPC read requires the verified Social Groups peer and a non-internal caller account subject equal to the requested account before its existing membership check. +- `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails and permits account holders to select `PUBLIC`, `FRIENDS_ONLY`, or `PRIVATE`, while `HIDDEN_STAFF` remains reserved for the staff-visibility owner. The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. The direct gRPC mutation has the same verified Social Groups peer and exact caller-account guard. -- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 account IDs. Social projections consume this authority at read time; unknown or unavailable entries are intentionally omitted so callers apply complete `PRIVATE` redaction. -- `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current implementation behind this method remains the local legacy export described above. +- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 account IDs. Social projections consume this authority at read time; unknown or unavailable entries are intentionally omitted so callers apply complete `PRIVATE` redaction. The current direct gRPC read requires the verified Social Groups peer. +- `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The legacy account-ID gRPC method currently fails closed before reading data because it cannot establish that caller/operation binding; the local export substrate is not the canonical route. - `CommitTenantCapacityAdmission` – **target-state internal RPC** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. -- `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only; the current account-targeted gRPC request is implementation drift. -- `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. +- `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only; the current account-targeted gRPC method fails closed before reading data and is implementation drift. +- `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. The current service must fail closed until the pending-deletion workflow, complete provider/transfer clearance, and retained financial evidence are available; its legacy synchronous hard-delete is not an accepted implementation. - Pending-deletion access is a separate opaque Account credential, not a JWT or normal account session. The non-export deletion-specific routes are `GET /accounts/{accountId}/deletion`, `POST /accounts/{accountId}/deletion/cancel`, and `POST /accounts/{accountId}/deletion/billing-settlement`; each is classified `pending_deletion_scoped` for its exact action and bound to the Account-owned deletion workflow registry. The account export lifecycle is state-dependent but always uses the canonical asynchronous `POST /accounts/{accountId}/exports`, `GET /accounts/{accountId}/exports/{exportId}`, and `GET /accounts/{accountId}/exports/{exportId}/content` resources: active accounts use the ordinary authenticated account subject, while pending-deletion accounts use the pending-deletion credential and `pending_deletion_scoped` classification on that same lifecycle. These target routes are not currently routable. - `POST /auth/pending-deletion/recovery/challenge` and `POST /auth/pending-deletion/recovery` are dedicated target recovery routes classified `public`; they may issue only `pending-deletion-access`, never normal login, bootstrap, connect-token, tenant, purchase, or gameplay authority. These target routes are not currently routable. - `RequestPasswordReset` – initiate a password reset email. Public initiation returns the same neutral success for known and unknown normalized email addresses; an unknown address creates no token and schedules no delivery. -- `CompletePasswordReset` – update the password using a token. -- External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. No provider route may become routable until the target globally bound flow is implemented and proved. +- `CompletePasswordReset` – update the password using a token. The current service conditionally consumes the still-valid token in the same transaction as the account mutation so a concurrent reuse cannot apply a second update; PostgreSQL execution remains a proof gate. +- External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the account-ID gRPC `LinkExternalAccount` also fails closed before mutation. The persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. No provider route may become routable until the target globally bound flow is implemented and proved. - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. - `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. @@ -111,18 +111,18 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. -- `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. The proto and Account producer can emit lifecycle state and `membershipAuthorityGeneration` alongside independent `membershipVersion`, but the current bare request cannot establish the required typed Game Session player context, so the direct gRPC handler fails closed before that producer read. Game Session does not yet enforce those fields. One fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. +- `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context. The current tenant-only proto/request lacks both complete alternatives, so the direct gRPC handler fails closed before the underlying producer read; Game Session's older consumer request must be converged before admission can rely on this route. Logging & Admin and `control-ui` callers use the redacted route variants. -- `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. +- `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. The currently exposed `GetRealmAccessGrantForRuntime` request cannot carry that lifecycle-bound typed caller/target evidence and its direct gRPC handler fails closed before reading grant data. - `GetTenantEntitlementsTenant` – caller-bound tenant-admin entitlement view for billing-safe control-plane UX. - `GetTenantEntitlementsCrossTenantSupportSafe` – cross-tenant support-safe entitlement view with redacted, high-level fields only. -- `RequestEmailVerification` – send an account-scoped verification email. The public REST initiation resolves a normalized email address and returns the same neutral success for known and unknown addresses; the internal gRPC method retains its account-ID request. Unknown public requests create no token and schedule no delivery. -- `VerifyEmail` – confirm an email verification token. -- `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. It must reject before any Stripe mutation and is not a v1 hosting-billing operation or entitlement path. Only a separately typed hosting-billing operation may mutate Stripe; until this generic method is removed or converged, its current implementation is drift and it is internal-only behind exact authenticated mTLS workload/method allowlisting, not a bearer-token variant. See [Stripe Integration](./stripe-integration.md). +- `RequestEmailVerification` – send an account-scoped verification email. The public REST initiation resolves a normalized email address and returns the same neutral success for known and unknown addresses; unknown public requests create no token and schedule no delivery. The legacy account-ID gRPC method fails closed before token creation or delivery because it cannot establish the caller-account binding. +- `VerifyEmail` – confirm an email verification token. The current service conditionally consumes the still-valid token in the same transaction as the account mutation; PostgreSQL concurrent-reuse execution remains a proof gate. +- `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. Its current gRPC handler returns `FAILED_PRECONDITION` before any Stripe call; it is not a v1 hosting-billing operation or entitlement path. Only a separately typed hosting-billing operation may mutate Stripe. Any retained internal-only generic call requires exact authenticated mTLS workload/method allowlisting, not a bearer-token variant; the deny-only handler does not establish that future caller authorization. See [Stripe Integration](./stripe-integration.md). - `CreateSubscription` – target operation for creating one recurring hosting subscription under the canonical [Subscription Management](./subscription-management.md) lifecycle and [Stripe Integration](./stripe-integration.md) provider-binding contract. The local proto carries only tenant/account/plan fields and cannot establish the required caller-bound billing owner, instrument, stable request identity, or provider-confirmed lifecycle. The current handler therefore returns `FAILED_PRECONDITION` before mutation until that complete boundary is implemented. -- `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. It must reject before any Stripe mutation, is not a supported v1 product contract, and cannot create a FireMUD entitlement. Until removed or converged, its current implementation is drift and it remains internal-only behind the exact authenticated mTLS workload/method allowlisting boundary described in [Stripe Integration](./stripe-integration.md). -- `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. It must reject before any Stripe mutation. Hosting refunds use a separately typed hosting-billing operation and its durable refund workflow; future marketplace refunds require a separately accepted value-conservation contract. +- `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. Its current gRPC handler returns `FAILED_PRECONDITION` before any Stripe call and cannot create a FireMUD entitlement. Any future internal call requires the exact authenticated mTLS workload/method allowlist described in [Stripe Integration](./stripe-integration.md). +- `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. Its current gRPC handler returns `FAILED_PRECONDITION` before any Stripe call. Hosting refunds use a separately typed hosting-billing operation and its durable refund workflow; future marketplace refunds require a separately accepted value-conservation contract. - `GetBalance` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. @@ -166,6 +166,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | | `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/export` | **Current legacy route.** Returns an Account/profile-local export and does not satisfy ADR 0050. | +| `GET` | `/accounts/{accountId}/tenant-export` | **Current legacy route, disabled.** Returns `501 NOT_IMPLEMENTED` before tenant/global Account data reads; the account-selected shape cannot satisfy the tenant-admin export contract. | | `POST` | `/accounts/{accountId}/exports` | **Target-state only.** Initiate or idempotently replay one asynchronous portable-data export within the defined global account scope using the caller's `requestId`; Account computes and persists the canonical, versioned `requestDigest` and `exportId`, returns the existing operation on a matching retry, and returns an idempotency conflict on a digest mismatch. Active accounts use the authenticated account subject; `security_locked` accounts use only the distinct Account-issued, expiring `security-lock-export` credential after Account-owned recovery authorization; `deactivated_pending_delete` accounts use only `pending-deletion-access`. No state accepts a tenant selector or a support-only bypass. | | `GET` | `/accounts/{accountId}/exports/{exportId}` | **Target-state only.** Read durable portable-data export status, owner contribution state, and the versioned manifest using the same bounded subject/credential branch that initiated the job. | | `GET` | `/accounts/{accountId}/exports/{exportId}/content` | **Target-state only.** Download the completed export artifact using the same bounded subject/credential branch; a security-lock recovery credential authorizes only its exact account/export lifecycle and is never a pending-deletion credential. That security-lock credential is single-use for export initiation and bounded/expiring for status and content access; pending-deletion access remains the separate workflow credential. Losing a response requires retrying the same persisted operation, not minting a second export or reusing the credential for another scope. | @@ -173,7 +174,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `POST` | `/accounts/{accountId}/deletion/cancel` | **Target-state only.** Cancel eligible pending deletion and establish a fresh normal account generation after the dedicated recovery proof. | | `POST` | `/accounts/{accountId}/deletion/billing-settlement` | **Target-state only.** Perform only the necessary billing-settlement action allowed by the pending-deletion workflow. | | `GET` | `/tenant-admin/tenants/{tenantId}/export` | **Target-state only; not currently routable.** Tenant-wide billing-safe export of tenant-owned data for a live `tenantAdmin`; no account subject selector. | -| `DELETE` | `/accounts/{accountId}` | Delete the global account after billing-owner preconditions pass | +| `DELETE` | `/accounts/{accountId}` | **Current route, disabled.** Returns `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before mutation. The target pending-deletion and retained-data workflow requires full ADR 0043/`DATA-01` authority and proof before enabling deletion. | | Provider-specific callback route (future) | Not yet routable | Link one server-verified provider identity after that provider's complete contract and proof exist; the caller-asserted `/accounts/{accountId}/external` route is unsupported | | `POST` | `/auth/player-bootstrap` | Current endpoint; **target registry-backed behavior:** return a short-lived `player-bootstrap` token for gameplay bootstrap only after Account has atomically established exactly one active issued-token registry record; registry failure fails issuance before the token is exposed, and the token is not the `/auth/login` control-ui session | | `GET` | `/auth/bootstrap/worlds` | List caller-visible worlds for first-party gameplay bootstrap | @@ -192,7 +193,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `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/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 fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. 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. Exact-final-head PostgreSQL proof, recovery/reconciliation after an unknown commit outcome, direct text end-to-end proof, and membership-generation snapshot proof remain open. | +| `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 | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 3fcae8a374..d4a00eeaeb 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and successful deletion immediately removes Account-owned rows including payment transactions. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. +The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and the legacy synchronous deletion path is now blocked before any row deletion because complete provider/transfer clearance and retained-record handling are absent. The partial export behaviors still conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. Account V22/V23 rewrite retained email values to canonical form and validate a canonical-email check, but compatibility with older binaries is unproved; the retained-data and rollout proof gap is tracked in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). @@ -16,21 +16,21 @@ 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 or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. 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. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. 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 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. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit 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. These paths do not create or restore membership. 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. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains open; no Overseer decision is implied. 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 are denied before Account reads until a typed verified player/target contract and consumer are implemented. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit 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. These paths do not create or restore membership. 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 current `application.yml` and `application-prod.yml` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. +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. -The credential-granting gRPC `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` methods now require the verified exact Game Session peer before invoking Account credential/challenge operations, with focused missing/wrong-peer denial tests. The broader internal gRPC boundary is not converged: legacy `GetProfile`, `UpdateProfile`, `ListPresenceVisibilityPolicies`, `ExportAccount`, `ExportTenantData`, `LinkExternalAccount`, and account-ID `RequestEmailVerification` still accept request-selected subjects with only bearer authentication, not exact method/workload and caller-subject authorization. The public REST guards do not protect direct gRPC calls. This is a current cross-account read, mutation, export, and verification side-effect gap, not evidence that every internal caller can bypass mTLS. +The credential-granting gRPC `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` methods require the verified exact Game Session peer before invoking Account credential/challenge operations. Legacy profile GET/PUT require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy reads require that peer. Direct account-ID export, external-link, and verification methods deny before reads or mutation. Runtime membership, grant, and entitlement reads deny even the exact Game Session peer until Unit 1B provides typed caller/target binding. Focused negative tests cover the local guards, but composed certificate and consumer proof remains open; REST guards alone do not protect direct gRPC calls. The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The live legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes instead admit the broad shared global-privileged-role helper (including `moderator`), accept caller-supplied `grantedBy`/`grantReason`, and do not apply the target lifecycle identity, revision, digest, or request-replay contract. They must be removed or fail closed until the canonical owner transport and its authenticated attribution and replay proof are implemented; this route is not an additional grant authority. -Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; email-verification token consumption has the same read/update/delete race. Atomic single-use consumption and concurrent-reuse proof for both paths remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). +Recovery/verification foundations are live. Password-reset and email-verification completion now claim the exact token row with a conditional SQL delete inside the account transaction before changing Account state; a failed or concurrent losing claim cannot mutate the account, and rollback restores the token. Focused local tests execute the single-use and rollback behavior; PostgreSQL concurrent-reuse cases compile but have not executed without Docker. Session revocation, token registry, distributed abuse controls, and end-to-end email-link reachability remain separate gaps under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -The local direct-text `REALMS`-to-`JOIN` path issues a short-lived Account-owned scope for an authenticated caller and validates the retained target snapshot and caller binding at `JoinPublicProductionMembership`; Game Session supplies a server-generated join-attempt identity. A committed policy-independent intent survives entitlement outages and can be resumed by an exact request retry; when the second transaction outcome is uncertain, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +The local direct-text `REALMS`-to-`JOIN` path issues a short-lived Account-owned scope for an authenticated caller and validates the retained target snapshot and caller binding at `JoinPublicProductionMembership`; Game Session supplies a server-generated join-attempt identity. A committed policy-independent intent survives entitlement outages and can be resumed by an exact request retry; when the second transaction outcome is uncertain, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. A bounded readback-only Account recovery worker now revisits abandoned `PENDING` intents without the caller; it cannot rerun the raw bearer-bound JOIN request, terminalize from expiry or absence, or prove direct text-client end-to-end behavior. PostgreSQL recovery, concurrency and direct text-client proof remain open. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -43,7 +43,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after Logging & Admin returns matching receipt evidence; failures leave it `PENDING` for retry. Logging & Admin locally implements durable receipt deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipts. After an accepted terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local implementation facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry resumes a pending intent; an absent terminal readback is reported as retryable unavailable, not as a membership result. No periodic pending-operation reconciler is claimed. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after Logging & Admin returns matching receipt evidence; failures leave it `PENDING` for retry. Logging & Admin locally implements durable receipt deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipts. After an accepted terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local implementation facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry resumes a pending intent; an absent terminal readback is reported as retryable unavailable, not as a membership result. A periodic bounded pending-operation reconciler is present locally and performs exact positive readback only; PostgreSQL execution and external delivery are not claimed. - **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). @@ -85,7 +85,7 @@ Transitions are explicit: `active` may move to `security_locked`, `deactivated_p The target restriction command commits the immutable category revision, current projection, account authority-generation effect, and idempotent result in one Account transaction. Logging & Admin may submit a digest-bound command for a punitive platform restriction or appeal outcome, but it remains the policy/case/audit owner and never writes Account tables. The current service does not yet prove this separate platform-ban table/command, recovery isolation, monotonic ordering, or end-to-end generation enforcement. -Account deletion is global, not tenant-scoped. A self-service request requires recent authentication, explicit confirmation, and a clear portable-data export option within the defined account scope. `DeleteAccount` must fail with `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER` until billing authority proves that the account has no owned subscription in `pending`, `provisioning`, `trialing`, `active`, `past_due`, `grace`, or `suspended`, no nonterminal billing-owner transfer naming it as old or proposed owner, and no unresolved customer, subscription, webhook, outbox, cancellation, or provider-reconciliation work. The response returns all safely disclosable tenant and blocker categories. The caller must complete transfer or terminal cancellation and allow every related durable/provider item to reconcile before retrying deletion. The current implementation proves only the nonterminal-subscription subset of this target precondition. +Account deletion is global, not tenant-scoped. A self-service request requires recent authentication, explicit confirmation, and a clear portable-data export option within the defined account scope. `DeleteAccount` must fail with `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER` until billing authority proves that the account has no owned subscription in `pending`, `provisioning`, `trialing`, `active`, `past_due`, `grace`, or `suspended`, no nonterminal billing-owner transfer naming it as old or proposed owner, and no unresolved customer, subscription, webhook, outbox, cancellation, or provider-reconciliation work. The response returns all safely disclosable tenant and blocker categories. The caller must complete transfer or terminal cancellation and allow every related durable/provider item to reconcile before retrying deletion. The current service instead returns `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before any row mutation for every existing account; it does not claim that the complete provider/transfer guard, pending-deletion lifecycle, or finite retained-record schedule is implemented. This containment remains in place until those gates are proved. An eligible confirmed request enters `deactivated_pending_delete`, immediately revokes ordinary account and bootstrap authority, and hides normal account/profile surfaces. Only explicit deletion cancellation, export, and necessary billing-settlement routes remain during the published cancellation and retention window. A durable, idempotent cross-service workflow then deletes, anonymizes, tombstones, or schedules policy-allowed retention for each owning domain. Failed work leaves the account pending with retry and operator diagnostics; a durably scheduled billing/provider step is intermediate pending evidence only and never terminal deletion. The account becomes terminal `deleted` only after every required non-retained step has completed and every permitted retained record has been durably finalized under its approved retention policy. @@ -270,7 +270,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### Runtime Implementation Status and Drift -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may return `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter response cannot be classified as `INACTIVE` because lifecycle state is target-only. The local explicit `JOIN`/`Join & Play` operation and controller exist; the current non-public mappings differ by surface: connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. PostgreSQL exact-final-head proof, recovery/reconciliation after unknown commit outcomes, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is present; the existing Account runtime membership, grant, and entitlement gRPC method shapes now deny before data reads pending typed player/target binding. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may return `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter response cannot be classified as `INACTIVE` because lifecycle state is target-only. The local explicit `JOIN`/`Join & Play` operation and controller exist; the current non-public mappings differ by surface: connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. A bounded Account-owned readback worker revisits abandoned `PENDING` JOIN intents but cannot infer a terminal result from expiry or absent evidence. PostgreSQL exact-final-head lost-acknowledgement/concurrency proof, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. ## Monetization and Notification Domain Notes @@ -278,7 +278,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit Billing provider integration, instrument ownership, payment reconciliation, and the reserved future-marketplace entitlement substrate are canonical in [Stripe Integration Design](./stripe-integration.md). Subscription status lifecycle and plan-change timing are canonical in [Subscription Management Design](./subscription-management.md). -The current virtual-currency gRPC facade returns `FAILED_PRECONDITION` for `GetBalance`, `AddCurrency`, and `SpendCurrency` before touching its existing storage/service substrate. This is fail-closed containment of unsupported v1 operations, not a completed economy or an entitlement source. Generic payment and donation/refund provider mutations remain separately open under the Stripe owner contract. +The current virtual-currency gRPC facade returns `FAILED_PRECONDITION` for `GetBalance`, `AddCurrency`, and `SpendCurrency` before touching its existing storage/service substrate. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` gRPC handlers likewise return `FAILED_PRECONDITION` before service/provider calls. These are fail-closed containment of unsupported v1 operations, not a completed economy, hosting-billing operation, or entitlement source; their underlying service substrate remains provider-mutating and unavailable for supported use under the [Stripe owner contract](./stripe-integration.md). Runtime and data consequences remain local to this document: `payment_transaction` is the financial/provider audit record, while `purchase_entitlement` is reserved for a separately accepted future marketplace and is not a v1 hosting-billing authority. Account must not infer gameplay value from payment status alone; a future paid-but-unfulfilled grant would remain non-active and therefore non-authorizing, and its durable operation state would remain visible to reconciliation and deletion guards. Existing donation rows and virtual-currency/premium-hosting code remain implementation substrate unless a supported product contract explicitly admits them; creator donations/tips are deferred. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 2812bae52f..7eeae42323 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -19,7 +19,7 @@ The future direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-crea ## Implementation Status -The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs a verified webhook lifecycle, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, active-subscription deletion guards, and end-to-end entitlement enforcement. The current generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` implementations are provider-mutating drift: those methods are unsupported/deferred and must reject before any Stripe mutation. Only separately typed hosting-billing operations may mutate Stripe; this authority slice does not change the code. `purchase_entitlement` and paid-but-unfulfilled compensation are reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md), and remain unsupported until its launch gates are implemented and proved. +The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs a verified webhook lifecycle, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, complete provider/transfer deletion clearance, retained financial evidence lifecycle, and end-to-end entitlement enforcement. The current `DeleteAccount` service returns `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` for every existing account before deleting any row; this is containment, not an implemented deletion workflow or complete blocker classification. The current generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` gRPC handlers reject with `FAILED_PRECONDITION` before provider or service calls. The underlying `PaymentService` and non-exposed purchase-workflow substrate still contain provider-mutating code and are not a supported v1 product path or entitlement source; future entry points must not re-enable it without the separately typed hosting-billing contract. `purchase_entitlement` and paid-but-unfulfilled compensation are reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md), and remain unsupported until its launch gates are implemented and proved. The account-owned wallet contracts are also target state. Per-subscription instrument binding, replacement-before-detach, the single-use transfer proof and database transfer fence, immutable predecessor-provider history, and the audited `cross_tenant_billing_safe` ownership-transfer route remain absent or partial until the corresponding routes and enforcement are implemented; the [Authorization Route Matrix](../../system-architecture-authz-route-matrix.md) records that coverage drift. @@ -119,7 +119,7 @@ If a future marketplace is separately accepted, it must define disjoint typed op - A fixed product purchase supplies an immutable `product_code`; it does not accept caller-authoritative `amount_cents` or currency. Account resolves the active product, price, currency, and catalog revision from the server-side Stripe product catalog. The resolved values are immutable inputs to the purchase digest and durable `purchase_operation`, and the same values are used for the Stripe `PaymentIntent`, checkout binding, webhook correlation, and reconciliation. - A variable donation uses a separate donation amount path. The caller may supply an amount only within the server-configured minimum, maximum, precision, and currency bounds; Account rejects fixed-product fields on that path and records the accepted bounded amount and server-authoritative currency in the digest and durable operation. A donation amount must never be interpreted as a fixed product price. -1. A future typed purchase or donation operation calls the Account Service with the appropriate fixed-product or bounded-donation variant, authenticated context, optional `tenantId`, and caller request ID. Under the target containment contract, the generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` methods reject before any Stripe mutation; their current provider-mutating implementation remains the drift recorded above. For an accepted future typed operation, Account derives the authoritative account from authenticated context and, before any external Stripe customer or `PaymentIntent` call, commits one durable `purchase_operation` and its webhook-correlation identity bound to the operation type, caller request ID, immutable purchase digest, resolved commercial values, customer-operation reference, and separate stable PaymentIntent idempotency identity. The webhook must resolve through this durable operation identity rather than a provider ID that may not yet have been persisted. +1. A future typed purchase or donation operation calls the Account Service with the appropriate fixed-product or bounded-donation variant, authenticated context, optional `tenantId`, and caller request ID. Under the target containment contract, the generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` methods reject before any Stripe mutation; their current gRPC handlers do so, while the underlying provider-mutating service substrate remains unavailable for supported use. For an accepted future typed operation, Account derives the authoritative account from authenticated context and, before any external Stripe customer or `PaymentIntent` call, commits one durable `purchase_operation` and its webhook-correlation identity bound to the operation type, caller request ID, immutable purchase digest, resolved commercial values, customer-operation reference, and separate stable PaymentIntent idempotency identity. The webhook must resolve through this durable operation identity rather than a provider ID that may not yet have been persisted. 2. The Account Service provisions or reuses the Stripe customer through the same durable intent contract as `billing_customer`: persist the account-keyed provisioning intent and stable customer-provisioning idempotency identity, reconcile provider metadata before retrying after a timeout, lost response, or failed local commit, and leave ambiguous state nonterminal. A generic lookup-or-create flow after an ambiguous attempt is prohibited. Once the customer is confirmed, Account calls Stripe to create the `PaymentIntent` using the purchase operation's distinct stable payment-intent idempotency identity and non-secret provider metadata carrying the durable purchase-operation correlation identity. 3. A `payment_transaction` row is created in `pending` status and linked to the purchase operation, with the returned `payment_intent` ID recorded as `provider_id`. If the provider call may have succeeded but the response or local linkage commit is lost, the operation remains nonterminal and reconciliation uses the same idempotency and provider-metadata identities; it never creates a new logical purchase attempt. 4. The client completes payment using Stripe’s client-side flow (for example, via Stripe.js); Stripe later calls a configured webhook when the intent succeeds or fails. @@ -170,9 +170,9 @@ Stripe integration must preserve tenant isolation while allowing platform-level The Account Service exposes gRPC and REST endpoints for initiating and inspecting billing flows: -- `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift and is not a supported v1 entitlement path. Only a separately typed hosting-billing operation may call Stripe. -- `CreateDonation` – Existing generic donation substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift and is not a supported v1 product path. -- `RefundPayment` – Existing generic refund substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift. Hosting refunds use a separately typed hosting-billing operation and durable refund workflow; future marketplace refunds require the separately accepted value-conservation contract. +- `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred. The current gRPC handler rejects before any Stripe mutation and cannot create a v1 entitlement; only a separately typed hosting-billing operation may call Stripe. +- `CreateDonation` – Existing generic donation substrate; unsupported/deferred. The current gRPC handler rejects before any Stripe mutation and is not a supported v1 product path. +- `RefundPayment` – Existing generic refund substrate; unsupported/deferred. The current gRPC handler rejects before any Stripe mutation. Hosting refunds require a separately typed hosting-billing operation and durable refund workflow; future marketplace refunds require the separately accepted value-conservation contract. - `CreateSubscription` – Create one recurring hosting subscription for an immutable `tenantId` and initial `plan_code` with caller-stable `requestId` and Account-computed versioned `requestDigest`; a retry with the same `requestId` and normalized create fields recomputes the same digest and replays the durable operation, while changed fields return `IDEMPOTENCY_CONFLICT`. Its provider `subscription_provisioning_request_id` is a separate identity, and creation rejects update-only fields. The current proto does not expose the caller retry pair, billing-owner resolution, or instrument selection, so the current handler rejects with `FAILED_PRECONDITION` before local or provider mutation rather than manufacturing an active subscription. - `UpdateSubscription` – Apply a plan, instrument, cancellation, or other supported mutation to an existing immutable `subscriptionId` using a distinct operation identity and expected row version; it rejects creation-only fields and any `tenantId` change. - `TransferBillingOwner` – Start or recover the audited provider-replacement handoff through the `subscription_transfer` state machine and guarded update of the canonical subscription row. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 2ddc39ee02..5f9988c8ed 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -26,7 +26,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. -- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy in rows 260-261. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. +- `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. - The `platformAdmin` privileged-control predicate applies to the exact internal-workload `account-service/IssueHumanOperatorAuthorizationReference` issuance route in addition to its declared route-class allowlist. This exact route identity does not add `internal_workload` to the support or billing-safe classification scopes; the separate automation issuance path prohibits privileged control. @@ -252,8 +252,8 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GET /accounts/{accountId}/exports/{exportId}/content` | State-dependent `account_scoped`, `security_lock_export_scoped`, or `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=export_content`; the active branch explicitly requires `applicability.account_state=active` and authoritative `account_state_export_eligible` evidence. The same branch must exact-match the completed operation before downloading its artifact. A cross-account or nonexistent `exportId` is non-disclosing and returns `PERMISSION_DENIED`. Active-account access requires `required_account_export_job_and_outcome`; security-lock access uses the same bounded expiring credential for the export operation after initiation and requires `required_account_recovery_case_export_job_and_outcome`; pending-deletion access remains a separate workflow credential and requires `required_account_deletion_workflow_export_job_and_outcome`. | | Account Service | `POST /accounts/{accountId}/deletion/billing-settlement` | `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=billing_settlement`; restricted to necessary billing settlement and cannot authorize export or normal billing mutations | | Account Service | `GET/PUT /tenants/{tenantId}/profiles/{accountId}` | `tenant_regular` | Canonical tenant-qualified self-service profile routes require path `accountId` to equal the authenticated caller for every scoped role, including `tenantAdmin`. Membership freshness and scoped-role checks consume the Account owner contract; no administrative or `platformAdmin` cross-account override exists, and legacy `/profiles/{accountId}` is implementation drift only | -| Account Service | `DeleteAccount` (`DELETE /accounts/{accountId}`) | `account_scoped` | Subject-bound to caller `accountId`; `platformAdmin` override only. The route additionally requires billing-deletion clearance for nonterminal subscription, transfer, provider, webhook, outbox, cancellation, customer, and reconciliation work. | -| Account Service | `ExportAccount` (`GET /accounts/{accountId}/export`) | `account_scoped` | **Status: `current_openapi_operator_surface`; current synchronous legacy implementation; not a second target operation.** Its target RPC semantics are protocol-equivalent to the sole canonical `POST /accounts/{accountId}/exports` route. The current Account/profile-local response and legacy `platformAdmin` override are known drift; the target canonical path is caller-subject-only. | +| 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 | `Authenticate` | `internal_workload` | Exact Game Session mTLS identity, no pre-existing issued token, and trusted server-derived credential source context | diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index fe096909ca..79dd0141be 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Cycle 23 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, billing handoffs, and the Account Service README primary source; the starting source count is 29. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–23 were productive. Cycle 13 corrected fail-open empty/ambiguous subscription-row entitlement projection. Cycle 14 confirmed the full authority/consolidation lens and routed public `PLAY` admission-outcome ordering to Unit 1B. Cycle 15 corrected billing status/registration schema and classified retryable entitlement outages. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and routed exact-binding reconnect token/lease to Unit 1B without an LKG fallback. Cycle 17 exposed public-registration membership bypass; #2847 converged registration to global-only identity and explicit policy-bound JOIN, while #2848 supplies the durable audit receiver. Cycle 18 corrected current/target status and routed non-public realm-discovery/CHARS disclosure to Unit 1B. Cycle 19 fixed Account's canonical UUID realm binding and stale membership-response status. Cycle 20 corrected local JOIN availability claims, `past_due` status precision, and Account producer audit-payload compaction after verified receiver minimization. Cycle 21 terminalized deterministic changed-policy JOIN conflicts in #2847 and corrected further stale local-JOIN status in #2848 consumer docs and historical decision inventories. Cycle 22 contained the previously exposed Game Design creator writes at Gateway with explicit read-only routes; the Account-owned hosted-content gate remains unimplemented and unproved. Cycle 23 guarded Account credential-granting gRPC methods by exact Game Session peer, contained deferred currency RPCs, and corrected stale route, membership-evidence, and registration status; other legacy gRPC subject binding remains open. Drafts #2846–#2848 are correction evidence, not taper or merge readiness. PostgreSQL execution, retained-data deployment disposition, unknown-commit recovery, direct text-to-Logging proof, lifecycle/generation snapshot completion, finite `COMMITTED` audit retention, and full billing evidence remain open. The initial billing-owner source before the first subscription row remains undecided, so creation stays disabled and AA-1.4 tracks the decision; explicit free/trial state, current-row authority, and strict new-binding controls remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index 0f9d2f3db8..2309011d8a 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -32,6 +32,8 @@ The 23 original family sections remain the top-level corpus map, but 5B is now p 4. Update **only the alignment index** for section/subunit status, main PR, completion evidence, and routed obligations. The index keeps the three 5B subunit rows under the two-document tracking model; record their evidence and routed work in the planned **Evidence / routed work** column. Record the whole-5B synthesis as a non-row evidence line associated with those three rows, never as an aggregate 5B status row. The index must not become a PR-shaped ledger. A split implementation PR is linked from the relevant subunit evidence rather than creating a PR section. Keep detailed finding evidence with the relevant review/PR artifacts, not a second live section-status ledger. Any future semantic boundary change must update both maintained documents before assigning new subunits or PRs. 5. A section is complete only when its refreshed source list and material handoffs have been assessed, valid findings are fixed or explicitly owned elsewhere, and the current review has tapered. For 5B, completion additionally requires all three subunit terminals plus a tapered whole-5B synthesis. Record each subunit's reviewed/allocated source count, evidence, and routed work in the index; record synthesis evidence on its non-row line. At final closeout, compare the union of the refreshed section and subunit lists with the [allocation](./design-capability-allocation.md): every allocated source must be reviewed in an owning section, explicitly handed off by heading, or listed as an exemption with a reason. Merging one PR alone does not establish section or subunit completion. +When Overseer closes broad discovery for a section by explicit judgment before taper, record that as a discovery stop, not section completion or merge readiness. Before handing off the section, reconcile each accepted finding and relevant tracker gap against current behavior: implement unsafe exposed paths in their owning boundary, or assign substantial pre-v1 work to a concrete owner and successor with dependency and activation gate. A tracker link alone does not remediate a live defect. Record deliberately deferred features with their containment, reason and revisit trigger; keep unexecuted PostgreSQL, cross-service and deployment proof attached to the applicable readiness gate. Preserve the difference between whole-corpus coverage, implemented capability and exercised proof in the index and owning trackers. + ## Starting manifests These recovered manifests are starting review prompts, not frozen inventories or old completion claims. Refresh each when its section starts. Historical statements about what is currently implemented or unresolved must be verified before use. Numbered paths below are review inputs; heading-scoped consumers and adjacent sections remain handoffs rather than duplicate owners. 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 bf55ad3f8a..640588e4e9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,13 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision; PostgreSQL runtime proof and direct text-client end-to-end proof are not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. 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. -Account runtime admission reads remain a security/proof blocker: both `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are currently configured as public gRPC methods, and handlers accept caller-selected identifiers without exact Game Session/World Management workload or tenant binding. The target internal-workload boundary and required negative proof are 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). +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). -Account's credential-granting gameplay gRPC methods now enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Other internal gRPC profile, presence, export, external-link, and account-ID verification handlers remain bearer-only and trust request-selected account/tenant IDs; direct calls bypass the current REST subject guards. The Account API/runtime owner retains method allowlisting and subject-binding convergence. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls now fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. +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. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. @@ -20,6 +20,27 @@ Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` SEC-04 does not move player session ownership into Logging & Admin. Game Session `/sessions*` lifecycle routes remain current owner-local hooks with direct owner edge exposure denied; the target external operator path forwards from Logging & Admin to Game Session after Account issues the authorization reference and the receiving Game Session redeems that same reference. That target lifecycle family, and other operator mutation families gated by action schemas, shared `mutationDigest/v1` vectors, and the authorization-reference flow, are not currently available to players or operators. +## Unit 1A Section-Exit Dispositions + +Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, not by two dry cycles. The current Account correction belongs to #2848; this table distinguishes contained live paths from substantial pre-v1 successors and proof gates. A successor or tracker owner is not evidence that exposed behavior is safe, and none of these rows makes the PR merge-ready. + +| Open item | Owner and concrete next slice | Exit or activation condition | +| --- | --- | --- | +| Direct Account gRPC runtime/profile/presence/export/link/verification reads and mutations | Account `AA-1.1`–`AA-1.3`, current #2848 correction | Exact workload and caller-subject guards, or explicit method denial before read/mutation; negative missing-peer/cross-account proof and composed certificate/CI proof. Game Session runtime read consumers remain unavailable until Unit 1B supplies the typed caller/target contract. | +| Generic payment, donation, refund and deferred virtual-currency RPCs | Account `AA-1.4`, current #2848 containment; later Account billing/economy successor | Unsupported methods deny before service/provider/balance work. Re-enable only for a supported product operation with exact workload authority, provider identity and negative mutation proof; a future economy requires its own accepted product contract. | +| Recovery-token reuse and JOIN abandoned `PENDING` intents | Account `AA-1.2`/`AA-1.3`, current #2848 correction | Atomic single-use reset/verification claims and bounded JOIN readback reconciler require executed PostgreSQL concurrency, lost-acknowledgement, no-duplicate and unresolved-outcome proof. Expiry or absent evidence never terminalizes a pending JOIN. | +| Verification and password-reset email-link reachability | Account `AA-1.3` delivery/confirmation successor and Platform edge handoff | Shipped verification links use GET while Account implements bearer-protected POST completion; shipped reset links point to a non-Account route. Token claims remain guarded, but email-based recovery/verification is not end-to-end proved. Before treating these flows as usable, provide an explicit web-client/edge confirmation handoff or matching handler, align public-route authentication without a state-changing GET shortcut, and execute link-to-completion proof; deployment-specific URL overrides alone need reachability proof. | +| Account deletion and retained financial/provider data | Account `AA-1.3` plus `DATA-01`, named pre-v1 pending-deletion/retention successor after this containment | Every current `DeleteAccount` entry denies before mutation. Enable only after the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, approved finite schedules, restore/replay and no-mutation/terminal proof exist; no partial synchronous substitute or invented TTL. | +| Portable account export and tenant-admin export | Account `AA-1.3`/ADR 0050 pre-v1 export successor | The legacy account/profile read is explicitly local and not a complete portable export; the account-targeted tenant export is disabled because it exposes global fields. Enable canonical asynchronous subject export and tenant-only admin export only with owner contributions, live authority, redaction, audit and retry proof. | +| Profile tenant qualification; membership lifecycle/generation, grants, roles, delegation and JOIN abuse limits | Account `AA-1.1`/`AA-1.2` authority successor, then Unit 1B consumer | Current profile route is self-bound and membership-checked; no tenant-qualified or delegated route activates until live generation/role/grant authority, caller binding and audit proof. Unit 1B must consume the exact snapshot and prove stale-generation/private-grant/character negatives before admission readiness. | +| Issued-token registry, deterministic replay, reset/logout revocation and authentication abuse controls | Account `AA-1.3` issuer/recovery successor; Game Session `AA-2.2`/`AA-3.3` consumer in Unit 1B | Current password/email-OTP login remains available but is not registry, replay, reset-revocation or graduated-throttle complete. Before claiming those properties, implement the single-record registry, atomic issuance/replay, revocation and Account-owned limiter/outage proof; Unit 1B handles logout/reconnect consumption. Do not infer safety from OTP challenge caps or a prior binding. | +| Login-factor changes, provider linking, TOTP, safety/appeal, account switching and signing-key rotation | Account `AA-1.3` security successors | Login-factor `PUT` and unverified linking are denied; other unimplemented features are not offered as supported authority. Each activates only after its Account-owned recent-reauth/provider/security-state or validator-convergence contract and negative proof, not because this corpus section was reviewed. | +| Hosting billing owner, provider lifecycle, current-row entitlement snapshot and strict new-binding rules | Account `AA-1.4`/`AA-1.5` billing-and-entitlement successor; Unit 1B consumer | Subscription creation is disabled and zero/ambiguous rows fail retryably. Select the initial billing-owner source/consent, then prove durable provider reconciliation, one current row and complete freshness/evidence before paid hosting or new commitments activate. Exact-binding last-known-good reconnect stays undecided; no fallback is authorized. | +| Official-hosted creator terms and future creator commerce | Account acceptance authority, Game Design mutation/readback gate, Platform `PO-2.1` edge; separate accepted product successor for commerce | Gateway exposes only safe GETs for now. Official hosted writes stay unavailable until current acceptance/changed-terms negative owner-side proof; creator purchases, tips, payouts and entitlement issuance remain unsupported pending separate product/authority acceptance. | +| Audit producer/receiver retention, migration, certificates and live proof | Account `AA-1.1`/`AA-1.2` producer, Logging receiver, #2847/#2848 readiness | Execute PostgreSQL receipt/projection and retained-row tests, verify exact workload certificate/render and direct text-to-Logging delivery, and define safe-watermark/hold/reference cleanup for committed payloads before long-running activation. Skipped local tests and green documentation checks do not close these gates. | + +Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Its first whole-unit review has not begun; the Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. + ## Packet 4 Status and Proof Gaps - `AA-2.1` / `AA-2.2` / `AA-3.3`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) remains the canonical target link for stable namespace-aware selection, admission, reconnect, and runtime replacement; [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) owns namespace-scoped controller identity, uniqueness, takeover, and binding-generation fencing. Existing account/session and realm-routing evidence remains partial and does not prove namespace-aware atomic takeover, replacement, or cleanup behavior. @@ -32,15 +53,15 @@ 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. The durable recovery/reconciliation seam for JOIN left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision and ADR 0025; do not mark ADR 0025 complete. PostgreSQL runtime proof 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.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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | -| `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 payment scaffolds still retain provider-mutating drift. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | +| `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.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, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains 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; 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, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. 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, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. 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 first-party post-logout replay cleanup are absent. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission and returns `JOIN_REQUIRED` without an Entity read otherwise; pre-membership world and realm discovery remains available. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, while the durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under ADR 0025; PostgreSQL runtime and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission and returns `JOIN_REQUIRED` without an Entity read otherwise; pre-membership world and realm discovery remains available. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, and a bounded Account-owned readback worker now revisits abandoned `PENDING` intents; PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. @@ -63,7 +84,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `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). -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 `PENDING`/unknown-database-outcome recovery seam 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). +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). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -145,7 +166,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 account-owned export/delete/recovery boundaries including active-subscription deletion guards. Explicit `JOIN`/`Join & Play`, transactional join authority, 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, 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. - **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. @@ -161,7 +182,7 @@ Account authority proof covers account-first tenantless bootstrap authentication - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. - Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. -- Account deletion currently removes payment and subscription rows after the active-billing precondition, while the canonical data-rights design retains billing/audit records for settlement and compliance. +- Every current Account deletion entry now denies before account and financial-row mutation. The full ADR 0043 pending-deletion and `DATA-01` retention workflow, with provider/transfer clearance and approved finite schedules, is the named pre-v1 Account successor required before deletion is enabled. - Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. - Automated signing-key rotation, overlap/pruning, and deployment-wide validator-convergence proof remain deferred even though JWKS publication and conditional file watching are live. - The continuity boundary intentionally excludes generalized chaos testing, arbitrary command replay, transport-byte replay, and reconstruction of queue/tick ownership if Game Logic later owns durable execution. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java index 49d9107845..dc11b8e3cd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java @@ -77,16 +77,18 @@ public ResponseEntity> exportTenantData( long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); SessionContext.requireAccountAccess(parsedTenantId, parsedAccountId); - TenantDataExportDto data = accountService.exportTenantData(parsedTenantId, parsedAccountId); - return ResponseEntity.ok(ApiResponse.success(data)); + throw new org.springframework.web.server.ResponseStatusException( + HttpStatus.NOT_IMPLEMENTED, + "Tenant-admin export is unavailable until the tenant-wide export contract is implemented"); } @DeleteMapping("/{accountId}") public ResponseEntity> deleteAccount(@PathVariable String accountId) { long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); - accountService.deleteAccount(parsedAccountId); - return ResponseEntity.ok(ApiResponse.success(null)); + throw new net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException( + "ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", + "Account deletion is unavailable until its provider reconciliation and data retention workflow is implemented"); } private void requireCurrentAccountOrGlobalPrivilegedRole(Long accountId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index 2829a20873..655c6199b3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -7,6 +7,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.util.List; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; @@ -58,6 +59,25 @@ public List pending(int limit) { .fetch(this::toEnvelope); } + /** Locks one exact Account JOIN transition envelope for transaction-local reconciliation. */ + public Optional findJoinEnvelopeForUpdate( + UUID auditEventId, long tenantId) { + if (auditEventId == null || tenantId <= 0) { + throw new IllegalArgumentException("JOIN audit identity and tenant are required"); + } + return dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where( + ACCOUNT_AUDIT_OUTBOX + .AUDIT_EVENT_ID + .eq(auditEventId) + .and(ACCOUNT_AUDIT_OUTBOX.SCOPE.eq("tenant")) + .and(ACCOUNT_AUDIT_OUTBOX.TENANT_ID.eq(tenantId)) + .and(ACCOUNT_AUDIT_OUTBOX.PRODUCER_SERVICE.eq("account-service")) + .and(ACCOUNT_AUDIT_OUTBOX.EVENT_TYPE.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"))) + .forUpdate() + .fetchOptional(this::toEnvelope); + } + public void markDelivered( UUID auditEventId, String receiptId, String logEventId, boolean minimized) { var update = diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java index 79de6c47e6..ea7e379ab8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -4,6 +4,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import org.jooq.DSLContext; @@ -54,6 +55,38 @@ public Optional find(String connectScopeId) { .fetchOptional(record -> toScope(record, connectScopeId)); } + /** + * Reads retained target evidence by its one-way token hash. This record cannot be used as a + * connect-scope bearer and deliberately does not reconstruct or expose the plaintext token. + */ + public Optional findEvidenceByTokenHash(String scopeTokenHash) { + if (scopeTokenHash == null || scopeTokenHash.isBlank()) { + throw new IllegalArgumentException("JOIN scope token hash is required"); + } + return dsl.selectFrom(ACCOUNT_CONNECT_SCOPE_RECORDS) + .where(ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH.eq(scopeTokenHash)) + .fetchOptional(AccountConnectScopeRepository::toEvidence); + } + + private static ConnectScopeEvidence toEvidence(Record record) { + return new ConnectScopeEvidence( + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.ACCOUNT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TENANT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.WORLD_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_NAMESPACE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_SCOPE), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.GAME_INSTANCE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CATALOG_REVISION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.POINTER_VERSION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.EVALUATED_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CONNECT_SCOPE_EXPIRES_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.SNAPSHOT_DIGEST)); + } + private VerifiedJoinScope toScope(Record record, String connectScopeId) { if (!"PUBLIC_PRODUCTION".equals(record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS))) { throw new IllegalStateException("JOIN scope is not public production"); @@ -79,4 +112,21 @@ private VerifiedJoinScope toScope(Record record, String connectScopeId) { } return scope; } + + public record ConnectScopeEvidence( + String scopeTokenHash, + long accountId, + String targetClass, + long tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion, + String evaluatedAt, + String connectScopeExpiresAt, + String snapshotDigest) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index a43a4b536b..c8eb47ab96 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -2,8 +2,12 @@ import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_JOIN_OPERATIONS; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.List; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; @@ -16,6 +20,8 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountJoinOperationRepository { + private static final int MAX_RECONCILIATION_PAGE_SIZE = 100; + private final DSLContext dsl; public AccountJoinOperationRepository(DSLContext dsl) { @@ -47,6 +53,84 @@ public Optional findForUpdate(String requestId) { .fetchOptional(AccountJoinOperationRepository::toJoinOperation); } + /** Returns a stable, bounded page of due PENDING operations below the caller's attempt cap. */ + public List findDuePendingReconciliation(Instant now, int limit, int maxAttempts) { + if (now == null) { + throw new IllegalArgumentException("JOIN reconciliation time is required"); + } + if (limit < 1 || limit > MAX_RECONCILIATION_PAGE_SIZE) { + throw new IllegalArgumentException("JOIN reconciliation page size must be between 1 and 100"); + } + if (maxAttempts < 1) { + throw new IllegalArgumentException("JOIN reconciliation attempt limit must be positive"); + } + return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) + .where( + ACCOUNT_JOIN_OPERATIONS + .STATUS + .eq("PENDING") + .and(ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.lt(maxAttempts)) + .and( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.le( + toLocalDateTime(now)))) + .orderBy( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.asc(), + ACCOUNT_JOIN_OPERATIONS.CREATED_AT.asc(), + ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.asc()) + .limit(limit) + .fetch(AccountJoinOperationRepository::toJoinOperation); + } + + /** + * Records one reconciliation attempt only if the pending row still has the observed attempt count + * and remains below the caller's cap. A false result means another worker changed it. + */ + public boolean recordReconciliationAttempt( + String requestId, + int expectedAttemptCount, + int maxAttempts, + Instant attemptedAt, + String reason, + Instant nextAttemptAt) { + if (requestId == null || requestId.isBlank()) { + throw new IllegalArgumentException("JOIN request ID is required"); + } + if (expectedAttemptCount < 0 || maxAttempts < 1 || expectedAttemptCount >= maxAttempts) { + throw new IllegalArgumentException("JOIN reconciliation attempt count is outside its limit"); + } + if (attemptedAt == null || nextAttemptAt == null || nextAttemptAt.isBefore(attemptedAt)) { + throw new IllegalArgumentException("JOIN reconciliation attempt times are invalid"); + } + if (reason == null || reason.isBlank() || reason.trim().length() > 128) { + throw new IllegalArgumentException( + "JOIN reconciliation reason must contain 1 to 128 characters"); + } + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set( + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT, + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.plus(1)) + .set( + ACCOUNT_JOIN_OPERATIONS.LAST_RECONCILIATION_ATTEMPT_AT, + toLocalDateTime(attemptedAt)) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_RECONCILIATION_ATTEMPT_REASON, reason.trim()) + .set( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT, + toLocalDateTime(nextAttemptAt)) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, toLocalDateTime(attemptedAt)) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING")) + .and( + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.eq( + expectedAttemptCount)) + .and(ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.lt(maxAttempts))) + .execute(); + return updated == 1; + } + public boolean hasRetainedOperation(long accountId) { return dsl.fetchExists( ACCOUNT_JOIN_OPERATIONS, ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID.eq(accountId)); @@ -209,9 +293,17 @@ public void recordCallerBoundAuthorityInvalidation(String requestId) { } public record JoinOperation( + String requestId, long accountId, long tenantId, UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion, String callerBinding, String scopeTokenHash, String connectScopeDigest, @@ -228,14 +320,26 @@ public record JoinOperation( int intentDigestVersion, String intentDigest, String lastAttemptFailureCode, - String lastAttemptAuthorityAvailability) {} + String lastAttemptAuthorityAvailability, + int reconciliationAttemptCount, + Instant lastReconciliationAttemptAt, + String lastReconciliationAttemptReason, + Instant nextReconciliationAttemptAt) {} private static JoinOperation toJoinOperation( net.firedevops.firemud.accountservice.jooq.tables.records.AccountJoinOperationsRecord row) { return new JoinOperation( + row.getRequestId(), row.getAccountId(), row.getTenantId(), row.getRealmId(), + row.getWorldSlug(), + row.getRealmSlug(), + row.getPlayableStateNamespaceId(), + row.getPlayableStateScope(), + row.getGameInstanceId(), + row.getCatalogRevision(), + row.getPointerVersion(), row.getVerifiedCallerBinding(), row.getScopeTokenHash(), row.getConnectScopeDigest(), @@ -252,6 +356,12 @@ private static JoinOperation toJoinOperation( row.getIntentDigestVersion(), row.getIntentDigest(), row.getLastAttemptFailureCode(), - row.getLastAttemptAuthorityAvailability()); + row.getLastAttemptAuthorityAvailability(), + row.getReconciliationAttemptCount(), + row.getLastReconciliationAttemptAt() == null + ? null + : toInstant(row.getLastReconciliationAttemptAt()), + row.getLastReconciliationAttemptReason(), + toInstant(row.getNextReconciliationAttemptAt())); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 1a4b5e3e10..758d89b331 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -34,6 +34,38 @@ public Optional findByAccountIdAndTenantId( .fetchOne(this::toEntity)); } + /** Reads and locks the exact membership row for a JOIN reconciliation proof. */ + public Optional findJoinProofForUpdate(long accountId, long tenantId) { + return dsl.select( + ACCOUNT_TENANT_MEMBERSHIP.ID, + ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID, + ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID, + ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, + ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE) + .from(ACCOUNT_TENANT_MEMBERSHIP) + .where( + ACCOUNT_TENANT_MEMBERSHIP + .ACCOUNT_ID + .eq(accountId) + .and(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID.eq(tenantId))) + .forUpdate() + .fetchOptional( + record -> + new JoinMembershipProof( + record.get(ACCOUNT_TENANT_MEMBERSHIP.ID), + record.get(ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID), + record.get(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID), + Boolean.TRUE.equals( + record.get(ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED)), + record.get(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE), + record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION), + record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION), + record.get(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE))); + } + public boolean existsByAccountIdAndTenantId(Long accountId, Long tenantId) { return dsl.fetchExists( ACCOUNT_TENANT_MEMBERSHIP, @@ -169,4 +201,14 @@ private AccountTenantMembership toEntity(Record record) { membership.setAuthorityProvenance(record.get(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE)); return membership; } + + public record JoinMembershipProof( + long membershipId, + long accountId, + long tenantId, + boolean gameplayAdmissionAllowed, + String lifecycleState, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java index acb2c576fb..9657039da8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java @@ -61,6 +61,22 @@ public void delete(EmailVerificationToken entity) { } } + /** Atomically consumes a still-valid token so only one transaction can claim it. */ + public boolean consumeIfUnexpired(EmailVerificationToken token, LocalDateTime capturedNow) { + if (token == null || token.getId() == null) { + return false; + } + return dsl.deleteFrom(EMAIL_VERIFICATION_TOKEN) + .where( + EMAIL_VERIFICATION_TOKEN + .ID + .eq(token.getId()) + .and(EMAIL_VERIFICATION_TOKEN.TOKEN.eq(token.getToken())) + .and(EMAIL_VERIFICATION_TOKEN.EXPIRES_AT.ge(capturedNow))) + .execute() + == 1; + } + public void deleteByAccountId(Long accountId) { dsl.deleteFrom(EMAIL_VERIFICATION_TOKEN) .where(EMAIL_VERIFICATION_TOKEN.ACCOUNT_ID.eq(accountId)) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java index 5c509ff3eb..38ede92a17 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java @@ -61,6 +61,22 @@ public void delete(PasswordResetToken entity) { } } + /** Atomically consumes a still-valid token so only one transaction can claim it. */ + public boolean consumeIfUnexpired(PasswordResetToken token, LocalDateTime capturedNow) { + if (token == null || token.getId() == null) { + return false; + } + return dsl.deleteFrom(PASSWORD_RESET_TOKEN) + .where( + PASSWORD_RESET_TOKEN + .ID + .eq(token.getId()) + .and(PASSWORD_RESET_TOKEN.TOKEN.eq(token.getToken())) + .and(PASSWORD_RESET_TOKEN.EXPIRES_AT.ge(capturedNow))) + .execute() + == 1; + } + public void deleteByAccountId(Long accountId) { dsl.deleteFrom(PASSWORD_RESET_TOKEN) .where(PASSWORD_RESET_TOKEN.ACCOUNT_ID.eq(accountId)) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationJob.java new file mode 100644 index 0000000000..0db99576f5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationJob.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Periodically invokes Account's bounded, readback-only JOIN reconciler. */ +@Component +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Invalid scheduling configuration must fail startup.") +public class AccountJoinReconciliationJob { + private final AccountJoinReconciliationService reconciliationService; + + public AccountJoinReconciliationJob( + AccountJoinReconciliationService reconciliationService, + @Value("${firemud.account.join-reconciliation.interval-ms:30000}") long intervalMillis) { + if (intervalMillis < 1) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.interval-ms must be positive"); + } + this.reconciliationService = reconciliationService; + } + + @Scheduled( + fixedDelayString = "${firemud.account.join-reconciliation.interval-ms:30000}", + timeUnit = TimeUnit.MILLISECONDS) + public void reconcilePendingJoinOperations() { + reconciliationService.reconcileDueOperations(Instant.now()); + } +} 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 new file mode 100644 index 0000000000..19d572f060 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java @@ -0,0 +1,462 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; +import java.nio.charset.StandardCharsets; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +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.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Readback-only recovery for Account JOIN operations left PENDING after an uncertain commit. */ +@Service +@SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Injected Spring collaborators are internal; invalid reconciliation settings must fail startup.") +public class AccountJoinReconciliationService { + private static final Logger logger = + LoggerFactory.getLogger(AccountJoinReconciliationService.class); + private static final int MAX_BATCH_SIZE = 100; + private static final Pattern SHA256_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set JOIN_AUDIT_FIELDS = + Set.of("accountId", "tenantId", "worldSlug", "realmSlug", "membershipVersion", "requestId"); + private static final JsonMapper AUDIT_JSON = + JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountConnectScopeRepository connectScopeRepository; + private final AccountTenantMembershipRepository membershipRepository; + private final AccountAuditOutboxRepository auditOutboxRepository; + private final TransactionTemplate joinTransactionTemplate; + private final int batchSize; + private final int maxAttempts; + private final long backoffMillis; + private final Counter committed; + private final Counter unresolved; + private final Counter failures; + private final Counter maxAttemptsReached; + + public AccountJoinReconciliationService( + AccountJoinOperationRepository joinOperationRepository, + AccountConnectScopeRepository connectScopeRepository, + AccountTenantMembershipRepository membershipRepository, + AccountAuditOutboxRepository auditOutboxRepository, + MeterRegistry meterRegistry, + PlatformTransactionManager transactionManager, + @Value("${firemud.account.join-reconciliation.batch-size:50}") int batchSize, + @Value("${firemud.account.join-reconciliation.max-attempts:12}") int maxAttempts, + @Value("${firemud.account.join-reconciliation.backoff-ms:30000}") long backoffMillis) { + if (batchSize < 1 || batchSize > MAX_BATCH_SIZE) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.batch-size must be between 1 and 100"); + } + if (maxAttempts < 1) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.max-attempts must be positive"); + } + if (backoffMillis < 1) { + throw new IllegalArgumentException( + "firemud.account.join-reconciliation.backoff-ms must be positive"); + } + this.joinOperationRepository = joinOperationRepository; + this.connectScopeRepository = connectScopeRepository; + this.membershipRepository = membershipRepository; + this.auditOutboxRepository = auditOutboxRepository; + this.batchSize = batchSize; + this.maxAttempts = maxAttempts; + this.backoffMillis = backoffMillis; + this.joinTransactionTemplate = new TransactionTemplate(transactionManager); + this.joinTransactionTemplate.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.committed = counter(meterRegistry, "committed"); + this.unresolved = counter(meterRegistry, "unresolved"); + this.failures = counter(meterRegistry, "failure"); + this.maxAttemptsReached = counter(meterRegistry, "max_attempts_reached"); + } + + /** Processes one bounded due page using the caller's captured time for deterministic rechecks. */ + public void reconcileDueOperations(Instant now) { + Objects.requireNonNull(now, "JOIN reconciliation time is required"); + final List dueOperations; + try { + dueOperations = + joinOperationRepository.findDuePendingReconciliation(now, batchSize, maxAttempts); + } catch (RuntimeException ex) { + failures.increment(); + logger.warn( + "JOIN reconciliation could not list due operations ({})", ex.getClass().getSimpleName()); + return; + } + + for (JoinOperation candidate : dueOperations) { + reconcileOne(candidate, now); + } + } + + /** Convenience entry point for direct operational invocation. */ + public void reconcileDueOperations() { + reconcileDueOperations(Instant.now()); + } + + private void reconcileOne(JoinOperation candidate, Instant now) { + try { + ReconciliationResult result = + joinTransactionTemplate.execute(transactionStatus -> reconcileLocked(candidate, now)); + if (result == null || result == ReconciliationResult.SKIPPED) { + return; + } + if (result == ReconciliationResult.COMMITTED) { + committed.increment(); + } else if (result == ReconciliationResult.ATTEMPT_RECORDED) { + unresolved.increment(); + } else if (result == ReconciliationResult.MAX_ATTEMPTS_REACHED) { + unresolved.increment(); + maxAttemptsReached.increment(); + } + } catch (RuntimeException ex) { + failures.increment(); + logger.warn( + "JOIN reconciliation readback failed for request {} ({})", + candidate.requestId(), + ex.getClass().getSimpleName()); + recordUnavailableAttempt(candidate, now); + } + } + + private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant now) { + // Keep the same lock order as the caller: account row, then durable operation row. + joinOperationRepository.lockAccount(candidate.accountId()); + JoinOperation operation = + joinOperationRepository.findForUpdate(candidate.requestId()).orElse(null); + if (operation == null + || operation.accountId() != candidate.accountId() + || !"PENDING".equals(operation.status()) + || operation.reconciliationAttemptCount() >= maxAttempts + || operation.nextReconciliationAttemptAt() == null + || operation.nextReconciliationAttemptAt().isAfter(now)) { + return ReconciliationResult.SKIPPED; + } + + String unresolvedReason = validateOperationAndPolicy(operation); + if (unresolvedReason == null) { + unresolvedReason = validateRetainedScope(operation); + } + + JoinMembershipProof membership = null; + AccountAuditEnvelope envelope = null; + if (unresolvedReason == null) { + membership = + membershipRepository + .findJoinProofForUpdate(operation.accountId(), operation.tenantId()) + .orElse(null); + if (membership == null) { + unresolvedReason = "MEMBERSHIP_EVIDENCE_ABSENT"; + } else if (!membershipMatches(operation, membership)) { + unresolvedReason = "MEMBERSHIP_EVIDENCE_MISMATCH"; + } + } + + 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"; + } + } + + if (unresolvedReason != null) { + return recordUnresolvedAttempt(operation, now, unresolvedReason); + } + + joinOperationRepository.finish( + operation.requestId(), + "COMMITTED", + "JOINED", + membership.membershipId(), + membership.membershipVersion(), + membership.membershipAuthorityGeneration()); + return ReconciliationResult.COMMITTED; + } + + private String validateOperationAndPolicy(JoinOperation operation) { + if (operation.requestId() == null + || operation.requestId().isBlank() + || operation.accountId() <= 0 + || operation.tenantId() <= 0 + || operation.realmId() == null + || !hasText(operation.worldSlug()) + || !hasText(operation.realmSlug()) + || !hasText(operation.playableStateNamespaceId()) + || !hasText(operation.playableStateScope()) + || operation.gameInstanceId() <= 0 + || operation.catalogRevision() <= 0 + || operation.pointerVersion() <= 0 + || operation.callerBinding() == null + || operation.callerBinding().isBlank() + || operation.intentDigestVersion() != 1 + || !isSha256(operation.intentDigest()) + || operation.requestDigestVersion() == null + || operation.requestDigestVersion() != 1 + || !isSha256(operation.requestDigest()) + || !"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) + || !Boolean.TRUE.equals(operation.allowPublicJoin()) + || operation.entitlementVersion() == null + || operation.entitlementVersion() <= 0 + || operation.outcome() != null + || operation.membershipId() != null + || operation.membershipVersion() != null + || operation.membershipAuthorityGeneration() != null) { + return "JOIN_OPERATION_POLICY_UNPROVEN"; + } + return null; + } + + private String validateRetainedScope(JoinOperation operation) { + if (!isSha256(operation.scopeTokenHash()) || !isSha256(operation.connectScopeDigest())) { + return "JOIN_SCOPE_DIGEST_UNCLEAR"; + } + var evidence = + connectScopeRepository.findEvidenceByTokenHash(operation.scopeTokenHash()).orElse(null); + if (evidence == null) { + return "JOIN_SCOPE_EVIDENCE_ABSENT"; + } + if (!scopeMatches(operation, evidence)) { + return "JOIN_SCOPE_EVIDENCE_MISMATCH"; + } + if (evidence.evaluatedAt() == null || evidence.connectScopeExpiresAt() == null) { + return "JOIN_SCOPE_TIME_UNCLEAR"; + } + try { + Instant evaluatedAt = Instant.parse(evidence.evaluatedAt()); + Instant expiresAt = Instant.parse(evidence.connectScopeExpiresAt()); + // Expiry blocks new caller use; it cannot erase positive persisted commit evidence. + if (!expiresAt.isAfter(evaluatedAt)) { + return "JOIN_SCOPE_TIME_UNCLEAR"; + } + } catch (DateTimeException ex) { + return "JOIN_SCOPE_TIME_UNCLEAR"; + } + return null; + } + + private static boolean scopeMatches( + JoinOperation operation, AccountConnectScopeRepository.ConnectScopeEvidence evidence) { + return evidence.accountId() == operation.accountId() + && "PUBLIC_PRODUCTION".equals(evidence.targetClass()) + && evidence.tenantId() == operation.tenantId() + && Objects.equals(evidence.realmId(), operation.realmId()) + && Objects.equals(evidence.worldSlug(), operation.worldSlug()) + && Objects.equals(evidence.realmSlug(), operation.realmSlug()) + && Objects.equals(evidence.playableStateNamespaceId(), operation.playableStateNamespaceId()) + && Objects.equals(evidence.playableStateScope(), operation.playableStateScope()) + && evidence.gameInstanceId() == operation.gameInstanceId() + && evidence.catalogRevision() == operation.catalogRevision() + && evidence.pointerVersion() == operation.pointerVersion() + && Objects.equals(evidence.scopeTokenHash(), operation.scopeTokenHash()) + && Objects.equals(evidence.snapshotDigest(), operation.connectScopeDigest()) + && isSha256(evidence.snapshotDigest()); + } + + private static boolean membershipMatches( + JoinOperation operation, JoinMembershipProof membership) { + return membership.membershipId() > 0 + && membership.accountId() == operation.accountId() + && membership.tenantId() == operation.tenantId() + && membership.gameplayAdmissionAllowed() + && "ACTIVE".equals(membership.lifecycleState()) + && "EXPLICIT_JOIN".equals(membership.authorityProvenance()) + && membership.membershipVersion() > 0 + && membership.membershipAuthorityGeneration() > 0; + } + + private static boolean auditEnvelopeMatches( + JoinOperation operation, JoinMembershipProof membership, AccountAuditEnvelope envelope) { + if (!joinAuditEventId(operation.requestId()).equals(envelope.auditEventId()) + || !"tenant".equals(envelope.scope()) + || !Objects.equals(envelope.tenantId(), operation.tenantId()) + || !"account-service".equals(envelope.producerService()) + || !"ACCOUNT_JOINED_PUBLIC_PRODUCTION".equals(envelope.eventType()) + || envelope.occurredAt() == null + || envelope.schemaVersion() != 1 + || envelope.payloadDigestVersion() != 1 + || !isSha256(envelope.payloadDigest()) + || envelope.payload() == null + || !envelope.payloadDigest().equals(AccountAuditDigest.ofPayload(envelope.payload()))) { + return false; + } + + JoinAuditPayload payload = parseJoinAuditPayload(envelope.payload()); + return payload != null + && payload.accountId() == operation.accountId() + && payload.tenantId() == operation.tenantId() + && Objects.equals(payload.worldSlug(), operation.worldSlug()) + && Objects.equals(payload.realmSlug(), operation.realmSlug()) + && payload.membershipVersion() == membership.membershipVersion() + && Objects.equals(payload.requestId(), operation.requestId()); + } + + private static JoinAuditPayload parseJoinAuditPayload(String json) { + try { + JsonNode root = AUDIT_JSON.readTree(json); + if (root == null || !root.isObject()) { + return null; + } + Set names = new HashSet<>(); + root.properties().forEach(entry -> names.add(entry.getKey())); + if (!JOIN_AUDIT_FIELDS.equals(names)) { + return null; + } + JsonNode accountId = root.get("accountId"); + JsonNode tenantId = root.get("tenantId"); + JsonNode worldSlug = root.get("worldSlug"); + JsonNode realmSlug = root.get("realmSlug"); + JsonNode membershipVersion = root.get("membershipVersion"); + JsonNode requestId = root.get("requestId"); + if (!isLong(accountId) + || !isLong(tenantId) + || !worldSlug.isTextual() + || !realmSlug.isTextual() + || !isLong(membershipVersion) + || !requestId.isTextual()) { + return null; + } + return new JoinAuditPayload( + accountId.longValue(), + tenantId.longValue(), + worldSlug.textValue(), + realmSlug.textValue(), + membershipVersion.longValue(), + requestId.textValue()); + } catch (RuntimeException ex) { + return null; + } + } + + private static boolean isLong(JsonNode node) { + return node != null && node.isIntegralNumber() && node.canConvertToLong(); + } + + private ReconciliationResult recordUnresolvedAttempt( + JoinOperation operation, Instant now, String reason) { + boolean recorded = + joinOperationRepository.recordReconciliationAttempt( + operation.requestId(), + operation.reconciliationAttemptCount(), + maxAttempts, + now, + reason, + nextAttemptAt(now)); + if (!recorded) { + return ReconciliationResult.SKIPPED; + } + if (operation.reconciliationAttemptCount() + 1 >= maxAttempts) { + logger.warn( + "JOIN reconciliation reached its attempt limit for request {}; it remains PENDING and caller-retryable (reason {})", + operation.requestId(), + reason); + return ReconciliationResult.MAX_ATTEMPTS_REACHED; + } + logger.debug( + "JOIN reconciliation remains pending for request {} (reason {})", + operation.requestId(), + reason); + return ReconciliationResult.ATTEMPT_RECORDED; + } + + private void recordUnavailableAttempt(JoinOperation candidate, Instant now) { + try { + joinTransactionTemplate.execute( + transactionStatus -> { + joinOperationRepository.lockAccount(candidate.accountId()); + JoinOperation operation = + joinOperationRepository.findForUpdate(candidate.requestId()).orElse(null); + if (operation == null + || operation.accountId() != candidate.accountId() + || !"PENDING".equals(operation.status()) + || operation.reconciliationAttemptCount() >= maxAttempts + || operation.nextReconciliationAttemptAt() == null + || operation.nextReconciliationAttemptAt().isAfter(now)) { + return ReconciliationResult.SKIPPED; + } + return recordUnresolvedAttempt(operation, now, "JOIN_READBACK_UNAVAILABLE"); + }); + } catch (RuntimeException ex) { + logger.warn( + "JOIN reconciliation could not persist a retry diagnostic for request {} ({})", + candidate.requestId(), + ex.getClass().getSimpleName()); + } + } + + private Instant nextAttemptAt(Instant attemptedAt) { + try { + return attemptedAt.plusMillis(backoffMillis); + } catch (DateTimeException | ArithmeticException ex) { + throw new IllegalStateException("JOIN reconciliation backoff is outside timestamp range", ex); + } + } + + private static UUID joinAuditEventId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static boolean isSha256(String value) { + return value != null && SHA256_PATTERN.matcher(value).matches(); + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + + private static Counter counter(MeterRegistry meterRegistry, String result) { + return Counter.builder("account.join.reconciliation.operations") + .description("Account JOIN reconciliation operation outcomes") + .tag("result", result) + .register(meterRegistry); + } + + private enum ReconciliationResult { + SKIPPED, + COMMITTED, + ATTEMPT_RECORDED, + MAX_ATTEMPTS_REACHED + } + + private record JoinAuditPayload( + long accountId, + long tenantId, + String worldSlug, + String realmSlug, + long membershipVersion, + String requestId) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 41d91d554e..343efe3588 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -45,13 +45,13 @@ import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.PingService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; -import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.common.security.SessionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -194,6 +194,33 @@ private void requireGameSessionPeer() { } } + private void requireSocialGroupsPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || workloadNamespace == null + || workloadNamespace.isBlank() + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/social-groups-service")) { + throw new AdminAuthorizationException("Verified Social Groups workload identity is required"); + } + } + + private void requireCallerAccountSubject(long accountId) { + if (SessionContext.isInternalService()) { + throw new AdminAuthorizationException("Authenticated account subject is required"); + } + + Long callerAccountId; + try { + callerAccountId = SessionContext.currentAccountIdOrNull(); + } catch (IllegalArgumentException ex) { + throw new AdminAuthorizationException("Authenticated account subject is required"); + } + if (callerAccountId == null || callerAccountId.longValue() != accountId) { + throw new AdminAuthorizationException("Profile access is restricted to the caller account"); + } + } + private DirectTextCallerContext directTextCaller( net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { return new DirectTextCallerContext( @@ -383,40 +410,26 @@ public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getTenantMembershipForRuntime( - requirePositiveRequestId(request.getAccountId(), "accountId"), - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getRequestId()); - GetTenantMembershipForRuntimeResponse response = - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(String.valueOf(dto.accountId())) - .setTenantId(String.valueOf(dto.tenantId())) - .setMembershipExists(dto.membershipExists()) - .setGameplayAdmissionAllowed(dto.gameplayAdmissionAllowed()) - .setMembershipVersion(dto.membershipVersion()) - .setMembershipLifecycleState(dto.membershipLifecycleState()) - .setMembershipAuthorityGeneration(dto.membershipAuthorityGeneration()) - .setEvaluatedAt(dto.evaluatedAt()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - GetTenantMembershipForRuntimeResponse response = + requireGameSessionPeer(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( GetTenantMembershipForRuntimeResponse.newBuilder() .setError( - appError("GetTenantMembershipForRuntime", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetTenantMembershipForRuntimeResponse response = - GetTenantMembershipForRuntimeResponse.newBuilder() - .setError(appError("GetTenantMembershipForRuntime", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); + appError("GetTenantMembershipForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); responseObserver.onCompleted(); + return; } + + responseObserver.onNext( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + appError( + "GetTenantMembershipForRuntime", + "FAILED_PRECONDITION", + "This request cannot establish an authorized player and target binding")) + .build()); + responseObserver.onCompleted(); } @Override @@ -425,41 +438,26 @@ public void getRealmAccessGrantForRuntime( GetRealmAccessGrantForRuntimeRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getRealmAccessGrantForRuntime( - requirePositiveRequestId(request.getAccountId(), "accountId"), - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getWorldSlug(), - request.getRealmSlug(), - request.getRequestId()); - GetRealmAccessGrantForRuntimeResponse response = - GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId(String.valueOf(dto.accountId())) - .setTenantId(String.valueOf(dto.tenantId())) - .setWorldSlug(dto.worldSlug()) - .setRealmSlug(dto.realmSlug()) - .setGranted(dto.granted()) - .setGrantVersion(dto.grantVersion()) - .setEvaluatedAt(dto.evaluatedAt()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - GetRealmAccessGrantForRuntimeResponse response = + requireGameSessionPeer(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( GetRealmAccessGrantForRuntimeResponse.newBuilder() .setError( - appError("GetRealmAccessGrantForRuntime", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetRealmAccessGrantForRuntimeResponse response = - GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setError(appError("GetRealmAccessGrantForRuntime", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); + appError("GetRealmAccessGrantForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); responseObserver.onCompleted(); + return; } + + responseObserver.onNext( + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setError( + appError( + "GetRealmAccessGrantForRuntime", + "FAILED_PRECONDITION", + "This request cannot establish an authorized player and target binding")) + .build()); + responseObserver.onCompleted(); } @Override @@ -468,43 +466,26 @@ public void getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getTenantEntitlementsForRuntime( - requirePositiveRequestId(request.getTenantId(), "tenantId"), request.getRequestId()); - GetTenantEntitlementsForRuntimeResponse response = - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId(String.valueOf(dto.tenantId())) - .setGameplayAvailable(dto.gameplayAvailable()) - .setAllowPublicJoin(dto.allowPublicJoin()) - .setEntitlementVersion(dto.entitlementVersion()) - .setTenantBillingSequence(dto.tenantBillingSequence()) - .setEvaluatedAt(dto.evaluatedAt()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - GetTenantEntitlementsForRuntimeResponse response = + requireGameSessionPeer(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setError( - appError("GetTenantEntitlementsForRuntime", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AuthenticationException ex) { - GetTenantEntitlementsForRuntimeResponse response = - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError(appError("GetTenantEntitlementsForRuntime", ex.getCode(), ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetTenantEntitlementsForRuntimeResponse response = - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError(appError("GetTenantEntitlementsForRuntime", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); + appError("GetTenantEntitlementsForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); responseObserver.onCompleted(); + return; } + + responseObserver.onNext( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + appError( + "GetTenantEntitlementsForRuntime", + "FAILED_PRECONDITION", + "This request cannot establish an authorized caller and target binding")) + .build()); + responseObserver.onCompleted(); } @Override @@ -512,16 +493,23 @@ public void getTenantEntitlementsForRuntime( public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getProfile( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId")); + requireSocialGroupsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + long accountId = requirePositiveRequestId(request.getAccountId(), "accountId"); + requireCallerAccountSubject(accountId); + var dto = accountService.getProfile(tenantId, accountId); GetProfileResponse response = GetProfileResponse.newBuilder() .setProfileJson(JsonMapper.builder().build().writeValueAsString(dto)) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + GetProfileResponse.newBuilder() + .setError(appError("GetProfile", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetProfileResponse response = GetProfileResponse.newBuilder() @@ -546,6 +534,7 @@ public void listPresenceVisibilityPolicies( StreamObserver responseObserver) { try { + requireSocialGroupsPeer(); long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); if (request.getAccountIdsCount() > MAX_ACCOUNT_IDS_PER_REQUEST) { throw new InvalidRequestException( @@ -569,6 +558,13 @@ public void listPresenceVisibilityPolicies( .build())); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() + .setError( + appError("ListPresenceVisibilityPolicies", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { responseObserver.onNext( net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() @@ -596,14 +592,18 @@ public void listPresenceVisibilityPolicies( public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { + requireSocialGroupsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + long accountId = requirePositiveRequestId(request.getAccountId(), "accountId"); + requireCallerAccountSubject(accountId); JsonNode node = JsonMapper.builder().build().readTree(request.getProfileJson()); String displayName = node.path("displayName").asText(null); String bio = node.path("bio").asText(null); String presenceVisibilityPolicy = node.path("presenceVisibilityPolicy").asText(null); accountService.updateProfile( new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId"), + tenantId, + accountId, displayName, bio, ProfilePresenceVisibilityPolicy.valueOf( @@ -613,6 +613,14 @@ public void updateProfile( UpdateProfileResponse response = UpdateProfileResponse.newBuilder().setSuccess(true).build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + UpdateProfileResponse response = + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError(appError("UpdateProfile", "PERMISSION_DENIED", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { UpdateProfileResponse response = UpdateProfileResponse.newBuilder() @@ -636,69 +644,30 @@ public void updateProfile( @Timed(value = "accountGrpc.exportAccount") public void exportAccount( ExportAccountRequest request, StreamObserver responseObserver) { - try { - var data = - accountService.exportAccountData( - requirePositiveRequestId(request.getAccountId(), "accountId")); - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) - .setProfilesJson(JsonMapper.builder().build().writeValueAsString(data.profiles())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(appError("ExportAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(appError("ExportAccount", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + ExportAccountResponse.newBuilder() + .setError( + appError( + "ExportAccount", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @Timed(value = "accountGrpc.exportTenantData") public void exportTenantData( ExportTenantDataRequest request, StreamObserver responseObserver) { - try { - var data = - accountService.exportTenantData( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId")); - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setTenantId(String.valueOf(data.tenantId())) - .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) - .setProfileJson( - data.profile() != null - ? JsonMapper.builder().build().writeValueAsString(data.profile()) - : "") - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(appError("ExportTenantData", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(appError("ExportTenantData", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + ExportTenantDataResponse.newBuilder() + .setError( + appError( + "ExportTenantData", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -707,9 +676,16 @@ public void deleteAccount( DeleteAccountRequest request, StreamObserver responseObserver) { try { AdminRoleGuard.requireAdminRole(); - accountService.deleteAccount(requirePositiveRequestId(request.getAccountId(), "accountId")); - DeleteAccountResponse response = DeleteAccountResponse.newBuilder().setSuccess(true).build(); - responseObserver.onNext(response); + requirePositiveRequestId(request.getAccountId(), "accountId"); + responseObserver.onNext( + DeleteAccountResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "DeleteAccount", + "ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", + "Account deletion is unavailable until its provider reconciliation and data retention workflow is implemented")) + .build()); responseObserver.onCompleted(); } catch (InvalidRequestException ex) { DeleteAccountResponse response = @@ -727,14 +703,6 @@ public void deleteAccount( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); - } catch (AccountLifecycleException ex) { - DeleteAccountResponse response = - DeleteAccountResponse.newBuilder() - .setSuccess(false) - .setError(appError("DeleteAccount", ex.getCode(), ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); } catch (Exception ex) { DeleteAccountResponse response = DeleteAccountResponse.newBuilder() @@ -803,36 +771,16 @@ public void linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest request, StreamObserver responseObserver) { - try { - accountService.linkExternalAccount( - new net.firedevops.firemud.accountservice.dto.LinkExternalAccountRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId"), - request.getProvider(), - request.getExternalId())); - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError(appError("LinkExternalAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError(appError("LinkExternalAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "LinkExternalAccount", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -841,32 +789,16 @@ public void requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest request, StreamObserver responseObserver) { - try { - accountService.requestEmailVerification( - requirePositiveRequestId(request.getAccountId(), "accountId")); - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError(appError("RequestEmailVerification", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError(appError("RequestEmailVerification", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "RequestEmailVerification", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override 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 b403a19629..8fb83c5621 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 @@ -609,7 +609,9 @@ private JoinPublicProductionResult executeJoinAttempt( } if (isConnectScopeExpired(scope)) { - return failedJoin(requestId, scope, "CONNECT_SCOPE_INVALID"); + accountJoinOperationRepository.recordAttemptFailure( + requestId, "NOT_EVALUATED", "AUTH_UNAVAILABLE"); + return pendingJoinFailure(scope, "AUTH_UNAVAILABLE"); } JoinEvaluation evaluation = evaluateJoin(scope); @@ -1819,61 +1821,19 @@ public AccountDataExportDto exportAccountData(Long accountId) { @Transactional(readOnly = true) @Timed(value = "account.tenant_export") public TenantDataExportDto exportTenantData(Long tenantId, Long accountId) { - Account account = requireAccount(accountId); - Profile profile = - profileRepository.findByAccountIdAndTenantId(accountId, tenantId).orElse(null); - if (!accountTenantMembershipRepository.existsByAccountIdAndTenantId(accountId, tenantId) - && profile == null) { - throw new IllegalArgumentException("Tenant data not found"); - } - return new TenantDataExportDto( - tenantId, - accountMapper.toDto(account), - profile != null ? profileMapper.toDto(profile) : null); + throw new ResponseStatusException( + HttpStatus.NOT_IMPLEMENTED, + "Tenant-admin export is unavailable until the tenant-wide export contract is implemented"); } @Override @Transactional @Timed(value = "account.delete") public void deleteAccount(Long accountId) { - Account account = requireAccount(accountId); - if (accountJoinOperationRepository.hasRetainedOperation(accountId)) { - throw new AccountLifecycleException( - "ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED", - "Account JOIN receipts require retention and deletion reconciliation"); - } - List subscriptions = - subscriptionRepository.findByAccountId(accountId); - Optional blockingSubscription = - subscriptions.stream().filter(this::isNonterminalSubscription).findFirst(); - if (blockingSubscription.isPresent()) { - throw new AccountLifecycleException( - "ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", - "Account has nonterminal tenant subscriptions; cancel or end subscriptions first"); - } - emailVerificationTokenRepository.deleteByAccountId(accountId); - passwordResetTokenRepository.deleteByAccountId(accountId); - accountRealmAccessGrantRepository.deleteByAccountId(accountId); - externalAccountRepository.deleteByAccountId(accountId); - paymentTransactionRepository.deleteByAccountId(accountId); - subscriptionRepository.deleteByAccountId(accountId); - profileRepository.deleteByAccountId(accountId); - accountTenantMembershipRepository.deleteByAccountId(accountId); - accountRepository.delete(account); - } - - private boolean isNonterminalSubscription( - net.firedevops.firemud.accountservice.entity.Subscription subscription) { - String status = - subscription.getStatus() == null - ? "" - : subscription.getStatus().trim().toLowerCase(java.util.Locale.ROOT); - boolean terminalStatus = - switch (status) { - case "canceled", "cancelled", "ended", "expired" -> true; - default -> false; - }; - return !terminalStatus || subscription.getEndedAt() == null; + requireAccount(accountId); + throw new AccountLifecycleException( + "ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", + "Account deletion is unavailable until its provider reconciliation and data retention workflow is implemented"); } @Override @@ -1909,13 +1869,16 @@ public void completePasswordReset(CompletePasswordResetRequest request) { passwordResetTokenRepository .findByToken(request.token()) .orElseThrow(() -> new IllegalArgumentException("Invalid token")); - if (token.getExpiresAt().isBefore(java.time.LocalDateTime.now())) { + LocalDateTime now = LocalDateTime.now(); + if (token.getExpiresAt().isBefore(now)) { throw new IllegalArgumentException("Token expired"); } + if (!passwordResetTokenRepository.consumeIfUnexpired(token, now)) { + throw new IllegalArgumentException("Invalid token"); + } net.firedevops.firemud.accountservice.entity.Account account = token.getAccount(); account.setPasswordHash(hashPassword(request.newPassword())); accountRepository.save(account); - passwordResetTokenRepository.delete(token); } @Override @@ -1961,13 +1924,16 @@ public void verifyEmail(VerifyEmailRequest request) { emailVerificationTokenRepository .findByToken(request.token()) .orElseThrow(() -> new IllegalArgumentException("Invalid token")); - if (token.getExpiresAt().isBefore(java.time.LocalDateTime.now())) { + LocalDateTime now = LocalDateTime.now(); + if (token.getExpiresAt().isBefore(now)) { throw new IllegalArgumentException("Token expired"); } + if (!emailVerificationTokenRepository.consumeIfUnexpired(token, now)) { + throw new IllegalArgumentException("Invalid token"); + } Account account = token.getAccount(); account.setEmailVerified(true); accountRepository.save(account); - emailVerificationTokenRepository.delete(token); } @Override diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java index 1c103e5523..a7b49951f6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java @@ -13,10 +13,10 @@ import net.firedevops.firemud.account.v1.PaymentServiceGrpc; import net.firedevops.firemud.account.v1.RefundPaymentRequest; import net.firedevops.firemud.account.v1.RefundPaymentResponse; -import net.firedevops.firemud.accountservice.dto.PaymentIntentDto; import net.firedevops.firemud.accountservice.service.PaymentService; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -46,40 +46,11 @@ public PaymentGrpcService(PaymentService paymentService, MeterRegistry meterRegi public void createPaymentIntent( CreatePaymentIntentRequest request, StreamObserver responseObserver) { - try { - PaymentIntentDto dto = - paymentService.createPaymentIntent( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getAmountCents()); - CreatePaymentIntentResponse response = - CreatePaymentIntentResponse.newBuilder() - .setIntentId(dto.id().toString()) - .setClientSecret(dto.clientSecret()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - CreatePaymentIntentResponse response = - CreatePaymentIntentResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "CreatePaymentIntent", - "INVALID_ARGUMENT", - ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - CreatePaymentIntentResponse response = - CreatePaymentIntentResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "CreatePaymentIntent", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + CreatePaymentIntentResponse.newBuilder() + .setError(unavailable("CreatePaymentIntent")) + .build()); + responseObserver.onCompleted(); } @Override @@ -121,67 +92,27 @@ public void createSubscription( @Timed(value = "paymentGrpc.createDonation") public void createDonation( CreateDonationRequest request, StreamObserver responseObserver) { - try { - PaymentIntentDto dto = - paymentService.createDonation( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getAmountCents()); - CreateDonationResponse response = - CreateDonationResponse.newBuilder() - .setIntentId(dto.id().toString()) - .setClientSecret(dto.clientSecret()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - CreateDonationResponse response = - CreateDonationResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "CreateDonation", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - CreateDonationResponse response = - CreateDonationResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "CreateDonation", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + CreateDonationResponse.newBuilder().setError(unavailable("CreateDonation")).build()); + responseObserver.onCompleted(); } @Override @Timed(value = "paymentGrpc.refundPayment") public void refundPayment( RefundPaymentRequest request, StreamObserver responseObserver) { - try { - paymentService.refundPayment( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getPaymentId(), "paymentId")); - RefundPaymentResponse response = RefundPaymentResponse.newBuilder().setSuccess(true).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - RefundPaymentResponse response = - RefundPaymentResponse.newBuilder() - .setSuccess(false) - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "RefundPayment", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - RefundPaymentResponse response = - RefundPaymentResponse.newBuilder() - .setSuccess(false) - .setError(GrpcAppErrors.internal(meterRegistry, logger, "RefundPayment", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + RefundPaymentResponse.newBuilder() + .setSuccess(false) + .setError(unavailable("RefundPayment")) + .build()); + responseObserver.onCompleted(); + } + + private ErrorDetail unavailable(String operation) { + String message = operation + " is unavailable"; + return meterRegistry == null + ? ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build() + : GrpcAppErrors.error(meterRegistry, logger, operation, "FAILED_PRECONDITION", message); } } diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 9ac4dcca75..e4f9b23226 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -72,8 +72,6 @@ firemud: - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp - account.v1.AccountService/Ping - - account.v1.AccountService/GetTenantMembershipForRuntime - - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership grpc: @@ -85,6 +83,11 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_INTERVAL_MS:60000} + join-reconciliation: + batch-size: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BATCH_SIZE:50} + max-attempts: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_MAX_ATTEMPTS:12} + interval-ms: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_INTERVAL_MS:30000} + backoff-ms: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BACKOFF_MS:30000} tokens: session-expiration-ms: ${FIREMUD_ACCOUNT_TOKENS_SESSION_EXPIRATION_MS:3600000} player-bootstrap-expiration-ms: ${FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS:300000} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 320f48b2c5..aaa18ca800 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -45,6 +45,11 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_INTERVAL_MS:60000} + join-reconciliation: + batch-size: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BATCH_SIZE:50} + max-attempts: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_MAX_ATTEMPTS:12} + interval-ms: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_INTERVAL_MS:30000} + backoff-ms: ${FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BACKOFF_MS:30000} tokens: session-expiration-ms: 3600000 player-bootstrap-expiration-ms: 300000 @@ -94,8 +99,6 @@ firemud: - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp - account.v1.AccountService/Ping - - account.v1.AccountService/GetTenantMembershipForRuntime - - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership diff --git a/services/account-service/src/main/resources/db/migration/V27__account_join_reconciliation.sql b/services/account-service/src/main/resources/db/migration/V27__account_join_reconciliation.sql new file mode 100644 index 0000000000..2e45cfb936 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V27__account_join_reconciliation.sql @@ -0,0 +1,25 @@ +-- PENDING JOIN evidence is retained until an exact deterministic outcome is proved. +-- Bounded reconciliation metadata schedules retries without expiring or deleting operations. +ALTER TABLE account_join_operations + ADD COLUMN reconciliation_attempt_count INTEGER NOT NULL DEFAULT 0, + ADD COLUMN last_reconciliation_attempt_at TIMESTAMP, + ADD COLUMN last_reconciliation_attempt_reason VARCHAR(128), + ADD COLUMN next_reconciliation_attempt_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ADD CONSTRAINT account_join_reconciliation_attempt_count_check + CHECK (reconciliation_attempt_count >= 0), + ADD CONSTRAINT account_join_reconciliation_attempt_detail_check + CHECK ((reconciliation_attempt_count = 0 + AND last_reconciliation_attempt_at IS NULL + AND last_reconciliation_attempt_reason IS NULL) + OR (reconciliation_attempt_count > 0 + AND last_reconciliation_attempt_at IS NOT NULL + AND last_reconciliation_attempt_reason IS NOT NULL + AND btrim(last_reconciliation_attempt_reason) <> '')); + +CREATE INDEX idx_account_join_operations_pending_reconciliation + ON account_join_operations( + next_reconciliation_attempt_at, + created_at, + request_id + ) + WHERE status = 'PENDING'; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index 7348a5ed68..5eec6c2e24 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -1,20 +1,33 @@ package net.firedevops.firemud.accountservice; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.time.LocalDateTime; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import org.jooq.DSLContext; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -25,6 +38,8 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -60,6 +75,8 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -117,6 +134,201 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws .isEqualTo(1L); } + @Test + void concurrentPasswordResetAttemptsConsumeTokenExactlyOnce() throws Exception { + String suffix = UUID.randomUUID().toString(); + String email = "reset-" + suffix + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "reset-" + suffix, + email, + "initial-hash") + .fetchOne(0, Long.class); + assertThat(accountId).isNotNull(); + String rawToken = UUID.randomUUID().toString(); + dsl.execute( + "INSERT INTO password_reset_token (account_id, token, expires_at) VALUES (?, ?, ?)", + accountId, + rawToken, + LocalDateTime.now().plusHours(1)); + + CompletePasswordResetRequest request = + new CompletePasswordResetRequest(rawToken, "new-password"); + assertExactlyOneConcurrentSuccess( + () -> { + accountService.completePasswordReset(request); + return null; + }, + () -> { + accountService.completePasswordReset(request); + return null; + }); + + assertThat( + dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) + .fetchOne(0, String.class)) + .isNotEqualTo("initial-hash"); + } + + @Test + void passwordResetConsumptionRollsBackWithAccountMutation() { + String suffix = UUID.randomUUID().toString(); + String email = "reset-rollback-" + suffix + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "rr-" + suffix, + email, + "initial-hash") + .fetchOne(0, Long.class); + assertThat(accountId).isNotNull(); + String rawToken = UUID.randomUUID().toString(); + dsl.execute( + "INSERT INTO password_reset_token (account_id, token, expires_at) VALUES (?, ?, ?)", + accountId, + rawToken, + LocalDateTime.now().plusHours(1)); + CompletePasswordResetRequest request = + new CompletePasswordResetRequest(rawToken, "new-password"); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + accountService.completePasswordReset(request); + throw new IllegalStateException("force rollback after token consumption"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("force rollback after token consumption"); + + assertThat( + dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) + .fetchOne(0, String.class)) + .isEqualTo("initial-hash"); + + accountService.completePasswordReset(request); + + assertThat( + dsl.resultQuery("SELECT COUNT(*) FROM password_reset_token WHERE token = ?", rawToken) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery("SELECT password_hash FROM accounts WHERE id = ?", accountId) + .fetchOne(0, String.class)) + .isNotEqualTo("initial-hash"); + } + + @Test + void accountDeletionUnavailablePreservesTerminalSubscriptionAndPaymentEvidence() { + String suffix = UUID.randomUUID().toString(); + String email = "delete-" + suffix + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "del-" + suffix.substring(0, 12), + email, + "initial-hash") + .fetchOne(0, Long.class); + assertThat(accountId).isNotNull(); + LocalDateTime subscriptionEndedAt = LocalDateTime.now().minusDays(1); + dsl.execute( + "INSERT INTO subscription (account_id, plan_id, status, started_at, ended_at, tenant_id) " + + "VALUES (?, ?, ?, ?, ?, ?)", + accountId, + "retained-plan", + "canceled", + subscriptionEndedAt.minusDays(30), + subscriptionEndedAt, + 1L); + String providerId = "pi-" + suffix.substring(0, 24); + dsl.execute( + "INSERT INTO payment_transaction " + + "(account_id, amount_cents, currency, status, provider_id, tenant_id) " + + "VALUES (?, ?, ?, ?, ?, ?)", + accountId, + 2500L, + "USD", + "succeeded", + providerId, + 1L); + + AccountLifecycleException exception = + Assertions.assertThrows( + AccountLifecycleException.class, () -> accountService.deleteAccount(accountId)); + + assertThat(exception.getCode()).isEqualTo("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE"); + assertThat( + dsl.resultQuery("SELECT COUNT(*) FROM accounts WHERE id = ?", accountId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM subscription " + + "WHERE account_id = ? AND status = 'canceled' AND ended_at IS NOT NULL", + accountId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM payment_transaction " + + "WHERE account_id = ? AND provider_id = ? AND status = 'succeeded'", + accountId, + providerId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void concurrentEmailVerificationAttemptsConsumeTokenExactlyOnce() throws Exception { + String suffix = UUID.randomUUID().toString(); + String email = "verify-" + suffix + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "verify-" + suffix, + email, + "initial-hash") + .fetchOne(0, Long.class); + assertThat(accountId).isNotNull(); + String rawToken = UUID.randomUUID().toString(); + dsl.execute( + "INSERT INTO email_verification_token (account_id, token, expires_at) VALUES (?, ?, ?)", + accountId, + rawToken, + LocalDateTime.now().plusHours(1)); + + VerifyEmailRequest request = new VerifyEmailRequest(rawToken); + assertExactlyOneConcurrentSuccess( + () -> { + accountService.verifyEmail(request); + return null; + }, + () -> { + accountService.verifyEmail(request); + return null; + }); + + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM email_verification_token WHERE token = ?", rawToken) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery("SELECT email_verified FROM accounts WHERE id = ?", accountId) + .fetchOne(0, Boolean.class)) + .isTrue(); + } + @Test void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { String token = @@ -175,4 +387,37 @@ void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Except assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); assertThat(response.body()).contains("\"message\":\"tenantId must be positive\""); } + + private static void assertExactlyOneConcurrentSuccess(Callable first, Callable second) + throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future firstResult = executor.submit(() -> runWhenReleased(first, ready, start)); + Future secondResult = executor.submit(() -> runWhenReleased(second, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat(firstResult.get(30, TimeUnit.SECONDS)) + .isNotEqualTo(secondResult.get(30, TimeUnit.SECONDS)); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private static boolean runWhenReleased( + Callable operation, CountDownLatch ready, CountDownLatch start) throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to start concurrent recovery attempt"); + } + try { + operation.call(); + return true; + } catch (IllegalArgumentException alreadyConsumed) { + return false; + } + } } 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 new file mode 100644 index 0000000000..d86af7f70a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -0,0 +1,383 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +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.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.v1.GameplayRealm; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH + }) +class AccountJoinPostgresIntegrationTest { + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + private static final String WORLD_SLUG = "join-proof-world"; + private static final String REALM_SLUG = "production"; + private static final String NAMESPACE_ID = "join-proof-namespace"; + private static final long GAME_INSTANCE_ID = 44L; + private static final long CATALOG_REVISION = 23L; + private static final long POINTER_VERSION = 17L; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + @MockitoSpyBean private AccountJoinOperationRepository joinOperationRepository; + + @Test + void terminalCommitWithLostAcknowledgementReadsBackExactStoredJoinResult() { + JoinFixture fixture = fixture("active"); + AtomicBoolean loseNextTerminalAcknowledgement = new AtomicBoolean(true); + doAnswer( + invocation -> { + invocation.callRealMethod(); + if ("COMMITTED".equals(invocation.getArgument(1)) + && loseNextTerminalAcknowledgement.compareAndSet(true, false)) { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + throw new IllegalStateException( + "simulated lost terminal commit acknowledgement"); + } + }); + } + return null; + }) + .when(joinOperationRepository) + .finish(anyString(), anyString(), anyString(), any(), any(), any()); + + JoinPublicProductionResult result = join(fixture); + + assertThat(result) + .isEqualTo( + new JoinPublicProductionResult( + true, + "JOINED", + fixture.accountId(), + fixture.tenantId(), + result.membershipId(), + 1L, + 1L, + true)); + assertThat(result.membershipId()).isPositive(); + assertThat( + dsl.fetchOne( + "SELECT status, outcome, request_digest, request_digest_version, entitlement_version, allow_public_join, membership_id, outcome_membership_version, outcome_membership_authority_generation " + + "FROM account_join_operations WHERE request_id = ?", + fixture.requestId())) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(row.get("outcome", String.class)).isEqualTo("JOINED"); + assertThat(row.get("request_digest", String.class)).startsWith("sha256:"); + assertThat(row.get("request_digest_version", Integer.class)).isEqualTo(1); + assertThat(row.get("entitlement_version", Long.class)).isEqualTo(1L); + assertThat(row.get("allow_public_join", Boolean.class)).isTrue(); + assertThat(row.get("membership_id", Long.class)).isEqualTo(result.membershipId()); + assertThat(row.get("outcome_membership_version", Long.class)).isEqualTo(1L); + assertThat(row.get("outcome_membership_authority_generation", Long.class)) + .isEqualTo(1L); + }); + assertTransitionAndAuditOutboxOnce(fixture, result.membershipId()); + } + + @Test + void rolledBackTerminalAttemptStaysPendingAndSameRequestCommitsOnceOnRetry() { + JoinFixture fixture = fixture("active"); + AtomicBoolean failNextTerminalAttempt = new AtomicBoolean(true); + doAnswer( + invocation -> { + invocation.callRealMethod(); + if ("COMMITTED".equals(invocation.getArgument(1)) + && failNextTerminalAttempt.compareAndSet(true, false)) { + throw new IllegalStateException( + "simulated failure before terminal transaction commit"); + } + return null; + }) + .when(joinOperationRepository) + .finish(anyString(), anyString(), anyString(), any(), any(), any()); + + AuthenticationException uncertain = + assertThrows(AuthenticationException.class, () -> join(fixture)); + + assertThat(uncertain.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat( + dsl.fetchOne( + "SELECT status, outcome, request_digest, membership_id, last_attempt_failure_code " + + "FROM account_join_operations WHERE request_id = ?", + fixture.requestId())) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("outcome", String.class)).isNull(); + assertThat(row.get("request_digest", String.class)).isNull(); + assertThat(row.get("membership_id", Long.class)).isNull(); + assertThat(row.get("last_attempt_failure_code", String.class)) + .isEqualTo("AUTH_UNAVAILABLE"); + }); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + + JoinPublicProductionResult recovered = join(fixture); + + assertThat(recovered.success()).isTrue(); + assertThat(recovered.outcomeCode()).isEqualTo("JOINED"); + assertThat(recovered.replayed()).isFalse(); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertTransitionAndAuditOutboxOnce(fixture, recovered.membershipId()); + } + + @Test + void failedJoinReplaysStoredOutcomeAndRejectsChangedPolicyDigest() { + JoinFixture fixture = fixture("grace"); + + JoinPublicProductionResult failed = join(fixture); + JoinPublicProductionResult replayed = join(fixture); + + assertThat(failed.success()).isFalse(); + assertThat(failed.outcomeCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(failed.replayed()).isFalse(); + assertThat(replayed) + .isEqualTo( + new JoinPublicProductionResult( + failed.success(), + failed.outcomeCode(), + failed.accountId(), + failed.tenantId(), + failed.membershipId(), + failed.membershipVersion(), + failed.membershipAuthorityGeneration(), + true)); + String originalDigest = + dsl.resultQuery( + "SELECT request_digest FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(0, String.class); + assertThat(originalDigest).startsWith("sha256:"); + assertThat( + dsl.resultQuery( + "SELECT status || ':' || outcome FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(0, String.class)) + .isEqualTo("FAILED:PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + + dsl.execute( + "UPDATE subscription SET status = 'active', entitlement_version = 2 WHERE tenant_id = ?", + fixture.tenantId()); + AuthenticationException conflict = + assertThrows(AuthenticationException.class, () -> join(fixture)); + + assertThat(conflict.getCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat( + dsl.resultQuery( + "SELECT request_digest FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(0, String.class)) + .isEqualTo(originalDigest); + assertThat( + dsl.resultQuery( + "SELECT status || ':' || outcome FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(0, String.class)) + .isEqualTo("FAILED:PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + } + + 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( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "join-proof-" + suffix, + "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); + + GameplayRealm realm = + GameplayRealm.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + GameplayAdmissionPointer pointer = + GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + when(gameSessionClient.getAdmissionPointer(tenantId, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + + DirectTextCallerContext caller = + new DirectTextCallerContext( + accountId, + tenantId, + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "join-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + tenantId, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + CATALOG_REVISION, + POINTER_VERSION); + DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); + return new JoinFixture(accountId, tenantId, requestId, caller, scope.connectScopeId()); + } + + private long countMemberships(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private JoinPublicProductionResult join(JoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.requestId())); + } + + private long countJoinOutbox(JoinFixture fixture) { + UUID eventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.requestId()).getBytes(StandardCharsets.UTF_8)); + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + eventId, + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long membershipId) { + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND authority_provenance = 'EXPLICIT_JOIN' AND membership_version = 1 AND membership_authority_generation = 1", + membershipId, + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND payload LIKE ?", + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.requestId()) + .getBytes(StandardCharsets.UTF_8)), + "%" + fixture.requestId() + "%") + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + private record JoinFixture( + long accountId, + long tenantId, + String requestId, + DirectTextCallerContext caller, + String connectScopeId) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java new file mode 100644 index 0000000000..7c5984f5d2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -0,0 +1,435 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +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.service.AccountJoinReconciliationService; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.v1.GameplayRealm; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.account.join-reconciliation.interval-ms=3600000", + "firemud.account.join-reconciliation.batch-size=20", + "firemud.account.join-reconciliation.max-attempts=2", + "firemud.account.join-reconciliation.backoff-ms=1000" + }) +class AccountJoinReconciliationPostgresIntegrationTest { + private static final UUID REALM_ID = UUID.fromString("a825f7ef-0ea3-4e8c-bf7c-a20242b4c931"); + private static final String WORLD_SLUG = "join-reconciliation-world"; + private static final String REALM_SLUG = "production"; + private static final String NAMESPACE_ID = "join-reconciliation-namespace"; + private static final long GAME_INSTANCE_ID = 73L; + private static final long CATALOG_REVISION = 29L; + private static final long POINTER_VERSION = 11L; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountJoinReconciliationService reconciliationService; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @Test + void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplicates() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult original = join(fixture); + assertThat(original.success()).isTrue(); + assertThat(original.outcomeCode()).isEqualTo("JOINED"); + long membershipId = original.membershipId(); + + // This is a synthetic ambiguous row assembled from a genuine committed JOIN. The current + // atomic terminal transaction cannot naturally commit membership/audit while leaving the + // operation PENDING; this fixture tests the exact readback branch without inventing evidence. + makeOperationPendingWithRetainedEvidence(fixture); + Instant scopeExpiry = expireScopeBeforeReconciliationButAfterEvaluation(fixture); + + Instant now = scopeExpiry.plusSeconds(1); + reconciliationService.reconcileDueOperations(now); + + assertOperation(fixture, "COMMITTED", "JOINED", 0, null); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_join_operations WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED' AND membership_id = ? AND outcome_membership_version = 1 AND outcome_membership_authority_generation = 1", + fixture.requestId(), + membershipId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertMembershipAndAuditOnce(fixture, membershipId); + + JoinPublicProductionResult retry = join(fixture); + assertThat(retry.success()).isTrue(); + assertThat(retry.outcomeCode()).isEqualTo("JOINED"); + assertThat(retry.replayed()).isTrue(); + assertThat(retry.membershipId()).isEqualTo(membershipId); + assertMembershipAndAuditOnce(fixture, membershipId); + } + + @Test + void absentScopeAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostics() { + JoinFixture absentScope = committedEvidencePendingFixture(); + dsl.execute( + "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", + AccountJoinDigest.tokenHash(absentScope.connectScopeId())); + assertUnresolved(absentScope, "JOIN_SCOPE_EVIDENCE_ABSENT"); + assertThat(countMemberships(absentScope)).isEqualTo(1L); + assertThat(countJoinOutbox(absentScope)).isEqualTo(1L); + + JoinFixture expiredWithoutMembership = committedEvidencePendingFixture(); + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + expiredWithoutMembership.accountId(), + expiredWithoutMembership.tenantId()); + expireScopeBeforeReconciliationButAfterEvaluation(expiredWithoutMembership); + assertUnresolved(expiredWithoutMembership, "MEMBERSHIP_EVIDENCE_ABSENT"); + assertThat(countMemberships(expiredWithoutMembership)).isZero(); + assertThat(countJoinOutbox(expiredWithoutMembership)).isEqualTo(1L); + } + + @Test + void absentMembershipOrAuditEnvelopeCannotTerminalizePendingOperation() { + JoinFixture absentMembership = committedEvidencePendingFixture(); + dsl.execute( + "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + absentMembership.accountId(), + absentMembership.tenantId()); + assertUnresolved(absentMembership, "MEMBERSHIP_EVIDENCE_ABSENT"); + assertThat(countJoinOutbox(absentMembership)).isEqualTo(1L); + + JoinFixture absentAudit = committedEvidencePendingFixture(); + dsl.execute( + "DELETE FROM account_audit_outbox WHERE audit_event_id = ?", + joinAuditEventId(absentAudit.requestId())); + assertUnresolved(absentAudit, "JOIN_AUDIT_ENVELOPE_ABSENT"); + assertThat(countMemberships(absentAudit)).isEqualTo(1L); + assertThat(countJoinOutbox(absentAudit)).isZero(); + } + + @Test + void concurrentCallerRetryAndReconcilerKeepSingleMembershipTransitionAndAudit() throws Exception { + JoinFixture fixture = committedEvidencePendingFixture(); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Instant now = Instant.now().plusSeconds(1); + Future reconciliation = + executor.submit( + () -> { + await(start); + reconciliationService.reconcileDueOperations(now); + }); + Future callerRetry = + executor.submit( + () -> { + await(start); + return join(fixture); + }); + start.countDown(); + + reconciliation.get(30, TimeUnit.SECONDS); + JoinPublicProductionResult retry = callerRetry.get(30, TimeUnit.SECONDS); + + assertThat(retry.success()).isTrue(); + assertThat(retry.outcomeCode()).isIn("JOINED", "ALREADY_ACTIVE"); + assertOperation(fixture, "COMMITTED", retry.outcomeCode(), 0, null); + assertMembershipAndAuditOnce(fixture, originalMembershipId(fixture)); + } finally { + executor.shutdownNow(); + } + } + + @Test + void naturallyAbandonedPendingIntentStaysVisibleAndStopsAtConfiguredAttemptLimit() { + JoinFixture fixture = fixture("active"); + when(gameSessionClient.getAdmissionPointer(fixture.tenantId(), WORLD_SLUG, REALM_SLUG)) + .thenThrow(new IllegalStateException("simulated unavailable admission authority")); + + JoinPublicProductionResult attempt = join(fixture); + + assertThat(attempt.success()).isFalse(); + assertThat(attempt.outcomeCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertOperation(fixture, "PENDING", null, 0, null); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + + Instant firstAttemptAt = Instant.now().plusSeconds(1); + reconciliationService.reconcileDueOperations(firstAttemptAt); + assertOperation(fixture, "PENDING", null, 1, "JOIN_OPERATION_POLICY_UNPROVEN"); + + reconciliationService.reconcileDueOperations(firstAttemptAt); + assertOperation(fixture, "PENDING", null, 1, "JOIN_OPERATION_POLICY_UNPROVEN"); + + reconciliationService.reconcileDueOperations(firstAttemptAt.plusMillis(1500)); + assertOperation(fixture, "PENDING", null, 2, "JOIN_OPERATION_POLICY_UNPROVEN"); + + reconciliationService.reconcileDueOperations(firstAttemptAt.plusSeconds(5)); + assertOperation(fixture, "PENDING", null, 2, "JOIN_OPERATION_POLICY_UNPROVEN"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + } + + private JoinFixture committedEvidencePendingFixture() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult committed = join(fixture); + assertThat(committed.success()).isTrue(); + assertThat(committed.outcomeCode()).isEqualTo("JOINED"); + makeOperationPendingWithRetainedEvidence(fixture); + return fixture; + } + + private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture) { + int updated = + dsl.execute( + "UPDATE account_join_operations SET status = 'PENDING', outcome = NULL, membership_id = NULL, outcome_membership_version = NULL, outcome_membership_authority_generation = NULL, reconciliation_attempt_count = 0, last_reconciliation_attempt_at = NULL, last_reconciliation_attempt_reason = NULL, next_reconciliation_attempt_at = CURRENT_TIMESTAMP - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED'", + fixture.requestId()); + assertThat(updated).isEqualTo(1); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + } + + private Instant expireScopeBeforeReconciliationButAfterEvaluation(JoinFixture fixture) { + String expiresAt = + dsl.resultQuery( + "SELECT connect_scope_expires_at FROM account_connect_scope_records WHERE scope_token_hash = ?", + AccountJoinDigest.tokenHash(fixture.connectScopeId())) + .fetchOne(0, String.class); + assertThat(expiresAt).isNotBlank(); + return Instant.parse(expiresAt); + } + + private void assertUnresolved(JoinFixture fixture, String reason) { + Instant now = Instant.now().plusSeconds(2); + reconciliationService.reconcileDueOperations(now); + assertOperation(fixture, "PENDING", null, 1, reason); + + reconciliationService.reconcileDueOperations(now); + assertOperation(fixture, "PENDING", null, 1, reason); + } + + private void assertOperation( + JoinFixture fixture, String status, String outcome, int attempts, String reason) { + var row = + dsl.resultQuery( + "SELECT status, outcome, reconciliation_attempt_count, last_reconciliation_attempt_reason, (next_reconciliation_attempt_at > last_reconciliation_attempt_at) AS backoff_scheduled FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(); + assertThat(row).isNotNull(); + assertThat(row.get("status", String.class)).isEqualTo(status); + assertThat(row.get("outcome", String.class)).isEqualTo(outcome); + assertThat(row.get("reconciliation_attempt_count", Integer.class)).isEqualTo(attempts); + assertThat(row.get("last_reconciliation_attempt_reason", String.class)).isEqualTo(reason); + if (attempts > 0) { + assertThat(row.get("backoff_scheduled", Boolean.class)).isTrue(); + } + } + + private long originalMembershipId(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private void assertMembershipAndAuditOnce(JoinFixture fixture, long membershipId) { + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND gameplay_admission_allowed = TRUE AND authority_provenance = 'EXPLICIT_JOIN' AND membership_version = 1 AND membership_authority_generation = 1", + membershipId, + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' AND payload_digest_version = 1 AND payload_digest LIKE 'sha256:%' AND payload LIKE ?", + joinAuditEventId(fixture.requestId()), + fixture.tenantId(), + "%" + fixture.requestId() + "%") + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + private long countMemberships(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private long countJoinOutbox(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + joinAuditEventId(fixture.requestId()), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private JoinPublicProductionResult join(JoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.requestId())); + } + + private JoinFixture fixture(String subscriptionStatus) { + String suffix = UUID.randomUUID().toString(); + String requestId = "join-reconcile-" + suffix; + long tenantId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "join-reconcile-" + suffix, + "join-reconcile-" + 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-reconcile", + subscriptionStatus); + + GameplayRealm realm = + GameplayRealm.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + GameplayAdmissionPointer pointer = + GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + when(gameSessionClient.getAdmissionPointer(tenantId, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + + DirectTextCallerContext caller = + new DirectTextCallerContext( + accountId, + tenantId, + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "join-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + tenantId, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + CATALOG_REVISION, + POINTER_VERSION); + DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); + return new JoinFixture(accountId, tenantId, requestId, caller, scope.connectScopeId()); + } + + private static UUID joinAuditEventId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static void await(CountDownLatch start) { + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent JOIN test did not receive its start signal"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("concurrent JOIN test was interrupted", ex); + } + } + + private record JoinFixture( + long accountId, + long tenantId, + String requestId, + DirectTextCallerContext caller, + String connectScopeId) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index a666f1fdad..8542656a96 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -17,7 +17,6 @@ import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; -import net.firedevops.firemud.accountservice.dto.TenantDataExportDto; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; import net.firedevops.firemud.accountservice.service.AccountService; @@ -110,13 +109,15 @@ void createAccountRetainsMinimumPasswordLength() throws Exception { } @Test - void deleteAccountAllowsScopedTenantAdmin() throws Exception { + void deleteAccountDeniesPlatformAdminBeforeServiceMutation() throws Exception { String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform(delete("/accounts/42").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")); + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error.code").value("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE")); + + verifyNoInteractions(accountService); } @Test @@ -145,10 +146,7 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { } @Test - void exportTenantDataAllowsScopedTenantRole() throws Exception { - AccountDto account = new AccountDto(42L, "demo", "demo@example.com", "player", true); - when(accountService.exportTenantData(7L, 42L)) - .thenReturn(new TenantDataExportDto(7L, account, null)); + void exportTenantDataFailsClosedWithoutReadingAccountService() throws Exception { String token = jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("moderator")))); @@ -157,8 +155,9 @@ void exportTenantDataAllowsScopedTenantRole() throws Exception { get("/accounts/42/tenant-export") .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")); + .andExpect(status().isNotImplemented()); + + verifyNoInteractions(accountService); } @Test @@ -193,7 +192,7 @@ void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { } @Test - void deleteAccountAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Exception { + void deleteAccountDeniesCurrentAccountBeforeServiceMutation() throws Exception { String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); mockMvc @@ -201,8 +200,10 @@ void deleteAccountAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Excep delete("/accounts/42") .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")); + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error.code").value("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE")); + + verifyNoInteractions(accountService); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java index cdad776a8c..ceb6732cb4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java @@ -9,7 +9,6 @@ import io.grpc.Status; import java.util.List; import java.util.Map; -import java.util.Set; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.common.security.AuthTokenInterceptor; import net.firedevops.firemud.common.security.JwtUtil; @@ -48,23 +47,15 @@ void allowsValidToken() { } @Test - void allowsConfiguredUnauthenticatedRuntimeMethodWithoutToken() { - AuthTokenInterceptor runtimeAwareInterceptor = - new AuthTokenInterceptor( - jwtUtil, - Set.of( - AccountServiceGrpc.getGetTenantMembershipForRuntimeMethod().getFullMethodName())); - TestServerCall call = - new TestServerCall( - AccountServiceGrpc.getGetTenantMembershipForRuntimeMethod().getFullMethodName()); - Metadata headers = new Metadata(); - - ServerCall.Listener listener = - runtimeAwareInterceptor.interceptCall( - call, headers, (c, h) -> new ServerCall.Listener<>() {}); - - assertNotNull(listener); - assertEquals(null, call.status); + void rejectsRuntimeMethodsWithoutToken() { + for (String method : + List.of( + AccountServiceGrpc.getGetTenantMembershipForRuntimeMethod().getFullMethodName(), + AccountServiceGrpc.getGetTenantEntitlementsForRuntimeMethod().getFullMethodName())) { + TestServerCall call = new TestServerCall(method); + interceptor.interceptCall(call, new Metadata(), (c, h) -> new ServerCall.Listener<>() {}); + assertEquals(Status.UNAUTHENTICATED.getCode(), call.status.getCode()); + } } private static class TestServerCall extends ServerCall { 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 new file mode 100644 index 0000000000..39f2ba7942 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java @@ -0,0 +1,500 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +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.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.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountJoinReconciliationServiceTest { + private static final Instant NOW = Instant.parse("2026-09-24T00:00:00Z"); + private static final Instant EVALUATED_AT = NOW.minusSeconds(60); + private static final Instant EXPIRED_AT = NOW.minusSeconds(30); + private static final long ACCOUNT_ID = 101L; + private static final long TENANT_ID = 7L; + private static final long MEMBERSHIP_ID = 501L; + private static final long MEMBERSHIP_VERSION = 4L; + private static final long MEMBERSHIP_AUTHORITY_GENERATION = 3L; + private static final String REQUEST_ID = "join-request-1"; + private static final String CONNECT_SCOPE_ID = "retained-connect-scope-token"; + private static final String CALLER_BINDING = "game-session:instance-a"; + private static final String WORLD_SLUG = "demo-world"; + private static final String REALM_SLUG = "production"; + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + + @Test + void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { + Fixture fixture = fixture(5); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending, 5); + 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())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()))); + + fixture.service.reconcileDueOperations(NOW); + + InOrder lockOrder = inOrder(fixture.joinOperations); + lockOrder.verify(fixture.joinOperations).lockAccount(ACCOUNT_ID); + lockOrder.verify(fixture.joinOperations).findForUpdate(REQUEST_ID); + verify(fixture.joinOperations) + .finish( + REQUEST_ID, + "COMMITTED", + "JOINED", + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION); + verify(fixture.joinOperations, never()) + .recordReconciliationAttempt(anyString(), anyInt(), anyInt(), any(), anyString(), any()); + assertThat(reconciliationCounter(fixture, "committed")).isEqualTo(1); + } + + @Test + void missingMembershipAfterScopeExpiryStaysPendingAndRecordsBackoffReason() { + 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))); + when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "MEMBERSHIP_EVIDENCE_ABSENT", NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "MEMBERSHIP_EVIDENCE_ABSENT", NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions(fixture.auditOutbox); + assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); + } + + @Test + void absentJoinAuditStaysPendingAndLogsAttemptLimitMetric() { + Fixture fixture = fixture(1); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending, 1); + 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())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, 0, 1, NOW, "JOIN_AUDIT_ENVELOPE_ABSENT", NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, 0, 1, NOW, "JOIN_AUDIT_ENVELOPE_ABSENT", NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isEqualTo(1); + } + + @Test + void wrongPayloadDigestStaysPending() { + 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))); + when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(activeJoinMembership())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, sha256("wrong")))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "JOIN_AUDIT_ENVELOPE_UNCLEAR", NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "JOIN_AUDIT_ENVELOPE_UNCLEAR", NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + + @Test + void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { + 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))); + when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(activeJoinMembership())); + String mismatchedPayload = joinAuditEnvelope("other-world", TENANT_ID, "unused").payload(); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + joinAuditEnvelope( + "other-world", TENANT_ID, AccountAuditDigest.ofPayload(mismatchedPayload)))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "JOIN_AUDIT_ENVELOPE_UNCLEAR", NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "JOIN_AUDIT_ENVELOPE_UNCLEAR", NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + + @Test + void wrongRetainedTargetStaysPending() { + 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("PRIVATE", TENANT_ID, WORLD_SLUG))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, 0, 3, NOW, "JOIN_SCOPE_EVIDENCE_MISMATCH", NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + 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); + } + + @Test + void repeatedRunDoesNotFinishSameJoinTwice() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10, 3)) + .thenReturn(List.of(pending), List.of()); + 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())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()))); + + fixture.service.reconcileDueOperations(NOW); + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .finish( + REQUEST_ID, + "COMMITTED", + "JOINED", + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION); + verify(fixture.auditOutbox).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); + verify(fixture.auditOutbox, never()) + .append(any(), anyString(), any(), anyString(), anyString()); + } + + @Test + void concurrentCallerTerminalizationIsSkippedAfterAccountAndOperationLocks() { + Fixture fixture = fixture(3); + JoinOperation pendingSnapshot = pendingOperation(0, NOW.minusSeconds(1)); + JoinOperation terminalOperation = terminalOperation(); + stubDue(fixture, pendingSnapshot, 3); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)) + .thenReturn(Optional.of(terminalOperation)); + + fixture.service.reconcileDueOperations(NOW); + + InOrder lockOrder = inOrder(fixture.joinOperations); + lockOrder.verify(fixture.joinOperations).lockAccount(ACCOUNT_ID); + lockOrder.verify(fixture.joinOperations).findForUpdate(REQUEST_ID); + verify(fixture.joinOperations, never()) + .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); + } + + private static Fixture fixture(int maxAttempts) { + AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); + AccountConnectScopeRepository connectScopes = mock(AccountConnectScopeRepository.class); + AccountTenantMembershipRepository memberships = mock(AccountTenantMembershipRepository.class); + AccountAuditOutboxRepository auditOutbox = mock(AccountAuditOutboxRepository.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(invocation -> new SimpleTransactionStatus()); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + AccountJoinReconciliationService service = + new AccountJoinReconciliationService( + joinOperations, + connectScopes, + memberships, + auditOutbox, + meterRegistry, + transactionManager, + 10, + maxAttempts, + 5_000); + return new Fixture( + service, joinOperations, connectScopes, memberships, auditOutbox, meterRegistry); + } + + private static void stubDue(Fixture fixture, JoinOperation operation, int maxAttempts) { + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10, maxAttempts)) + .thenReturn(List.of(operation)); + } + + private static JoinOperation pendingOperation(int attemptCount, Instant nextAttemptAt) { + VerifiedJoinScope scope = verifiedScope(); + return new JoinOperation( + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + "namespace-prod", + "SHARED", + 9001L, + 12L, + 8L, + CALLER_BINDING, + AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID), + scope.snapshotDigest(), + "AVAILABLE", + true, + 42L, + 1, + AccountJoinDigest.request(scope, CALLER_BINDING, true, 42L), + "PENDING", + null, + null, + null, + null, + 1, + AccountJoinDigest.intent(REQUEST_ID, scope, CALLER_BINDING), + null, + "AVAILABLE", + attemptCount, + attemptCount == 0 ? null : NOW.minusSeconds(1), + attemptCount == 0 ? null : "PREVIOUS_RECONCILIATION_ATTEMPT", + nextAttemptAt); + } + + private static JoinOperation terminalOperation() { + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + return new JoinOperation( + pending.requestId(), + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + "COMMITTED", + "JOINED", + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION, + pending.intentDigestVersion(), + pending.intentDigest(), + null, + "AVAILABLE", + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt()); + } + + private static VerifiedJoinScope verifiedScope() { + VerifiedJoinScope unsigned = + new VerifiedJoinScope( + CONNECT_SCOPE_ID, + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + "namespace-prod", + "SHARED", + 9001L, + 12L, + 8L, + EVALUATED_AT.toString(), + EXPIRED_AT.toString(), + "unused"); + return new VerifiedJoinScope( + unsigned.connectScopeId(), + unsigned.accountId(), + unsigned.tenantId(), + unsigned.realmId(), + unsigned.worldSlug(), + unsigned.realmSlug(), + unsigned.playableStateNamespaceId(), + unsigned.playableStateScope(), + unsigned.gameInstanceId(), + unsigned.catalogRevision(), + unsigned.pointerVersion(), + unsigned.evaluatedAt(), + unsigned.connectScopeExpiresAt(), + AccountJoinDigest.scope(unsigned)); + } + + private static ConnectScopeEvidence scopeEvidence( + String targetClass, long tenantId, String worldSlug) { + VerifiedJoinScope scope = verifiedScope(); + return new ConnectScopeEvidence( + AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID), + ACCOUNT_ID, + targetClass, + tenantId, + REALM_ID, + worldSlug, + REALM_SLUG, + "namespace-prod", + "SHARED", + 9001L, + 12L, + 8L, + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.snapshotDigest()); + } + + private static JoinMembershipProof activeJoinMembership() { + return new JoinMembershipProof( + MEMBERSHIP_ID, + ACCOUNT_ID, + TENANT_ID, + true, + "ACTIVE", + MEMBERSHIP_VERSION, + MEMBERSHIP_AUTHORITY_GENERATION, + "EXPLICIT_JOIN"); + } + + private static AccountAuditEnvelope joinAuditEnvelope( + String payloadWorldSlug, long payloadTenantId, String digest) { + String payload = + "{\"accountId\":" + + ACCOUNT_ID + + ",\"tenantId\":" + + payloadTenantId + + ",\"worldSlug\":\"" + + payloadWorldSlug + + "\",\"realmSlug\":\"" + + REALM_SLUG + + "\",\"membershipVersion\":" + + MEMBERSHIP_VERSION + + ",\"requestId\":\"" + + REQUEST_ID + + "\"}"; + return new AccountAuditEnvelope( + joinAuditEventId(), + "tenant", + TENANT_ID, + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + NOW.minusSeconds(10), + 1, + 1, + digest, + payload); + } + + private static UUID joinAuditEventId() { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + REQUEST_ID).getBytes(StandardCharsets.UTF_8)); + } + + private static String correctPayloadDigest() { + return AccountAuditDigest.ofPayload( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, "unused").payload()); + } + + private static String sha256(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } + + private static double reconciliationCounter(Fixture fixture, String result) { + return fixture + .meterRegistry + .get("account.join.reconciliation.operations") + .tag("result", result) + .counter() + .count(); + } + + private record Fixture( + AccountJoinReconciliationService service, + AccountJoinOperationRepository joinOperations, + AccountConnectScopeRepository connectScopes, + AccountTenantMembershipRepository memberships, + AccountAuditOutboxRepository auditOutbox, + SimpleMeterRegistry meterRegistry) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 22ad57156d..ad03bd7c13 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -72,6 +72,11 @@ class AccountGrpcServiceTest { "spiffe://firemud/ns/test/sa/game-session-service", WORKLOAD_NAMESPACE, "game-session-service"); + private static final GrpcPeerIdentity SOCIAL_GROUPS_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/social-groups-service", + WORKLOAD_NAMESPACE, + "social-groups-service"); private static PlayerExecutionContext validPlayerContext() { return PlayerExecutionContext.newBuilder() @@ -661,23 +666,28 @@ void getProfileReturnsProfile() throws Exception { .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( 1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), - new StreamObserver() { - @Override - public void onNext(GetProfileResponse value) { - ref.set(value); - } + SessionContext.setContext("2", List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + new StreamObserver() { + @Override + public void onNext(GetProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertEquals( "demo", @@ -699,23 +709,28 @@ public void onCompleted() {} void getProfileRejectsZeroAccountIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("0").build(), - new StreamObserver() { - @Override - public void onNext(GetProfileResponse value) { - ref.set(value); - } + SessionContext.setContext("2", List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("0").build(), + new StreamObserver() { + @Override + public void onNext(GetProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -723,6 +738,81 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } + @Test + void getProfileRejectsMissingOrWrongPeerBeforeLookup() { + List rejectedPeers = + java.util.Arrays.asList( + null, + GAME_SESSION_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/social-groups-service", + "other", + "social-groups-service")); + + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext("2", List.of("player"), Map.of()); + + withPeer( + peer, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + } + + @Test + void getProfileRejectsInternalOrCrossAccountSubjectBeforeLookup() { + for (boolean internalService : List.of(false, true)) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext( + internalService ? "2" : "3", List.of(), Map.of(), internalService, "", ""); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } + + @Test + void getProfileRejectsMissingCallerAccountSubjectBeforeLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.clear(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void listPresenceVisibilityPoliciesMapsPersistedPolicies() { PingService pingService = Mockito.mock(PingService.class); @@ -732,17 +822,21 @@ void listPresenceVisibilityPoliciesMapsPersistedPolicies() { Map.of( 2L, ProfilePresenceVisibilityPolicy.PRIVATE, 3L, ProfilePresenceVisibilityPolicy.HIDDEN_STAFF)); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .addAccountIds("3") - .addAccountIds("2") - .build(), - observer); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("2") + .addAccountIds("3") + .addAccountIds("2") + .build(), + observer)); assertNotNull(observer.response()); assertEquals(2, observer.response().getPoliciesCount()); @@ -760,19 +854,58 @@ void listPresenceVisibilityPoliciesMapsPersistedPolicies() { Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L, 3L)); } + @Test + void listPresenceVisibilityPoliciesRejectsMissingOrWrongPeerBeforeLookup() { + List rejectedPeers = + java.util.Arrays.asList( + null, + GAME_SESSION_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/social-groups-service", + "other", + "social-groups-service")); + + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = + new RecordingObserver<>(); + + withPeer( + peer, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("2") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + } + @Test void listPresenceVisibilityPoliciesRejectsNonPositiveAccountId() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("0") - .build(), - observer); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("0") + .build(), + observer)); assertNotNull(observer.response()); assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); @@ -786,18 +919,22 @@ void listPresenceVisibilityPoliciesRejectsNonPositiveAccountId() { void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenThrow(new IllegalArgumentException("Tenant not found")); RecordingObserver notFoundObserver = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - notFoundObserver); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("2") + .build(), + notFoundObserver)); assertEquals("NOT_FOUND", notFoundObserver.response().getError().getCode()); assertTrue(notFoundObserver.completed()); @@ -808,12 +945,15 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors .thenThrow(new IllegalStateException("Policy lookup unavailable")); RecordingObserver internalObserver = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - internalObserver); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds("2") + .build(), + internalObserver)); assertEquals("INTERNAL", internalObserver.response().getError().getCode()); assertTrue(internalObserver.completed()); @@ -821,295 +961,440 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors } @Test - void getTenantMembershipForRuntimeReturnsResponse() { + void getTenantMembershipForRuntimeRejectsMissingPeerBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) - .thenReturn( - new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantMembershipForRuntimeResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - @Override - public void onCompleted() {} - }); + withPeer( + null, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); - assertNotNull(ref.get()); - assertEquals("2", ref.get().getAccountId()); - assertTrue(ref.get().getMembershipExists()); - assertTrue(ref.get().getGameplayAdmissionAllowed()); - assertEquals(44L, ref.get().getMembershipVersion()); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); } @Test - void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed() { + void getTenantMembershipForRuntimeFailsClosedWithExactPeerBecauseCallerContextIsMissing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) - .thenReturn( - new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, false, true, 44L, "MISSING", 0L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); + SessionContext.clear(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); - assertNotNull(observer.response()); - assertFalse(observer.response().getMembershipExists()); - assertTrue(observer.response().getGameplayAdmissionAllowed()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService); } @Test - void getTenantMembershipForRuntimeRejectsZeroTenantIdBeforeLookup() { + void getTenantMembershipForRuntimeRejectsWrongPeerBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("0") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantMembershipForRuntimeResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - @Override - public void onCompleted() {} - }); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("0") + .setRequestId("req-1") + .build(), + observer)); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); Mockito.verifyNoInteractions(accountService); } @Test - void getRealmAccessGrantForRuntimeRejectsZeroAccountIdBeforeLookup() { + void getTenantMembershipForRuntimeFailsClosedForCrossAccountOrTenantIds() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext("2", List.of("player"), Map.of("1", List.of("player"))); + List crossTargetRequests = + List.of( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("3") + .setTenantId("1") + .setRequestId("cross-account") + .build(), + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("9") + .setRequestId("cross-tenant") + .build()); + + for (GetTenantMembershipForRuntimeRequest request : crossTargetRequests) { + RecordingObserver observer = new RecordingObserver<>(); + withPeer(GAME_SESSION_PEER, () -> service.getTenantMembershipForRuntime(request, observer)); + + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } - AtomicReference ref = new AtomicReference<>(); - service.getRealmAccessGrantForRuntime( - GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId("0") - .setTenantId("1") - .setWorldSlug("demo") - .setRealmSlug("production") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetRealmAccessGrantForRuntimeResponse value) { - ref.set(value); - } + @Test + void getRealmAccessGrantForRuntimeRejectsMissingOrWrongPeerBeforeLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List rejectedPeers = + java.util.Arrays.asList( + null, + SOCIAL_GROUPS_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); - @Override - public void onError(Throwable t) {} + for (GrpcPeerIdentity peer : rejectedPeers) { + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + peer, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("req-1") + .build(), + observer)); - @Override - public void onCompleted() {} - }); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + @Test + void getRealmAccessGrantForRuntimeFailsClosedForCrossAccountOrTenantIds() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext("2", List.of("player"), Map.of("1", List.of("player"))); + List crossTargetRequests = + List.of( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("3") + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("cross-account") + .build(), + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("2") + .setTenantId("9") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("cross-tenant") + .build()); + + for (GetRealmAccessGrantForRuntimeRequest request : crossTargetRequests) { + RecordingObserver observer = new RecordingObserver<>(); + withPeer(GAME_SESSION_PEER, () -> service.getRealmAccessGrantForRuntime(request, observer)); + + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } } @Test - void getTenantEntitlementsForRuntimeReturnsResponse() { + void getTenantEntitlementsForRuntimeFailsClosedWithExactPeerBeforeRead() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-2")) - .thenReturn( - new net.firedevops.firemud.accountservice.dto.RuntimeEntitlementsDto( - 1L, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.clear(); - AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-2") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-2") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } - @Override - public void onCompleted() {} - }); + @Test + void getTenantEntitlementsForRuntimeRejectsMissingOrWrongPeerBeforeRead() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List rejectedPeers = + java.util.Arrays.asList( + null, + SOCIAL_GROUPS_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); - assertNotNull(ref.get()); - assertEquals("1", ref.get().getTenantId()); - assertTrue(ref.get().getGameplayAvailable()); - assertTrue(ref.get().getAllowPublicJoin()); - assertEquals(19L, ref.get().getEntitlementVersion()); + for (GrpcPeerIdentity peer : rejectedPeers) { + RecordingObserver observer = + new RecordingObserver<>(); + withPeer( + peer, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-2") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } } @Test - void getTenantEntitlementsForRuntimeReturnsUnavailableAuthorityError() { + void getTenantEntitlementsForRuntimeFailsClosedForCrossTenantTarget() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-ambiguous")) - .thenThrow( - new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Tenant entitlement authority is missing or ambiguous; retry later")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext("2", List.of("player"), Map.of("1", List.of("player"))); + RecordingObserver observer = new RecordingObserver<>(); - AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-ambiguous") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("9") + .setRequestId("cross-tenant") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } - @Override - public void onCompleted() {} - }); + @Test + void updateProfileAllowsExactSocialPeerWithMatchingSubject() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - assertNotNull(ref.get()); - assertTrue(ref.get().hasError()); - assertEquals("ENTITLEMENT_UNAVAILABLE", ref.get().getError().getCode()); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext("2", List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertTrue(observer.response().getSuccess()); + assertTrue(observer.completed()); + org.mockito.ArgumentCaptor + captor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.dto.UpdateProfileRequest.class); + Mockito.verify(accountService).updateProfile(captor.capture()); + assertEquals(1L, captor.getValue().tenantId()); + assertEquals(2L, captor.getValue().accountId()); + assertEquals("demo", captor.getValue().displayName()); } @Test - void getTenantEntitlementsForRuntimeRejectsZeroTenantIdBeforeLookup() { + void updateProfileMapsServiceRuntimeFailuresToApplicationErrors() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + Mockito.doThrow(new IllegalArgumentException("bad")) + .when(accountService) + .updateProfile(Mockito.any()); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext("2", List.of("player"), Map.of()); - AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("0") - .setRequestId("req-2") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verify(accountService).updateProfile(Mockito.any()); + } - @Override - public void onCompleted() {} - }); + @Test + void updateProfileRejectsMissingOrWrongPeerBeforeUpdate() { + List rejectedPeers = + java.util.Arrays.asList( + null, + GAME_SESSION_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/social-groups-service", + "other", + "social-groups-service")); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext("2", List.of("player"), Map.of()); + + withPeer( + peer, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertFalse(observer.response().getSuccess()); + Mockito.verifyNoInteractions(accountService); + } } @Test - void updateProfileErrorReturnsDetail() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.updateProfile(Mockito.any())) - .thenThrow(new IllegalArgumentException("bad")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + void updateProfileRejectsCrossAccountOrInternalSubjectBeforeUpdate() { + for (boolean internalService : List.of(false, true)) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext( + internalService ? "2" : "3", List.of(), Map.of(), internalService, "", ""); - AtomicReference ref = new AtomicReference<>(); - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId("2") - .setProfileJson( - "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - new StreamObserver() { - @Override - public void onNext(UpdateProfileResponse value) { - ref.set(value); - } + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertFalse(observer.response().getSuccess()); + Mockito.verifyNoInteractions(accountService); + } + } - @Override - public void onCompleted() {} - }); + @Test + void updateProfileRejectsMissingCallerAccountSubjectBeforeUpdate() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.clear(); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertFalse(observer.response().getSuccess()); + Mockito.verifyNoInteractions(accountService); } @Test void updateProfileRejectsZeroTenantIdBeforeUpdate() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setProfileJson( - "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - new StreamObserver() { - @Override - public void onNext(UpdateProfileResponse value) { - ref.set(value); - } + SessionContext.setContext("2", List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("0") + .setAccountId("2") + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + new StreamObserver() { + @Override + public void onNext(UpdateProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -1118,11 +1403,9 @@ public void onCompleted() {} } @Test - void exportAccountErrorReturnsDetail() { + void exportAccountFailsClosedWithoutAuthorizedInternalCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.exportAccountData(2L)) - .thenThrow(new IllegalArgumentException("missing")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -1142,11 +1425,12 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("NOT_FOUND", ref.get().getError().getCode()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); } @Test - void exportAccountRejectsZeroAccountIdBeforeLookup() { + void exportAccountFailsClosedBeforeValidatingRequestWithoutCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -1168,20 +1452,19 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); Mockito.verifyNoInteractions(accountService); } @Test - void exportTenantDataRejectsZeroTenantIdBeforeLookup() { + void exportTenantDataFailsClosedWithoutAuthorizedInternalCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); service.exportTenantData( - ExportTenantDataRequest.newBuilder().setTenantId("0").setAccountId("2").build(), + ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId("2").build(), new StreamObserver() { @Override public void onNext(ExportTenantDataResponse value) { @@ -1196,13 +1479,12 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); Mockito.verifyNoInteractions(accountService); } @Test - void deleteAccountSuccess() { + void deleteAccountFailsClosedBeforeServiceMutation() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -1225,7 +1507,9 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertTrue(ref.get().getSuccess()); + assertFalse(ref.get().getSuccess()); + assertEquals("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); } @Test @@ -1259,7 +1543,7 @@ public void onCompleted() {} } @Test - void linkExternalAccountSuccess() { + void linkExternalAccountFailsClosedWithoutAuthorizedInternalCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -1287,11 +1571,13 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertTrue(ref.get().getSuccess()); + assertFalse(ref.get().getSuccess()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); } @Test - void linkExternalAccountRejectsZeroTenantIdBeforeLink() { + void linkExternalAccountFailsClosedBeforeValidatingRequestWithoutCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -1320,13 +1606,12 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); Mockito.verifyNoInteractions(accountService); } @Test - void requestEmailVerificationRejectsZeroAccountIdBeforeDispatch() { + void requestEmailVerificationFailsClosedWithoutAuthorizedInternalCaller() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -1335,7 +1620,7 @@ void requestEmailVerificationRejectsZeroAccountIdBeforeDispatch() { new AtomicReference<>(); service.requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.newBuilder() - .setAccountId("0") + .setAccountId("2") .build(), new StreamObserver() { @Override @@ -1353,8 +1638,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); Mockito.verifyNoInteractions(accountService); } 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 0de1da7673..430bc72acb 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 @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -669,7 +670,7 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { } @Test - void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { + void expiredPersistedPendingJoinRemainsPendingWithoutAuthorityOrMembershipReads() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -731,9 +732,17 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans .toString(); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + request.requestId(), expiredScope.accountId(), expiredScope.tenantId(), expiredScope.realmId(), + expiredScope.worldSlug(), + expiredScope.realmSlug(), + expiredScope.playableStateNamespaceId(), + expiredScope.playableStateScope(), + expiredScope.gameInstanceId(), + expiredScope.catalogRevision(), + expiredScope.pointerVersion(), callerBinding, net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), expiredScope.snapshotDigest(), @@ -751,20 +760,26 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( request.requestId(), expiredScope, callerBinding), "ENTITLEMENT_UNAVAILABLE", - "UNAVAILABLE")); + "UNAVAILABLE", + 0, + null, + null, + java.time.Instant.now())); JoinPublicProductionResult expiredRetry = service.joinPublicProduction(bootstrap.bootstrapToken(), request); - JoinPublicProductionResult terminalReadback = + JoinPublicProductionResult repeatedExpiredRetry = service.joinPublicProduction(bootstrap.bootstrapToken(), request); assertFalse(expiredRetry.success()); - assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); - assertFalse(terminalReadback.success()); - assertTrue(terminalReadback.replayed()); - assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); + assertFalse(expiredRetry.replayed()); + assertEquals("AUTH_UNAVAILABLE", expiredRetry.outcomeCode()); + assertFalse(repeatedExpiredRetry.success()); + assertFalse(repeatedExpiredRetry.replayed()); + assertEquals("AUTH_UNAVAILABLE", repeatedExpiredRetry.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); verifyNoInteractions( subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); } @@ -792,9 +807,17 @@ void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { VerifiedJoinScope scope = retainedScope.get(); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + "join-global-collision-1", 12L, scope.tenantId(), scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), "different-caller", net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), scope.snapshotDigest(), @@ -812,7 +835,11 @@ void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( "join-global-collision-1", scope, "different-caller"), null, - "NOT_EVALUATED")); + "NOT_EVALUATED", + 0, + null, + null, + java.time.Instant.now())); AuthenticationException conflict = assertThrows( @@ -897,9 +924,17 @@ private void retainJoinEvidence( String intentDigest = invocation.getArgument(3); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + requestId, scope.accountId(), scope.tenantId(), scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), callerBinding, net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( scope.connectScopeId()), @@ -917,7 +952,11 @@ private void retainJoinEvidence( 1, intentDigest, null, - "NOT_EVALUATED")); + "NOT_EVALUATED", + 0, + null, + null, + java.time.Instant.now())); return true; }) .when(accountJoinOperationRepository) @@ -931,9 +970,17 @@ private void retainJoinEvidence( var pending = retainedOperation.get(); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + pending.requestId(), pending.accountId(), pending.tenantId(), pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -950,7 +997,11 @@ private void retainJoinEvidence( pending.intentDigestVersion(), pending.intentDigest(), null, - "AVAILABLE")); + "AVAILABLE", + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt())); return null; }) .when(accountJoinOperationRepository) @@ -965,9 +1016,17 @@ private void retainJoinEvidence( String availability = invocation.getArgument(1); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + pending.requestId(), pending.accountId(), pending.tenantId(), pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -986,7 +1045,11 @@ private void retainJoinEvidence( pending.intentDigestVersion(), pending.intentDigest(), invocation.getArgument(2), - availability)); + availability, + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt())); return null; }) .when(accountJoinOperationRepository) @@ -999,9 +1062,17 @@ private void retainJoinEvidence( var pending = retainedOperation.get(); retainedOperation.set( new AccountJoinOperationRepository.JoinOperation( + pending.requestId(), pending.accountId(), pending.tenantId(), pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), pending.callerBinding(), pending.scopeTokenHash(), pending.connectScopeDigest(), @@ -1018,7 +1089,11 @@ private void retainJoinEvidence( pending.intentDigestVersion(), pending.intentDigest(), null, - pending.lastAttemptAuthorityAvailability())); + pending.lastAttemptAuthorityAvailability(), + pending.reconciliationAttemptCount(), + pending.lastReconciliationAttemptAt(), + pending.lastReconciliationAttemptReason(), + pending.nextReconciliationAttemptAt())); return null; }) .when(accountJoinOperationRepository) @@ -3896,24 +3971,27 @@ void exportAccountDataIncludesProfilesAcrossTenants() { } @Test - void exportTenantDataRequiresTenantMembershipOrProfile() { - Account account = new Account(); - account.setId(2L); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(profileRepository.findByAccountIdAndTenantId(2L, 7L)).thenReturn(Optional.empty()); - when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 7L)).thenReturn(false); + void exportTenantDataFailsClosedBeforeReadingAccountOrTenantData() { + org.springframework.web.server.ResponseStatusException exception = + assertThrows( + org.springframework.web.server.ResponseStatusException.class, + () -> service.exportTenantData(7L, 2L)); - assertThrows(IllegalArgumentException.class, () -> service.exportTenantData(7L, 2L)); + assertEquals(org.springframework.http.HttpStatus.NOT_IMPLEMENTED, exception.getStatusCode()); + verifyNoInteractions(accountRepository, profileRepository, accountTenantMembershipRepository); } - @Test - void deleteAccountRefusesNonterminalSubscription() { + @ParameterizedTest + @CsvSource({"active, false", "canceled, true"}) + void deleteAccountFailsClosedWithoutMutationForAnySubscriptionState( + String status, boolean terminal) { Account account = new Account(); account.setId(2L); Subscription subscription = new Subscription(); - subscription.setStatus("active"); + subscription.setStatus(status); + if (terminal) { + subscription.setEndedAt(java.time.LocalDateTime.now()); + } subscription.setAccount(account); subscription.setTenantId(7L); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); @@ -3921,32 +3999,41 @@ void deleteAccountRefusesNonterminalSubscription() { AccountLifecycleException ex = assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); - assertEquals("ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", ex.getCode()); + assertEquals("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", ex.getCode()); + verify(accountRepository).findById(2L); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .delete(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions( + accountJoinOperationRepository, + emailVerificationTokenRepository, + passwordResetTokenRepository, + accountRealmAccessGrantRepository, + externalAccountRepository, + paymentTransactionRepository, + subscriptionRepository, + profileRepository, + accountTenantMembershipRepository); } @Test - void deleteAccountRemovesAccountOwnedRowsAfterTerminalSubscriptions() { - Account account = new Account(); - account.setId(2L); - Subscription subscription = new Subscription(); - subscription.setStatus("canceled"); - subscription.setEndedAt(java.time.LocalDateTime.now()); - subscription.setAccount(account); - subscription.setTenantId(7L); - when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByAccountId(2L)).thenReturn(java.util.List.of(subscription)); + void deleteAccountStillRequiresAnExistingAccountBeforeReturningUnavailable() { + when(accountRepository.findById(404L)).thenReturn(Optional.empty()); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, () -> service.deleteAccount(404L)); - service.deleteAccount(2L); - - org.mockito.Mockito.verify(emailVerificationTokenRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(passwordResetTokenRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(accountRealmAccessGrantRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(externalAccountRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(paymentTransactionRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(subscriptionRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(profileRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(accountTenantMembershipRepository).deleteByAccountId(2L); - org.mockito.Mockito.verify(accountRepository).delete(account); + assertEquals("Account not found", exception.getMessage()); + verify(accountRepository).findById(404L); + verifyNoInteractions( + accountJoinOperationRepository, + emailVerificationTokenRepository, + passwordResetTokenRepository, + accountRealmAccessGrantRepository, + externalAccountRepository, + paymentTransactionRepository, + subscriptionRepository, + profileRepository, + accountTenantMembershipRepository); } @Test @@ -3978,6 +4065,94 @@ void requestPasswordResetUnknownEmailIsNeutral() { passwordResetTokenRepository, emailService, notificationService); } + @Test + void completePasswordResetConsumesTokenBeforeUpdatingPassword() { + Account account = new Account(); + account.setId(1L); + account.setPasswordHash("old-hash"); + net.firedevops.firemud.accountservice.entity.PasswordResetToken token = + new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); + token.setId(7L); + token.setAccount(account); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); + when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(passwordResetTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) + .thenReturn(true); + + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "tok", "new-password")); + + assertFalse("old-hash".equals(account.getPasswordHash())); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(passwordResetTokenRepository, accountRepository); + order + .verify(passwordResetTokenRepository) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); + order.verify(accountRepository).save(account); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .delete(token); + } + + @Test + void completePasswordResetRejectsAlreadyConsumedTokenBeforePasswordMutation() { + Account account = new Account(); + account.setPasswordHash("old-hash"); + net.firedevops.firemud.accountservice.entity.PasswordResetToken token = + new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); + token.setId(7L); + token.setAccount(account); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); + when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(passwordResetTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) + .thenReturn(false); + + assertThrows( + IllegalArgumentException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "tok", "new-password"))); + + assertEquals("old-hash", account.getPasswordHash()); + org.mockito.Mockito.verifyNoInteractions(accountRepository); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .delete(token); + } + + @Test + void completePasswordResetRejectsExpiredTokenBeforeConsumption() { + net.firedevops.firemud.accountservice.entity.PasswordResetToken token = + new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); + token.setId(7L); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().minusSeconds(1)); + when(passwordResetTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "tok", "new-password"))); + + assertEquals("Token expired", exception.getMessage()); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); + org.mockito.Mockito.verifyNoInteractions(accountRepository); + } + @Test void sendUsernameReminderEmailsUsername() { Account account = new Account(); @@ -4081,14 +4256,78 @@ void requestEmailVerificationByUnknownEmailIsNeutral() { void verifyEmailSetsFlag() { Account account = new Account(); EmailVerificationToken token = new EmailVerificationToken(); + token.setId(9L); token.setAccount(account); + token.setToken("tok"); token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(emailVerificationTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) + .thenReturn(true); service.verifyEmail(new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok")); assertTrue(account.isEmailVerified()); - org.mockito.Mockito.verify(emailVerificationTokenRepository).delete(token); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(emailVerificationTokenRepository, accountRepository); + order + .verify(emailVerificationTokenRepository) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); + order.verify(accountRepository).save(account); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .delete(token); + } + + @Test + void verifyEmailRejectsAlreadyConsumedTokenBeforeMarkingAccountVerified() { + Account account = new Account(); + EmailVerificationToken token = new EmailVerificationToken(); + token.setId(9L); + token.setAccount(account); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); + when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + when(emailVerificationTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))) + .thenReturn(false); + + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + + assertFalse(account.isEmailVerified()); + org.mockito.Mockito.verifyNoInteractions(accountRepository); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .delete(token); + } + + @Test + void verifyEmailRejectsExpiredTokenBeforeConsumption() { + EmailVerificationToken token = new EmailVerificationToken(); + token.setId(9L); + token.setToken("tok"); + token.setExpiresAt(java.time.LocalDateTime.now().minusSeconds(1)); + when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + + assertEquals("Token expired", exception.getMessage()); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class)); + org.mockito.Mockito.verifyNoInteractions(accountRepository); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java index ebe64f87bf..7348981974 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java @@ -6,7 +6,8 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.util.concurrent.atomic.AtomicReference; +import java.util.ArrayList; +import java.util.List; import net.firedevops.firemud.account.v1.CreateDonationRequest; import net.firedevops.firemud.account.v1.CreateDonationResponse; import net.firedevops.firemud.account.v1.CreatePaymentIntentRequest; @@ -15,41 +16,33 @@ import net.firedevops.firemud.account.v1.CreateSubscriptionResponse; import net.firedevops.firemud.account.v1.RefundPaymentRequest; import net.firedevops.firemud.account.v1.RefundPaymentResponse; -import net.firedevops.firemud.accountservice.dto.PaymentIntentDto; import net.firedevops.firemud.accountservice.service.PaymentService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class PaymentGrpcServiceTest { @Test - void createPaymentIntentReturnsResponse() { + void createPaymentIntentFailsClosedForRepeatedRequestsWithoutCallingService() { PaymentService paymentService = Mockito.mock(PaymentService.class); - Mockito.when(paymentService.createPaymentIntent(1L, 2L, 500L)) - .thenReturn(new PaymentIntentDto(10L, 1L, 2L, 500L, 25L, 475L, "USD", "secret", false)); PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.createPaymentIntent( + List responses = new ArrayList<>(); + CreatePaymentIntentRequest request = CreatePaymentIntentRequest.newBuilder() .setTenantId("1") .setAccountId("2") .setAmountCents(500) - .build(), - new StreamObserver() { - @Override - public void onNext(CreatePaymentIntentResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + .build(); - @Override - public void onCompleted() {} - }); + service.createPaymentIntent(request, collecting(responses)); + service.createPaymentIntent(request, collecting(responses)); - assertEquals("10", ref.get().getIntentId()); - assertEquals("secret", ref.get().getClientSecret()); + assertEquals(2, responses.size()); + for (CreatePaymentIntentResponse response : responses) { + assertNotNull(response); + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals("CreatePaymentIntent is unavailable", response.getError().getMessage()); + } + Mockito.verifyNoInteractions(paymentService); } @Test @@ -57,121 +50,63 @@ void createSubscriptionReturnsFailedPreconditionWithoutCallingService() { PaymentService paymentService = Mockito.mock(PaymentService.class); PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); - AtomicReference ref = new AtomicReference<>(); - service.createSubscription( - CreateSubscriptionRequest.newBuilder() - .setTenantId("1") - .setAccountId("2") - .setPlanId("plan") - .build(), - new StreamObserver() { - @Override - public void onNext(CreateSubscriptionResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); - assertEquals("Subscription creation is unavailable", ref.get().getError().getMessage()); + CreateSubscriptionResponse response = + invoke( + service, + CreateSubscriptionRequest.newBuilder() + .setTenantId("1") + .setAccountId("2") + .setPlanId("plan") + .build()); + + assertNotNull(response); + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals("Subscription creation is unavailable", response.getError().getMessage()); Mockito.verifyNoInteractions(paymentService); } @Test - void createDonationReturnsResponse() { + void createDonationFailsClosedForRepeatedRequestsWithoutCallingService() { PaymentService paymentService = Mockito.mock(PaymentService.class); - Mockito.when(paymentService.createDonation(1L, 2L, 100L)) - .thenReturn(new PaymentIntentDto(11L, 1L, 2L, 100L, 5L, 95L, "USD", "donate", true)); PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.createDonation( + List responses = new ArrayList<>(); + CreateDonationRequest request = CreateDonationRequest.newBuilder() .setTenantId("1") .setAccountId("2") .setAmountCents(100) - .build(), - new StreamObserver() { - @Override - public void onNext(CreateDonationResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + .build(); - @Override - public void onCompleted() {} - }); + service.createDonation(request, collecting(responses)); + service.createDonation(request, collecting(responses)); - assertEquals("11", ref.get().getIntentId()); - assertEquals("donate", ref.get().getClientSecret()); - } - - @Test - void refundPaymentRuntimeFailureReturnsInternalErrorDetail() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - Mockito.doThrow(new IllegalStateException("boom")).when(paymentService).refundPayment(1L, 9L); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); - - AtomicReference ref = - new AtomicReference<>(); - service.refundPayment( - net.firedevops.firemud.account.v1.RefundPaymentRequest.newBuilder() - .setTenantId("1") - .setPaymentId("9") - .build(), - new StreamObserver<>() { - @Override - public void onNext(net.firedevops.firemud.account.v1.RefundPaymentResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INTERNAL", ref.get().getError().getCode()); + assertEquals(2, responses.size()); + for (CreateDonationResponse response : responses) { + assertNotNull(response); + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals("CreateDonation is unavailable", response.getError().getMessage()); + } + Mockito.verifyNoInteractions(paymentService); } @Test - void createPaymentIntentRejectsZeroTenantIdBeforeCreate() { + void refundPaymentFailsClosedForRepeatedRequestsWithoutCallingService() { PaymentService paymentService = Mockito.mock(PaymentService.class); PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.createPaymentIntent( - CreatePaymentIntentRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setAmountCents(500) - .build(), - new StreamObserver<>() { - @Override - public void onNext(CreatePaymentIntentResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + List responses = new ArrayList<>(); + RefundPaymentRequest request = + RefundPaymentRequest.newBuilder().setTenantId("1").setPaymentId("9").build(); + + service.refundPayment(request, collecting(responses)); + service.refundPayment(request, collecting(responses)); + + assertEquals(2, responses.size()); + for (RefundPaymentResponse response : responses) { + assertNotNull(response); + assertFalse(response.getSuccess()); + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals("RefundPayment is unavailable", response.getError().getMessage()); + } Mockito.verifyNoInteractions(paymentService); } @@ -180,88 +115,41 @@ void createSubscriptionRejectsZeroAccountIdBeforeCreate() { PaymentService paymentService = Mockito.mock(PaymentService.class); PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); - AtomicReference ref = new AtomicReference<>(); - service.createSubscription( - CreateSubscriptionRequest.newBuilder() - .setTenantId("1") - .setAccountId("0") - .setPlanId("plan") - .build(), - new StreamObserver<>() { - @Override - public void onNext(CreateSubscriptionResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + CreateSubscriptionResponse response = + invoke( + service, + CreateSubscriptionRequest.newBuilder() + .setTenantId("1") + .setAccountId("0") + .setPlanId("plan") + .build()); + + assertNotNull(response); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals("accountId must be positive", response.getError().getMessage()); Mockito.verifyNoInteractions(paymentService); } - @Test - void createDonationRejectsZeroTenantIdBeforeCreate() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.createDonation( - CreateDonationRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setAmountCents(100) - .build(), - new StreamObserver<>() { - @Override - public void onNext(CreateDonationResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + private static StreamObserver collecting(List responses) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + responses.add(value); + } - @Override - public void onCompleted() {} - }); + @Override + public void onError(Throwable t) {} - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(paymentService); + @Override + public void onCompleted() {} + }; } - @Test - void refundPaymentRejectsZeroPaymentIdBeforeRefund() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.refundPayment( - RefundPaymentRequest.newBuilder().setTenantId("1").setPaymentId("0").build(), - new StreamObserver<>() { - @Override - public void onNext(RefundPaymentResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("paymentId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(paymentService); + private static CreateSubscriptionResponse invoke( + PaymentGrpcService service, CreateSubscriptionRequest request) { + List responses = new ArrayList<>(); + service.createSubscription(request, collecting(responses)); + assertEquals(1, responses.size()); + return responses.getFirst(); } } From 12a1721b913b9f8cc60d936d2facd5a2b808f25b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 19:08:55 +1200 Subject: [PATCH 18/55] Keep JOIN PostgreSQL fixture username within schema limit --- .../AccountJoinReconciliationPostgresIntegrationTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index 7c5984f5d2..f67c20479b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -336,14 +336,14 @@ private JoinPublicProductionResult join(JoinFixture fixture) { private JoinFixture fixture(String subscriptionStatus) { String suffix = UUID.randomUUID().toString(); - String requestId = "join-reconcile-" + suffix; + String requestId = "join-rec-" + suffix; long tenantId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; long accountId = Objects.requireNonNull( dsl.resultQuery( "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", - "join-reconcile-" + suffix, - "join-reconcile-" + suffix + "@example.com", + "join-rec-" + suffix, + "join-rec-" + suffix + "@example.com", "test-hash") .fetchOne(0, Long.class)); dsl.execute( From d2be23ceabdef5c92864bc738430dfb4e545055c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 28 Sep 2026 01:12:40 +1300 Subject: [PATCH 19/55] Reconcile JOIN child migration ordering and routing fixture --- .../accountservice/service/impl/AccountServiceImplTest.java | 6 ++++++ ...ision.sql => V5__separate_gameplay_catalog_revision.sql} | 0 ...identity.sql => V6__persist_gameplay_realm_identity.sql} | 0 3 files changed, 6 insertions(+) rename services/game-session-service/src/main/resources/db/migration/{V3__separate_gameplay_catalog_revision.sql => V5__separate_gameplay_catalog_revision.sql} (100%) rename services/game-session-service/src/main/resources/db/migration/{V4__persist_gameplay_realm_identity.sql => V6__persist_gameplay_realm_identity.sql} (100%) 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 d6bb874921..2c61f502d4 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 @@ -2965,6 +2965,9 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis .setDisplayName("Private Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(false) @@ -2982,6 +2985,9 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis .setRealmDisplayName("Private Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(false) diff --git a/services/game-session-service/src/main/resources/db/migration/V3__separate_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V3__separate_gameplay_catalog_revision.sql rename to services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql diff --git a/services/game-session-service/src/main/resources/db/migration/V4__persist_gameplay_realm_identity.sql b/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V4__persist_gameplay_realm_identity.sql rename to services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql From f8d45fddfb11f13307064f6a20336a96567e753a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 28 Sep 2026 01:51:53 +1300 Subject: [PATCH 20/55] Provide scoped local Compose workload identities --- build.gradle.kts | 2 +- dev-tools/certs/README.md | 6 +- dev-tools/certs/clean-dev-certs.sh | 117 +++++++++- dev-tools/certs/ensure-dev-certs.sh | 147 +++++++++++- dev-tools/certs/generate-dev-certs.sh | 15 +- ...ocal-compose-workload-identity-contract.sh | 219 ++++++++++++++++++ docker/README.md | 6 +- .../docker-compose.local-images.override.yml | 32 ++- docker/docker-compose.override.yml | 36 ++- 9 files changed, 552 insertions(+), 28 deletions(-) create mode 100644 dev-tools/tests/local-compose-workload-identity-contract.sh diff --git a/build.gradle.kts b/build.gradle.kts index fd4edc976a..b84a5b0d7a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -511,7 +511,7 @@ tasks.register("buildDockerImagesSmoke") { } tasks.register("generateDevCerts") { - commandLine("bash", "dev-tools/certs/generate-dev-certs.sh") + commandLine("bash", "dev-tools/certs/ensure-dev-certs.sh") } tasks.register("ensureLocalComposeEnv") { diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index e91e114763..05e8db2471 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -7,7 +7,7 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only publication leaf with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only leaf with the exact SPIFFE URI and service DNS SANs. The generic generator keeps workload private keys mode `0600`; `ensure-dev-certs.sh` changes permissions only on its ignored local Compose runtime projection so non-root containers can read their own local keys. Hosted preview and dev-demo do not use this signing mode for runtime issuance; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for non-publication workloads and consume only cert-manager's five runtime-facing `firemud-grpc-` leaf Secrets. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. -- `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. -- `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. +- `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local Compose entrypoints have the shared cert/key set and distinct Account, Game Session, and Social Groups workload identities before Compose boots. It validates the local CA, URI SAN, DNS SAN, and key pair, then creates `dev-tools/certs/local-runtime/` with only runtime-facing certificate material. The projection is ignored by Git and never contains `ca.key`; the host-side CA private key remains mode `0600`. +- `dev-tools/certs/clean-dev-certs.sh` removes only its listed top-level files and the known workload-leaf/runtime-projection filenames, then removes those directories only when empty. Unexpected files and symlinks are preserved and reported; cleanup does not recurse destructively. diff --git a/dev-tools/certs/clean-dev-certs.sh b/dev-tools/certs/clean-dev-certs.sh index 3139c39eb0..987d041e27 100644 --- a/dev-tools/certs/clean-dev-certs.sh +++ b/dev-tools/certs/clean-dev-certs.sh @@ -12,11 +12,60 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi +if [[ -L "$CERT_DIR" ]]; then + echo "Refusing symlink certificate directory; preserving it: $CERT_DIR" >&2 + exit 1 +fi if [ ! -d "$CERT_DIR" ]; then echo "No certificate directory at $CERT_DIR" exit 0 fi +removed_any=false +preserved_any=false + +report_preserved() { + echo "Preserving unexpected certificate entry: $1" >&2 + preserved_any=true +} + +remove_known_file() { + local path="$1" + if [[ -L "$path" ]]; then + report_preserved "$path (symlink)" + elif [[ -f "$path" ]]; then + rm -- "$path" + removed_any=true + elif [[ -e "$path" ]]; then + report_preserved "$path (not a regular file)" + fi +} + +report_directory_contents() { + local directory="$1" + local path + while IFS= read -r -d '' path; do + report_preserved "$path" + done < <(find "$directory" -mindepth 1 -print0) +} + +remove_empty_directory() { + local directory="$1" + if [[ -L "$directory" ]]; then + report_preserved "$directory (symlink directory)" + elif [[ -d "$directory" ]]; then + if rmdir -- "$directory" 2>/dev/null; then + removed_any=true + else + preserved_any=true + echo "Preserving non-empty or inaccessible certificate directory: $directory" >&2 + report_directory_contents "$directory" + fi + elif [[ -e "$directory" ]]; then + report_preserved "$directory (not a directory)" + fi +} + generated_files=( ca.crt ca.key @@ -32,16 +81,70 @@ generated_files=( dev-cert.cnf ) -removed_any=false for filename in "${generated_files[@]}"; do - if [ -e "$CERT_DIR/$filename" ]; then - rm -f "$CERT_DIR/$filename" - removed_any=true - fi + remove_known_file "$CERT_DIR/$filename" done +workloads=(account-service game-session-service social-groups-service) +workload_dir="$CERT_DIR/workloads" +if [[ -L "$workload_dir" ]]; then + report_preserved "$workload_dir (symlink directory)" +elif [[ -d "$workload_dir" ]]; then + for workload in "${workloads[@]}"; do + remove_known_file "$workload_dir/$workload.crt" + remove_known_file "$workload_dir/$workload.key" + done + remove_empty_directory "$workload_dir" +elif [[ -e "$workload_dir" ]]; then + report_preserved "$workload_dir (not a directory)" +fi + +runtime_root="$CERT_DIR/local-runtime" +runtime_files=(ca.crt client.crt client.key server.crt server.key dev-ca.pem dev-cert.pem dev-key.pem) +if [[ -L "$runtime_root" ]]; then + report_preserved "$runtime_root (symlink directory)" +elif [[ -d "$runtime_root" ]]; then + profiles=(default "${workloads[@]}") + for profile in "${profiles[@]}"; do + profile_dir="$runtime_root/$profile" + if [[ -L "$profile_dir" ]]; then + report_preserved "$profile_dir (symlink directory)" + continue + elif [[ ! -d "$profile_dir" ]]; then + if [[ -e "$profile_dir" ]]; then + report_preserved "$profile_dir (not a directory)" + fi + continue + fi + + if [[ "$profile" != "default" ]]; then + leaf_dir="$profile_dir/workloads" + if [[ -L "$leaf_dir" ]]; then + report_preserved "$leaf_dir (symlink directory)" + elif [[ -d "$leaf_dir" ]]; then + remove_known_file "$leaf_dir/$profile.crt" + remove_known_file "$leaf_dir/$profile.key" + remove_empty_directory "$leaf_dir" + elif [[ -e "$leaf_dir" ]]; then + report_preserved "$leaf_dir (not a directory)" + fi + fi + + for filename in "${runtime_files[@]}"; do + remove_known_file "$profile_dir/$filename" + done + remove_empty_directory "$profile_dir" + done + remove_empty_directory "$runtime_root" +elif [[ -e "$runtime_root" ]]; then + report_preserved "$runtime_root (not a directory)" +fi + if [ "$removed_any" = true ]; then - echo "Removed generated certificates from $CERT_DIR" -else + echo "Removed known generated certificates from $CERT_DIR" +fi +if [ "$preserved_any" = true ]; then + echo "Unexpected entries were preserved; inspect the paths reported above." +elif [ "$removed_any" = false ]; then echo "No generated certificates found in $CERT_DIR" fi diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 2bbf956423..184b6a5332 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -4,9 +4,13 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" CERT_DIR="${1:-$SCRIPT_DIR}" GENERATOR="$SCRIPT_DIR/generate-dev-certs.sh" +WORKLOAD_NAMESPACE="local" +WORKLOAD_DIR="$CERT_DIR/workloads" +RUNTIME_DIR="$CERT_DIR/local-runtime" required_files=( "$CERT_DIR/ca.crt" + "$CERT_DIR/ca.key" "$CERT_DIR/client.crt" "$CERT_DIR/client.key" "$CERT_DIR/dev-ca.pem" @@ -24,9 +28,144 @@ for file in "${required_files[@]}"; do fi done -if [[ "$missing" == "0" ]]; then - echo "Development certificates already exist in $CERT_DIR" - exit 0 +if [[ "$missing" != "0" ]]; then + "$GENERATOR" "$CERT_DIR" fi +chmod 600 "$CERT_DIR/ca.key" -"$GENERATOR" "$CERT_DIR" +workloads=(account-service game-session-service social-groups-service) +mkdir -p "$WORKLOAD_DIR" +chmod 700 "$WORKLOAD_DIR" + +workload_certificate_is_valid() { + local workload="$1" + local certificate="$WORKLOAD_DIR/$workload.crt" + local private_key="$WORKLOAD_DIR/$workload.key" + local expected_uri="spiffe://firemud/ns/$WORKLOAD_NAMESPACE/sa/$workload" + local subject_alt_names certificate_public_key private_key_public_key + + [[ -f "$certificate" && -f "$private_key" ]] || return 1 + openssl verify -purpose sslclient -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || return 1 + openssl verify -purpose sslserver -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || return 1 + subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName 2>/dev/null)" || return 1 + [[ "$subject_alt_names" == *"URI:$expected_uri"* && "$subject_alt_names" == *"DNS:$workload"* ]] || return 1 + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ + | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null)" || return 1 + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null)" || return 1 + [[ -n "$certificate_public_key" && "$certificate_public_key" == "$private_key_public_key" ]] +} + +for workload in "${workloads[@]}"; do + certificate="$WORKLOAD_DIR/$workload.crt" + private_key="$WORKLOAD_DIR/$workload.key" + if ! workload_certificate_is_valid "$workload"; then + "$GENERATOR" --workload "$CERT_DIR/ca.crt" "$CERT_DIR/ca.key" \ + "$certificate" "$private_key" "$WORKLOAD_NAMESPACE" "$workload" + fi + workload_certificate_is_valid "$workload" || { + echo "local workload certificate failed identity, key-match, or CA validation: $workload" >&2 + exit 1 + } +done + +# Keep host-side workload keys private. Readability is granted only to the +# per-service runtime projection copied below; the generic generator output +# remains mode 0600. +chmod 700 "$WORKLOAD_DIR" +chmod 644 "$WORKLOAD_DIR"/*.crt +chmod 600 "$WORKLOAD_DIR"/*.key + +# Mount only runtime material. Protected callers receive their own leaf, not +# the other protected services' private keys. No projection includes ca.key. +[[ ! -L "$RUNTIME_DIR" ]] || { + echo "refusing symlink as local Compose runtime projection: $RUNTIME_DIR" >&2 + exit 1 +} +mkdir -p "$RUNTIME_DIR" +chmod 755 "$RUNTIME_DIR" +runtime_files=(ca.crt client.crt client.key server.crt server.key dev-ca.pem dev-cert.pem dev-key.pem) +runtime_profiles=(default "${workloads[@]}") +while IFS= read -r -d '' existing_path; do + [[ ! -L "$existing_path" ]] || { + echo "refusing symlink in local Compose runtime projection: $existing_path" >&2 + exit 1 + } + profile_name="${existing_path##*/}" + approved=false + for profile in "${runtime_profiles[@]}"; do + if [[ "$profile_name" == "$profile" && -d "$existing_path" ]]; then + approved=true + break + fi + done + [[ "$approved" == "true" ]] || { + echo "refusing unapproved entry in local Compose runtime projection: $profile_name" >&2 + exit 1 + } +done < <(find "$RUNTIME_DIR" -mindepth 1 -maxdepth 1 -print0) + +for workload in "${workloads[@]}"; do + profile_dir="$RUNTIME_DIR/$workload" + [[ ! -L "$profile_dir" ]] || { + echo "refusing symlink in local Compose runtime projection: $profile_dir" >&2 + exit 1 + } + mkdir -p "$profile_dir/workloads" +done + +for profile in "${runtime_profiles[@]}"; do + profile_dir="$RUNTIME_DIR/$profile" + [[ ! -L "$profile_dir" && ! -L "$profile_dir/workloads" ]] || { + echo "refusing symlink in local Compose runtime projection: $profile_dir" >&2 + exit 1 + } + mkdir -p "$profile_dir" + chmod 755 "$profile_dir" + expected_profile_files=(ca.crt client.crt client.key server.crt server.key dev-ca.pem dev-cert.pem dev-key.pem) + if [[ "$profile" != "default" ]]; then + mkdir -p "$profile_dir/workloads" + chmod 755 "$profile_dir/workloads" + expected_profile_files+=(workloads "workloads/$profile.crt" "workloads/$profile.key") + fi + + while IFS= read -r -d '' existing_path; do + [[ ! -L "$existing_path" ]] || { + echo "refusing symlink in local Compose runtime projection: $existing_path" >&2 + exit 1 + } + relative_path="${existing_path#"$profile_dir"/}" + approved=false + for expected_path in "${expected_profile_files[@]}"; do + if [[ "$relative_path" == "$expected_path" ]]; then + if [[ "$expected_path" == "workloads" ]]; then + [[ -d "$existing_path" ]] && approved=true + else + [[ -f "$existing_path" ]] && approved=true + fi + break + fi + done + [[ "$approved" == "true" ]] || { + echo "refusing unapproved file in local Compose runtime projection: $profile/$relative_path" >&2 + exit 1 + } + done < <(find "$profile_dir" -mindepth 1 -print0) + + for file in "${runtime_files[@]}"; do + [[ -f "$CERT_DIR/$file" ]] || { + echo "missing runtime certificate material: $CERT_DIR/$file" >&2 + exit 1 + } + cp "$CERT_DIR/$file" "$profile_dir/$file" + done + if [[ "$profile" != "default" ]]; then + cp "$WORKLOAD_DIR/$profile.crt" "$profile_dir/workloads/$profile.crt" + cp "$WORKLOAD_DIR/$profile.key" "$profile_dir/workloads/$profile.key" + chmod 755 "$profile_dir/workloads" + chmod 644 "$profile_dir/workloads/$profile.crt" "$profile_dir/workloads/$profile.key" + fi + chmod 644 "$profile_dir"/*.crt "$profile_dir"/*.key "$profile_dir"/*.pem +done + +echo "Development certificates and local Compose workload identities are ready in $CERT_DIR" diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index ca5abcaae8..0dae8edb9c 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -27,7 +27,7 @@ if [[ "${1:-}" == "--workload" ]]; then exit 1 } case "$workload" in - account-service|game-session-service|game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) + account-service|game-session-service|social-groups-service|game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) ;; *) echo "unsupported gRPC workload identity: $workload" >&2 @@ -87,7 +87,10 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi -if [ -f "$CERT_DIR/dev-cert.pem" ] && [ -f "$CERT_DIR/dev-key.pem" ] && [ -f "$CERT_DIR/dev-ca.pem" ]; then +if [ -f "$CERT_DIR/ca.crt" ] && [ -f "$CERT_DIR/ca.key" ] \ + && [ -f "$CERT_DIR/client.crt" ] && [ -f "$CERT_DIR/client.key" ] \ + && [ -f "$CERT_DIR/server.crt" ] && [ -f "$CERT_DIR/server.key" ] \ + && [ -f "$CERT_DIR/dev-cert.pem" ] && [ -f "$CERT_DIR/dev-key.pem" ] && [ -f "$CERT_DIR/dev-ca.pem" ]; then echo "Dev certificates already exist in $CERT_DIR" exit 0 fi @@ -152,9 +155,11 @@ rm -f "$CERT_DIR"/*.csr "$CERT_DIR"/*.srl rm -f "$CERT_DIR/dev-cert.cnf" # Containers run as a non-root application user in CI and local Docker. -# Make the generated development certificates world-readable so bind mounts -# remain readable inside the container regardless of host UID/GID. +# Keep the CA private key host-only. Runtime containers use the CA certificate +# and leaf keys from the local-runtime projection prepared by ensure-dev-certs. +# The shared client/server keys remain readable for non-root local containers. chmod 755 "$CERT_DIR" -chmod 644 "$CERT_DIR"/*.crt "$CERT_DIR"/*.key "$CERT_DIR"/*.pem +chmod 644 "$CERT_DIR"/*.crt "$CERT_DIR"/client.key "$CERT_DIR"/server.key "$CERT_DIR"/*.pem +chmod 600 "$CERT_DIR/ca.key" echo "Certificates generated in $(cd "$CERT_DIR" && pwd)" diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh new file mode 100644 index 0000000000..5402d7b673 --- /dev/null +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -0,0 +1,219 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CERT_DIR="$(mktemp -d)" +trap 'rm -rf "$CERT_DIR"' EXIT + +assert_mode() { + local expected_mode="$1" + local path="$2" + local actual_mode + actual_mode="$(stat -c '%a' "$path")" + [[ "$actual_mode" == "$expected_mode" ]] || { + echo "expected mode $expected_mode for $path, got $actual_mode" >&2 + exit 1 + } +} + +assert_workload_certificate() { + local workload="$1" + local certificate="$CERT_DIR/local-runtime/$workload/workloads/$workload.crt" + local private_key="$CERT_DIR/local-runtime/$workload/workloads/$workload.key" + local subject_alt_names extended_key_usage expected_uri certificate_public_key private_key_public_key + expected_uri="spiffe://firemud/ns/local/sa/$workload" + + openssl verify -purpose sslclient -CAfile "$CERT_DIR/local-runtime/$workload/ca.crt" "$certificate" >/dev/null + openssl verify -purpose sslserver -CAfile "$CERT_DIR/local-runtime/$workload/ca.crt" "$certificate" >/dev/null + subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName)" + [[ "$subject_alt_names" == *"URI:$expected_uri"* \ + && "$subject_alt_names" == *"DNS:$workload"* \ + && "$subject_alt_names" == *"DNS:$workload.local"* \ + && "$subject_alt_names" == *"DNS:$workload.local.svc"* \ + && "$subject_alt_names" == *"DNS:$workload.local.svc.cluster.local"* ]] || { + echo "workload certificate has incorrect SANs: $workload" >&2 + printf '%s\n' "$subject_alt_names" >&2 + exit 1 + } + extended_key_usage="$(openssl x509 -in "$certificate" -noout -ext extendedKeyUsage)" + [[ "$extended_key_usage" == *"TLS Web Server Authentication"* \ + && "$extended_key_usage" == *"TLS Web Client Authentication"* ]] || { + echo "workload certificate does not support both gRPC mTLS roles: $workload" >&2 + exit 1 + } + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ + | openssl pkey -pubin -outform DER | openssl dgst -sha256)" + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER | openssl dgst -sha256)" + [[ "$certificate_public_key" == "$private_key_public_key" ]] || { + echo "workload certificate and private key do not match: $workload" >&2 + exit 1 + } +} + +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" + +runtime_dir="$CERT_DIR/local-runtime" +[[ -z "$(find "$runtime_dir" -name ca.key -print -quit)" ]] || { + echo "CA private key was copied into the Compose runtime projection" >&2 + exit 1 +} +assert_mode 600 "$CERT_DIR/ca.key" +assert_mode 700 "$CERT_DIR/workloads" +assert_mode 755 "$runtime_dir" +for profile in default account-service game-session-service social-groups-service; do + assert_mode 755 "$runtime_dir/$profile" + assert_mode 644 "$runtime_dir/$profile/client.key" + assert_mode 644 "$runtime_dir/$profile/server.key" + assert_mode 644 "$runtime_dir/$profile/dev-key.pem" +done +for workload in account-service game-session-service social-groups-service; do + assert_mode 600 "$CERT_DIR/workloads/$workload.key" + assert_mode 755 "$runtime_dir/$workload/workloads" + assert_mode 644 "$runtime_dir/$workload/workloads/$workload.key" +done + +expected_files=( + default/ca.crt + default/client.crt + default/client.key + default/dev-ca.pem + default/dev-cert.pem + default/dev-key.pem + default/server.crt + default/server.key + account-service/ca.crt + account-service/client.crt + account-service/client.key + account-service/dev-ca.pem + account-service/dev-cert.pem + account-service/dev-key.pem + account-service/server.crt + account-service/server.key + account-service/workloads/account-service.crt + account-service/workloads/account-service.key + game-session-service/ca.crt + game-session-service/client.crt + game-session-service/client.key + game-session-service/dev-ca.pem + game-session-service/dev-cert.pem + game-session-service/dev-key.pem + game-session-service/server.crt + game-session-service/server.key + game-session-service/workloads/game-session-service.crt + game-session-service/workloads/game-session-service.key + social-groups-service/ca.crt + social-groups-service/client.crt + social-groups-service/client.key + social-groups-service/dev-ca.pem + social-groups-service/dev-cert.pem + social-groups-service/dev-key.pem + social-groups-service/server.crt + social-groups-service/server.key + social-groups-service/workloads/social-groups-service.crt + social-groups-service/workloads/social-groups-service.key +) +mapfile -t expected_files < <(printf '%s\n' "${expected_files[@]}" | sort) +mapfile -t actual_files < <(cd "$runtime_dir" && find . -type f -printf '%P\n' | sort) +[[ "${actual_files[*]}" == "${expected_files[*]}" ]] || { + echo "local runtime projection does not match the approved file allowlist" >&2 + printf 'expected: %s\n' "${expected_files[*]}" >&2 + printf 'actual: %s\n' "${actual_files[*]}" >&2 + exit 1 +} + +declare -A seen_certificates=() +for workload in account-service game-session-service social-groups-service; do + assert_workload_certificate "$workload" + fingerprint="$(openssl x509 -in "$runtime_dir/$workload/workloads/$workload.crt" -noout -fingerprint -sha256 | cut -d= -f2)" + [[ -z "${seen_certificates[$fingerprint]:-}" ]] || { + echo "local workloads share a certificate: $workload" >&2 + exit 1 + } + seen_certificates[$fingerprint]=1 +done + +# A malformed or stale local leaf is replaced only after it fails closed +# identity/issuer/key validation; the generic workload generator remains 0600. +printf 'invalid local leaf\n' >"$CERT_DIR/workloads/account-service.crt" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" +assert_workload_certificate account-service +[[ ! -e "$runtime_dir/game-session-service/workloads/account-service.key" \ + && ! -e "$runtime_dir/social-groups-service/workloads/account-service.key" \ + && ! -e "$runtime_dir/account-service/workloads/game-session-service.key" \ + && ! -e "$runtime_dir/account-service/workloads/social-groups-service.key" ]] || { + echo "local runtime projection exposes another workload's private key" >&2 + exit 1 +} + +for compose_file in docker-compose.override.yml docker-compose.local-images.override.yml; do + compose_path="$ROOT_DIR/docker/$compose_file" + rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "false"' "$compose_path" + rg -Fq 'GRPC_SERVER_TLS_ENABLED: "true"' "$compose_path" + rg -Fq '../dev-tools/certs/local-runtime/default:/app/certs:ro' "$compose_path" + rg -Fq 'GATEWAY_WS_URL: ws://gateway:8080/ws/game' "$compose_path" + if rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "true"' "$compose_path" \ + || rg -Fq 'GRPC_SERVER_TLS_ENABLED: "false"' "$compose_path" \ + || rg -Fq '../dev-tools/certs:/app/certs' "$compose_path"; then + echo "$compose_file contains an insecure gRPC override or broad certificate mount" >&2 + exit 1 + fi + [[ "$(rg -c 'volumes: \*local-runtime-volumes' "$compose_path")" == "8" ]] || { + echo "$compose_file does not project runtime-only certs for every Java service" >&2 + exit 1 + } + for workload in account-service game-session-service social-groups-service; do + rg -Fq "../dev-tools/certs/local-runtime/$workload:/app/certs:ro" "$compose_path" + rg -Fq "FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/$workload.crt" "$compose_path" + rg -Fq "FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/$workload.key" "$compose_path" + rg -Fq 'FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt' "$compose_path" + done + rg -Fq 'FIREMUD_GRPC_WORKLOAD_NAMESPACE: local' "$compose_path" +done + +cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$CERT_DIR" 2>&1)" +[[ ! -e "$CERT_DIR/workloads" && ! -e "$CERT_DIR/local-runtime" && ! -e "$CERT_DIR/ca.key" ]] || { + echo "certificate cleanup left generated workload or runtime material behind" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} + +# Unknown files and symlinks are preserved and reported; only known generated +# leaf/projection names are deleted, and their directories remain non-empty. +mkdir -p "$CERT_DIR/workloads" "$CERT_DIR/local-runtime/default" +printf 'generated\n' >"$CERT_DIR/workloads/account-service.key" +printf 'keep\n' >"$CERT_DIR/workloads/keep.txt" +printf 'generated\n' >"$CERT_DIR/local-runtime/default/client.key" +printf 'keep\n' >"$CERT_DIR/local-runtime/default/keep.txt" +printf 'target\n' >"$CERT_DIR/retained-target" +ln -s "$CERT_DIR/retained-target" "$CERT_DIR/local-runtime/default/server.key" +cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$CERT_DIR" 2>&1)" +[[ ! -e "$CERT_DIR/workloads/account-service.key" \ + && ! -e "$CERT_DIR/local-runtime/default/client.key" \ + && -f "$CERT_DIR/workloads/keep.txt" \ + && -f "$CERT_DIR/local-runtime/default/keep.txt" \ + && -L "$CERT_DIR/local-runtime/default/server.key" \ + && "$(<"$CERT_DIR/retained-target")" == "target" ]] || { + echo "certificate cleanup did not preserve unexpected files and symlinks safely" >&2 + exit 1 +} +[[ "$cleanup_output" == *"$CERT_DIR/workloads/keep.txt"* \ + && "$cleanup_output" == *"$CERT_DIR/local-runtime/default/server.key"* ]] || { + echo "certificate cleanup did not report preserved entries" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} + +symlink_case="$CERT_DIR/symlink-case" +mkdir -p "$symlink_case/target" +printf 'protected\n' >"$symlink_case/target/social-groups-service.key" +ln -s "$symlink_case/target" "$symlink_case/workloads" +cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$symlink_case" 2>&1)" +[[ -L "$symlink_case/workloads" \ + && "$(<"$symlink_case/target/social-groups-service.key")" == "protected" \ + && "$cleanup_output" == *"$symlink_case/workloads (symlink directory)"* ]] || { + echo "certificate cleanup followed or failed to report a symlinked leaf directory" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} + +echo "Local Compose workload identity contract passed." diff --git a/docker/README.md b/docker/README.md index e6da86a1cf..5f17477bdf 100644 --- a/docker/README.md +++ b/docker/README.md @@ -34,7 +34,9 @@ docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.ym docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.yml down ``` -For ordinary local development, prefer `./gradlew devUp` and `./gradlew devDown`. The Gradle task builds the base image, application images, and `pg-dump-cron` image, generates development certificates, synchronizes the local Compose environment, and waits for the requested services to become ready. The raw source-built commands above are useful when iterating directly on the Compose build path; the certificate helper prepares the mounted local material, while the local override still selects plaintext internal gRPC for this development stack. +For ordinary local development, prefer `./gradlew devUp` and `./gradlew devDown`. The Gradle task builds the base image, application images, and `pg-dump-cron` image, ensures development certificates and workload identities, synchronizes the local Compose environment, and waits for the requested services to become ready. The raw source-built commands above are useful when iterating directly on the Compose build path. + +Both local Compose lanes use internal gRPC mTLS. `ensure-dev-certs.sh` creates local-only Account, Game Session, and Social Groups workload leaves signed by the local development CA, and prepares the ignored `dev-tools/certs/local-runtime/` bind-mount projection. That projection contains runtime certificates and keys but not the CA private key; it is not a hosted certificate source. The local overrides point the protected callers at their own leaf, set the `local` workload namespace for Account and Logging & Admin peer checks, and keep Gateway/TCP Proxy HTTP and WebSocket routing unchanged. Do not copy these local settings or certificates into preview, dev-demo, or production deployments. Canonical smoke/bootstrap proof: @@ -76,6 +78,6 @@ Gradle-managed local prebuilt-image stack: ## Local Runtime Notes - Compose service discovery uses Docker DNS plus the defaults in service `application.yml` files and the local Compose env overrides; it does not depend on a separate Spring `dev` profile lane. -- The local override files intentionally relax internal gRPC/TLS settings for the Docker development stack. +- The local override files keep internal gRPC mTLS enabled for the Docker development stack and replace the base certificate-directory mount with the CA-key-free local runtime projection. - The Compose stack also runs `pg-dump-cron`, which writes rotated PostgreSQL dumps under `docker/backups/`. - The scripted smoke clients require Python 3 and the `websocket-client` package; see [Smoke Tests for Login + PLAY + LOOK](../design/developer-workflows/login-session-smoke-tests.md#requirements) for the client prerequisites and transport-specific controls. diff --git a/docker/docker-compose.local-images.override.yml b/docker/docker-compose.local-images.override.yml index 7a1ddddac1..5af039f319 100644 --- a/docker/docker-compose.local-images.override.yml +++ b/docker/docker-compose.local-images.override.yml @@ -1,8 +1,11 @@ x-local-java-env: &local-java-env BPL_JAVA_NMT_ENABLED: "false" BPL_JVM_THREAD_COUNT: "20" - FIREMUD_GRPC_PLAINTEXT: "true" - GRPC_SERVER_TLS_ENABLED: "false" + FIREMUD_GRPC_PLAINTEXT: "false" + GRPC_SERVER_TLS_ENABLED: "true" + +x-local-runtime-volumes: &local-runtime-volumes + - ../dev-tools/certs/local-runtime/default:/app/certs:ro services: account-service: @@ -12,6 +15,12 @@ services: mem_limit: 768m environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/account-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/account-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + FIREMUD_GRPC_WORKLOAD_NAMESPACE: local + volumes: + - ../dev-tools/certs/local-runtime/account-service:/app/certs:ro gateway: build: null @@ -22,6 +31,7 @@ services: <<: *local-java-env FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_ALLOW_INSECURE_HEADERS_FROM_TRUSTED_CIDRS: "true" FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_INSECURE_TRUSTED_CIDRS_0: 172.16.0.0/12 + volumes: *local-runtime-volumes automation-scripting-service: build: null @@ -30,6 +40,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes entity-management-service: build: null @@ -38,6 +49,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes game-design-service: build: null @@ -46,6 +58,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes game-logic-service: build: null @@ -54,6 +67,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes game-session-service: build: null @@ -63,6 +77,11 @@ services: environment: <<: *local-java-env GAME_LOGIC_DEFAULT_ROOM_ID: "1" + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/game-session-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/game-session-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + volumes: + - ../dev-tools/certs/local-runtime/game-session-service:/app/certs:ro logging-admin-service: build: null @@ -71,6 +90,8 @@ services: mem_limit: 768m environment: <<: *local-java-env + FIREMUD_GRPC_WORKLOAD_NAMESPACE: local + volumes: *local-runtime-volumes social-groups-service: build: null @@ -79,6 +100,11 @@ services: mem_limit: 768m environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/social-groups-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/social-groups-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + volumes: + - ../dev-tools/certs/local-runtime/social-groups-service:/app/certs:ro tcp-proxy-service: build: null @@ -88,6 +114,7 @@ services: environment: <<: *local-java-env GATEWAY_WS_URL: ws://gateway:8080/ws/game + volumes: *local-runtime-volumes world-management-service: build: null @@ -96,6 +123,7 @@ services: mem_limit: 768m environment: <<: *local-java-env + volumes: *local-runtime-volumes pg-dump-cron: build: null diff --git a/docker/docker-compose.override.yml b/docker/docker-compose.override.yml index 20fb7f21f5..795df2baa7 100644 --- a/docker/docker-compose.override.yml +++ b/docker/docker-compose.override.yml @@ -1,47 +1,73 @@ -# Local override for plaintext/dev-only Compose behavior. Do not reuse these -# settings as a template for preview or other production-like environments. +# Local override for the development Compose stack. Do not reuse these settings +# as a template for preview or other production-like environments. x-local-java-env: &local-java-env - FIREMUD_GRPC_PLAINTEXT: "true" - GRPC_SERVER_TLS_ENABLED: "false" + FIREMUD_GRPC_PLAINTEXT: "false" + GRPC_SERVER_TLS_ENABLED: "true" + +x-local-runtime-volumes: &local-runtime-volumes + - ../dev-tools/certs/local-runtime/default:/app/certs:ro services: account-service: environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/account-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/account-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + FIREMUD_GRPC_WORKLOAD_NAMESPACE: local + volumes: + - ../dev-tools/certs/local-runtime/account-service:/app/certs:ro gateway: environment: <<: *local-java-env FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_ALLOW_INSECURE_HEADERS_FROM_TRUSTED_CIDRS: "true" FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_INSECURE_TRUSTED_CIDRS_0: 172.16.0.0/12 + volumes: *local-runtime-volumes automation-scripting-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes entity-management-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes game-design-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes game-logic-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes game-session-service: environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/game-session-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/game-session-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + volumes: + - ../dev-tools/certs/local-runtime/game-session-service:/app/certs:ro logging-admin-service: environment: <<: *local-java-env + FIREMUD_GRPC_WORKLOAD_NAMESPACE: local + volumes: *local-runtime-volumes social-groups-service: environment: <<: *local-java-env + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/workloads/social-groups-service.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/workloads/social-groups-service.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + volumes: + - ../dev-tools/certs/local-runtime/social-groups-service:/app/certs:ro tcp-proxy-service: environment: @@ -52,10 +78,12 @@ services: TCP_PROXY_DEFAULT_POINTER_VERSION: ${TCP_PROXY_DEFAULT_POINTER_VERSION:-1} TCP_PROXY_DEFAULT_GAME_INSTANCE_ID: ${TCP_PROXY_DEFAULT_GAME_INSTANCE_ID:-1} TCP_PROXY_DEFAULT_TENANT_ID: ${TCP_PROXY_DEFAULT_TENANT_ID:-1} + volumes: *local-runtime-volumes world-management-service: environment: <<: *local-java-env + volumes: *local-runtime-volumes redisinsight: image: redis/redisinsight:2.70 From 14184b92fd7dca368f1003bc946ca012f0249b04 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 28 Sep 2026 02:09:15 +1300 Subject: [PATCH 21/55] Clarify merged JOIN status and tracker rows --- .../implementation-tracking/player-access-and-session.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 127b925403..347bef105a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -53,11 +53,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.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.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.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, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. 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; 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, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. 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, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. 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 first-party post-logout replay cleanup are absent. | From d14f1b7dcc418bae989c4d5a92852901b404708b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 28 Sep 2026 09:02:54 +1300 Subject: [PATCH 22/55] Document retained pending JOIN recovery after scope expiry --- .../microservices/account-service/runtime-and-data.md | 2 +- design/architecture/system-architecture-authentication.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 74bdf8d595..cc9c5c3327 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,7 +16,7 @@ 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. Six focused unit cases in `ExpiredCredentialCleanupJobTest` executed locally; seven PostgreSQL integration cases in `CredentialCleanupRepositoryIntegrationTest` passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. -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 currently records retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the bounded worker can terminalize only exact positive prior-commit evidence. A malformed or missing bearer is rejected without inventing a terminal operation result. The parent previously documented terminal `CONNECT_SCOPE_INVALID` for expired `PENDING` scope; whether that should replace the child’s current retryable behavior remains an unresolved owner decision. 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 currently records retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the bounded worker can terminalize only exact positive prior-commit evidence. A malformed or missing bearer is rejected without inventing a terminal operation result. An exact caller retry cannot rerun JOIN with the expired scope, and automatic readback attempts reaching their cap leave the intent `PENDING` rather than inventing a terminal failure. 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. 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. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 2ff68c571c..837ccbdc18 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -314,7 +314,7 @@ These modes are complementary: public browse remains available before authentica ``` - Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. `allowPublicJoin` is lowercase `true` or `false`; `entitlementVersion` is a positive canonical decimal. Account stores the intent digest/version before evaluation, then stores the request digest/version and exact policy evidence only after `AVAILABLE` authority has supplied both policy values. If entitlement authority is unavailable, Account records the attempt failure and availability while leaving the operation `PENDING`; it does not create a policy-bound request digest or invent a policy result/version. A retry with the same intent may reconcile that pending operation when authority is available. At the membership commit gate Account re-evaluates policy and requires the exact same digest and evidence; changed policy returns `IDEMPOTENCY_CONFLICT` without committing membership or its transition event. Exact retries replay the stored operation result after their required current-policy check. No earlier JOIN digest was persisted, so no version-compatibility path is required. -- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery; for a retained `PENDING` operation, an expired scope terminally returns `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. +- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched scope cannot authorize a new JOIN and requires fresh authenticated `REALMS` discovery. For an existing matching `PENDING` operation with an expired retained scope, an exact retry returns retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the intent remains `PENDING` for readback-only reconciliation of exact prior-commit evidence, including after automatic attempts are exhausted. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. Normative semantic split: From 3c9afe4c21b9d49000fdee58fb5b187059392b7d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:05:32 +1300 Subject: [PATCH 23/55] Gate direct-text JOIN scopes on live entitlement --- .../system-architecture-authz-route-matrix.md | 5 +- ...ystem-architecture-authz-route-matrix.yaml | 45 +++++++++- .../service/impl/AccountServiceImpl.java | 6 ++ .../service/impl/AccountServiceImplTest.java | 86 +++++++++++++++++++ 4 files changed, 136 insertions(+), 6 deletions(-) diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index b2c5844a2f..4fb6071df7 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -215,7 +215,7 @@ For every first public-production text entry, the target command sequence is `LO | Game Session Service | `WORLDS` anonymous browse | `public` | Public-production catalog only; no account-specific membership, grant, or character information | | Game Session Service | `WORLDS` authenticated discovery | `pre_tenant_discovery` | No pre-existing tenant role is required. Tenant visibility is derived server-side from membership or public-production visibility plus entitlement state; global roles do not widen gameplay discovery | | Game Session Service | `REALMS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive branch from the authoritative realm mode: public production permits pre-membership discovery; private/playtest requires caller-bound `membershipLifecycleState=ACTIVE`, current membership authority generation/version, and the current Account-owned grant for the exact target. Private/playtest is never classified as public onboarding, never falls back to public discovery, and never uses a grant to repair membership. Hidden/unauthorized targets are omitted; explicit branch failures use `NON_PUBLIC_ENROLLMENT_REQUIRED`, `REALM_ACCESS_DENIED`, `WORLD_ACCESS_DENIED`, `ADMISSION_POINTER_UNAVAILABLE`, `REALM_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE`, or `AUTH_UNAVAILABLE` as applicable. | -| Game Session Service | `JOIN` | `public_production_onboarding` | **Target-only; not currently implemented.** Explicit caller-bound open-enrollment action for the current public production realm; Account commits durable membership plus audit/outbox idempotently | +| Game Session Service | `JOIN` | `public_production_onboarding` | **Implemented locally; proof incomplete.** Game Session retains the Account-issued scope and submits explicit JOIN to Account, which commits caller-bound membership plus audit/outbox evidence locally. Membership-generation, unknown-outcome recovery/reconciliation, receipt/retention, PostgreSQL runtime, and direct-text end-to-end proof remain open; see [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Game Session Service | `CHARS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Public discovery may lead to `JOIN_REQUIRED` for missing or `INACTIVE` membership; private/playtest requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. It applies the current `admission_pointer` check to the selected catalog realm, but does not apply `PLAY`'s exact-binding admission lease, binding fence, or binding-ownership gate; character discovery and creation do not require a selected character. Policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and unavailable or invalid authority uses the applicable unavailable/invalid-authority outcome. Missing or non-`ACTIVE` private/playtest membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`, and character discovery is not membership repair. | | Game Session Service | `PLAY` | `gameplay_admission` | **Target:** requires an existing caller-bound membership plus any non-public realm grant, current entitlements, and the current admissible realm pointer; `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when the selected target is confirmed as public production and its joining policy denies entry, and only an admissible, publicly visible public-production target whose joining policy permits entry and whose membership is missing or `INACTIVE` returns `JOIN_REQUIRED`; `ACTIVE` membership does not require `JOIN`, and `PLAY` never creates or restores membership. `PLAY` alone performs the final gameplay-binding CAS. First-party `/ws/game/**` also enforces connect-context scope. Unavailable, ambiguous, stale, or otherwise invalid routing returns `ADMISSION_POINTER_UNAVAILABLE`; a deliberately closed realm returns `REALM_UNAVAILABLE`; entitlement authority outage returns `ENTITLEMENT_UNAVAILABLE`. | | Spring Cloud Gateway | `/ws/game/**` (connect-token bootstrap) | `gameplay_admission` | **Implemented but non-promotable until the named Gateway readiness evidence is complete:** carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. This is one canonical WebSocket entry point with mutually exclusive variants. The current `first_party_web` variant accepts exactly the protected cookie for first-party protected-cookie clients, including native or other nonbrowser clients using a cookie jar. The live `GameplayHandshakeFilter` rejects `X-Firemud-Connect-Token` on this public route with `CONNECT_TOKEN_REJECTED` and reason `unsupported_carrier_or_route`, without falling back to the cookie. A future explicitly classified `non_first_party_public` variant may use the header only after its dedicated matrix entry and issuance, replay, signed-context, response, and carrier proof exist; it cannot select or fall back to `first_party_web`. Gateway consumes exactly one supported carrier, strips it, atomically enforces single use using the dedicated replay record/fence, matches the signed connect scope to the request, and emits the signed connect context for Game Session. Non-`101` outcomes use the bounded `CONNECT_TOKEN_MISSING`, `CONNECT_TOKEN_EXPIRED`, `CONNECT_TOKEN_REPLAYED`, `CONNECT_SCOPE_MISMATCH`, `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, `CONNECT_TOKEN_REJECTED`, `POLICY_DENY`, `POLICY_PRESSURE`, `BACKEND_UNAVAILABLE`, `PROTOCOL_MISMATCH`, or `INTERNAL_ERROR` handshake classes. | @@ -242,7 +242,8 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `EnterPrivilegedControlWindow` | `account_scoped` | **Target; not currently implemented.** Exact `control-ui` profile plus recent ordinary reauthentication and independent TOTP; this route creates the bounded role-scoped window and does not require an existing elevation window | | Account Service | `IssueHumanOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus a forwarded `control-ui` token with its exact active Account issued-token registry record; Account rereads current account/token generation, operator roles, role-appropriate assurance, the applicable tenant or target-tenant generation, and required `privileged_control` predicate before issuing the bounded reference | | Account Service | `IssueAutomationOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus current versioned automation policy; no end-user JWT or user impersonation. The current branch is tenant-scoped only, binds the exact current tenant generation, and rejects global-role or `privileged_control` action families | -| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Target-only; not currently implemented.** Canonical operation is defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). The local route is called only by the exact Game Session mTLS workload with typed caller-bound player execution context, accepts no end-user token, and requires `verified_connectScopeId_exact_target`. Account revalidates the exact `connectScopeId`, `catalogRevision`, `pointerVersion`, and resolved target immediately before commit; silent retargeting is forbidden. The obsolete implicit membership writer is removed. | +| Account Service | `IssueDirectTextConnectScope` | `internal_workload` | **Implemented locally; end-to-end proof incomplete.** Exact Game Session mTLS and typed caller/target context are required; Account rereads the public-production target and current gameplay entitlement before retaining an opaque short-lived scope. The scope is not caller authority or a JOIN policy decision; see [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) | +| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Implemented locally; proof incomplete.** Account's explicit writer is the sole membership mutation path; the canonical contract and current transaction consequences are defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). Target-only membership-generation snapshot proof, unknown-outcome recovery/reconciliation, audit receipt/retention proof, PostgreSQL runtime proof, and direct-text end-to-end proof remain open. The obsolete implicit membership writer is removed. | | Account Service | `DELETE /tenants/{tenantId}/memberships/me` | `caller_membership_scoped` | Caller-bound membership exit remains available while billing-blocked to any current member role, requires live subject-bound membership, and advances membership authority atomically | | Account Service | `AuthLogout` / `AuthLogoutAll` | `account_scoped` | Accepts `control-ui` (`audience: control-ui`) or `player-bootstrap` (`audience: player-bootstrap`) with registry-backed authenticated account scope. Bounded retries may return no-op success only from a durable committed exact-token tombstone (`AuthLogout`) or durable proof that a prior logout-all superseded the token (`AuthLogoutAll`); registry absence alone is insufficient and the retry exception grants no reusable authorization context | | Account Service | `GET /accounts/{accountId}/deletion` | `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=deletion_status`; the Account-issued credential is bound to the account and deletion workflow and returns deletion status only | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 16ef35c108..bc23c5792b 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -1160,7 +1160,6 @@ routes: any_of: [JOIN_REQUIRED, PUBLIC_PRODUCTION_ADMISSION_DENIED, NON_PUBLIC_ENROLLMENT_REQUIRED, REALM_ACCESS_DENIED, WORLD_ACCESS_DENIED, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE] - service: game-session-service route: JOIN - route_status: target_not_currently_routable scope: tenant classification: public_production_onboarding auth_path: game_session_authenticated_context @@ -1173,9 +1172,15 @@ routes: membership_authority_generation_applies: false required_live_checks: [public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, TENANT_BILLING_BLOCKED] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE, IDEMPOTENCY_CONFLICT] mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation + implementation_status: + known_drift: + - membership_authority_generation_snapshot_and_consumer_proof_remains_target_only + - join_unknown_database_outcome_recovery_and_reconciliation_remains_target_only + - join_audit_receipt_retention_and_safe_watermark_proof_remains_target_only + - postgresql_runtime_and_direct_text_end_to_end_proof_unavailable - service: game-session-service route: PLAY scope: tenant @@ -1930,11 +1935,40 @@ routes: mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation route_status: target_not_currently_routable + - service: account-service + route: IssueDirectTextConnectScope + scope: tenant + classification: internal_workload + auth_path: exact_mtls_workload_plus_caller_specific_context + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [game-session-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/game-session-service"] + delegated_subject: typed_player_execution_context + target_binding: typed_caller_context_and_exact_resolved_target + tenant_billing_authority_generation_applies: false + membership_authority_generation_applies: false + required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer] + canonical_errors: + any_of: [ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, REALM_UNAVAILABLE, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE] + end_user_token_required: false + issuance_contract: + result: opaque_short_lived_connect_scope_id + binds: [caller_account, resolved_target, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt] + silent_retarget: forbidden + implementation_status: + known_drift: + - direct_text_client_end_to_end_proof_unavailable - service: account-service route: JoinPublicProductionMembership scope: tenant classification: internal_workload - route_status: target_not_currently_routable auth_path: exact_mtls_workload issued_token_state: none accepted_token_profiles: [] @@ -1968,7 +2002,10 @@ routes: membership_creation: caller_bound_after_validation implementation_status: known_drift: - - explicit_JOIN_and_Join_And_Play_are_not_currently_implemented; connect_token_and_play_now_require_existing_membership_and_do_not_invoke_this_writer + - membership_authority_generation_snapshot_and_consumer_proof_remains_target_only + - join_unknown_database_outcome_recovery_and_reconciliation_remains_target_only + - join_audit_receipt_retention_and_safe_watermark_proof_remains_target_only + - postgresql_runtime_and_direct_text_end_to_end_proof_unavailable - service: account-service route: DELETE /tenants/{tenantId}/memberships/me scope: tenant 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 bd1588ba3a..a675ac39bc 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 @@ -492,6 +492,12 @@ public DirectTextJoinScope issueDirectTextConnectScope( || current.pointerVersion() != target.pointerVersion()) { throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(current.tenantId(), caller.requestId()); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); String scopeId = 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 2c61f502d4..4e318c250a 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 @@ -26,6 +26,9 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +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.PasswordResetRequest; @@ -2135,6 +2138,57 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } + @Test + void issueDirectTextConnectScopeRejectsUnavailableEntitlementWithoutRetainingScope() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @Test + void issueDirectTextConnectScopeRejectsBillingBlockedEntitlementWithoutRetainingScope() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + Subscription canceled = new Subscription(); + canceled.setId(31L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + + assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); + assertEquals("Gameplay is not available for this tenant", exception.getMessage()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @Test + void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + + DirectTextJoinScope result = + service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); + + assertNotNull(result.connectScopeId()); + assertNotNull(result.connectScopeExpiresAt()); + org.mockito.Mockito.verify(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + @Test void issueConnectTokenReturnsShortLivedConnectToken() { Account account = new Account(); @@ -4323,6 +4377,38 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } + private static Account directTextAccount() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + return account; + } + + private static DirectTextCallerContext directTextCaller() { + return new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + "production-namespace-7", + "SHARED", + 44L, + "session-1", + "direct-text-request-1"); + } + + private static DirectTextJoinTarget directTextTarget() { + return new DirectTextJoinTarget( + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + "production-namespace-7", + "SHARED", + 44L, + 23L, + 17L); + } + private static String hash(String password) { Argon2 argon2 = Argon2Factory.create(); char[] chars = password.toCharArray(); From aa47971e10dffce2501f2cc630076e14d58f79e1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:21:57 +1300 Subject: [PATCH 24/55] Preserve Logging audit V2 and migrate projections forward --- .../logging-admin-service/runtime-and-data.md | 1 + .../migration/V2__account_audit_receipts.sql | 25 -- .../V3__account_audit_receipt_projection.sql | 68 ++++ ...oggingAdminApplicationIntegrationTest.java | 293 ++++++++++++++++++ 4 files changed, 362 insertions(+), 25 deletions(-) create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V3__account_audit_receipt_projection.sql diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index c5a123e1e5..5f0c6de3d8 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -29,6 +29,7 @@ Target external session-lifecycle operator requests enter through Gateway and Lo The current shipped scope is narrower than this target contract: +- The current branch's forward Logging V3 adds the Account audit projection and links retained V2 receipts without rewriting V2. Exact audit projections require a scope-qualified tenant key matching `tenantId` (or zero for platform scope); older ordinary tenant `log_events` writers may omit that new key and leave its compatibility value at zero, while tenant queries continue to use `tenantId`. The V2-to-V3 retained-row migration test compiles but has not executed locally without Docker, so this is not retained-database activation proof. - The service exposes core admin investigation reads, saga inspection of Logging & Admin-local rows only, coordination-health reads, and a narrow log query whose current implementation reads only the service-owned PostgreSQL `log_events` table for an exact tenant plus case-insensitive message containment. Saga inspection does not aggregate adopter-local state; target cross-owner visibility requires owner read APIs plus a bounded aggregation/read model and must distinguish an unknown or unavailable adopter from an empty result. Moderation policy-input and report-persistence paths are only unsupported legacy transport/internal seams that hard fail closed or remain authorization-unproved; they are not exposed current capabilities. The service does not implement the target profile-aware indexed or console/journal query integrations, Kibana/Grafana clients, embedded dashboards, separate admin UI, or the complete target control-plane workflow for every recovery, regional, or aggregate operation. - The moderation policy-input and audit persistence mutation has present legacy transport stubs through `POST /moderation/actions` and the internal `ApplyModerationAction` gRPC ingress; after narrow tenant/admin checks they hard fail closed with HTTP `503 Service Unavailable` or an application-level gRPC `UNAVAILABLE` error, without dispatch or persistence. They are unsupported, nonconformant implementation drift and must not be wired or called as available mutations. They do not provide the target fixed-category policy-input/audit record or Account, Game Session, or Social & Groups enforcement state. Current execution performs no Account authorization-reference issuance or redemption, owner forwarding, or owner enforcement. Once its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin receiving-boundary validation/redemption are complete, Logging & Admin redeems the separate intent-persistence reference exactly once at its receiving boundary; that reference is never forwarded or reused and the path does not require owner-side authorization-reference redemption or enforcement. Any future owner-enforcement command uses a separately issued reference redeemed once by its receiving owner. The separate `EvaluateModerationPolicy` compatibility read remains live at the owner enforcement boundaries and carries no mutation authorization reference. Public administrative report persistence at `POST /admin/reports` is unavailable: the HTTP controller and Gateway route were removed because canonical authorization and live reference validation are not implemented. The internal `CreateReport` gRPC ingress is not public; its interim receiver guard requires an internal-service JWT naming `social-groups-service`, which the Social & Groups client emits, while certificate-derived exact workload/method authorization remains unproved. The reserved player-bootstrap `POST /reports` submission route is separate and also unavailable until its caller-bound subject and live tenant-membership checks exist. - Admission-pointer reads, audit, and prepared-upgrade proof reads are implemented and live. Internal admission-pointer mutation, version-upgrade preparation, and prepared-cutover owner paths have implementation-participating surfaces, but the current pointer writer is read-then-write/nonconformant; the target atomic open/close CAS and prepared cutover remain unimplemented and externally unavailable behind internal trust boundaries, with public HTTP/Gateway write support unavailable and no current UI control. Target-only absent is reserved for operations with no executable owner path at all, such as quota-override mutations or future named typed recovery actions whose owner contracts do not yet exist. diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql index d5305828fa..4e1a61f25a 100644 --- a/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql +++ b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql @@ -1,30 +1,5 @@ -ALTER TABLE log_events - ALTER COLUMN tenant_id DROP NOT NULL; - -ALTER TABLE log_events - ADD COLUMN scope VARCHAR(16) NOT NULL DEFAULT 'tenant'; - -ALTER TABLE log_events - ADD COLUMN audit_event_id VARCHAR(36); - -ALTER TABLE log_events - ADD COLUMN tenant_key BIGINT NOT NULL DEFAULT 0; - -UPDATE log_events SET tenant_key = tenant_id; - -ALTER TABLE log_events - ADD CONSTRAINT chk_log_events_scope_tenant - CHECK ( - (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) - OR (scope = 'tenant' AND tenant_id IS NOT NULL AND tenant_key = tenant_id) - ); - -CREATE UNIQUE INDEX uq_log_events_account_audit_identity - ON log_events (scope, tenant_key, audit_event_id); - CREATE TABLE account_audit_receipts ( id BIGSERIAL PRIMARY KEY, - log_event_id BIGINT NOT NULL UNIQUE REFERENCES log_events (id), receipt_id UUID NOT NULL UNIQUE, scope VARCHAR(16) NOT NULL, tenant_id BIGINT, diff --git a/services/logging-admin-service/src/main/resources/db/migration/V3__account_audit_receipt_projection.sql b/services/logging-admin-service/src/main/resources/db/migration/V3__account_audit_receipt_projection.sql new file mode 100644 index 0000000000..c0d9144b4e --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V3__account_audit_receipt_projection.sql @@ -0,0 +1,68 @@ +ALTER TABLE log_events + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE log_events + ADD COLUMN scope VARCHAR(16) NOT NULL DEFAULT 'tenant', + ADD COLUMN audit_event_id VARCHAR(36), + ADD COLUMN tenant_key BIGINT NOT NULL DEFAULT 0; + +ALTER TABLE log_events + ADD CONSTRAINT chk_log_events_scope_tenant + CHECK ( + (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND ( + (audit_event_id IS NOT NULL AND tenant_key = tenant_id) + OR (audit_event_id IS NULL AND tenant_key IN (0, tenant_id)) + ) + ) + ); + +CREATE UNIQUE INDEX uq_log_events_account_audit_identity + ON log_events (scope, tenant_key, audit_event_id); + +ALTER TABLE account_audit_receipts + ADD COLUMN log_event_id BIGINT; + +INSERT INTO log_events ( + scope, + tenant_id, + tenant_key, + audit_event_id, + type, + message, + timestamp, + account_id +) +SELECT receipt.scope, + receipt.tenant_id, + receipt.tenant_key, + receipt.audit_event_id, + 'ACCOUNT_AUDIT', + 'Account audit event ' || receipt.audit_event_id, + TIMESTAMP '1970-01-01 00:00:00' + + receipt.occurred_at_seconds * INTERVAL '1' SECOND + + (receipt.occurred_at_nanos / 1000) * INTERVAL '0.000001' SECOND, + NULL +FROM account_audit_receipts AS receipt; + +UPDATE account_audit_receipts AS receipt +SET log_event_id = ( + SELECT event.id + FROM log_events AS event + WHERE event.scope = receipt.scope + AND event.tenant_key = receipt.tenant_key + AND event.audit_event_id = receipt.audit_event_id +); + +ALTER TABLE account_audit_receipts + ALTER COLUMN log_event_id SET NOT NULL; + +ALTER TABLE account_audit_receipts + ADD CONSTRAINT uq_account_audit_receipts_log_event_id UNIQUE (log_event_id); + +ALTER TABLE account_audit_receipts + ADD CONSTRAINT fk_account_audit_receipts_log_event_id + FOREIGN KEY (log_event_id) REFERENCES log_events (id); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 9f1ac3ed47..478ffeb83c 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -15,13 +15,16 @@ import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; +import java.time.LocalDateTime; import java.util.HexFormat; import java.util.Map; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.loggingadmin.client.AccountClient; import net.firedevops.firemud.loggingadmin.client.GameSessionClient; @@ -39,7 +42,10 @@ import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -98,6 +104,7 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GameSessionControlPlaneClient gameSessionControlPlaneClient; @Autowired private DSLContext dsl; + @Autowired private DataSource dataSource; @Autowired private LogEventService logEventService; @Autowired private LogQueryService logQueryService; @@ -222,6 +229,292 @@ void concurrentExactRetriesCreateOneProjectionAndReturnTheSameIdentifiers() thro } } + @Test + void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { + String schema = "logging_admin_migration_" + UUID.randomUUID().toString().replace("-", ""); + dsl.execute("CREATE SCHEMA " + schema); + try { + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .target(MigrationVersion.fromVersion("2")) + .load() + .migrate(); + + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (tenant_id, type, message, timestamp, account_id) " + + "VALUES (?, ?, ?, ?, ?)", + 73L, + "PAYMENT", + "legacy payment log", + LocalDateTime.of(2025, 3, 1, 12, 0), + 12L); + seedV2Receipt( + schema, + UUID.fromString("30000000-0000-4000-8000-000000000001"), + "tenant", + 73L, + "10000000-0000-4000-8000-000000000001", + Instant.parse("2025-03-01T12:00:01.123456Z"), + false); + seedV2Receipt( + schema, + UUID.fromString("30000000-0000-4000-8000-000000000002"), + "tenant", + 73L, + "10000000-0000-4000-8000-000000000002", + Instant.parse("2025-03-01T12:00:02.987654Z"), + true); + seedV2Receipt( + schema, + UUID.fromString("40000000-0000-4000-8000-000000000001"), + "platform", + null, + "20000000-0000-4000-8000-000000000001", + Instant.parse("2025-03-01T12:00:03.123456Z"), + false); + seedV2Receipt( + schema, + UUID.fromString("40000000-0000-4000-8000-000000000002"), + "platform", + null, + "20000000-0000-4000-8000-000000000002", + Instant.parse("2025-03-01T12:00:04.987654Z"), + true); + + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); + + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + schema + ".log_events WHERE message = ?", + Integer.class, + "legacy payment log")) + .isEqualTo(1); + assertThat( + dsl.fetchValue( + "SELECT tenant_key FROM " + schema + ".log_events WHERE message = ?", + Long.class, + "legacy payment log")) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + schema + ".account_audit_receipts", + Integer.class)) + .isEqualTo(4); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + + schema + + ".account_audit_receipts AS receipt LEFT JOIN " + + schema + + ".log_events AS event ON event.id = receipt.log_event_id " + + "WHERE event.id IS NULL", + Integer.class)) + .isEqualTo(0); + assertBackfilledReceipt( + schema, + "30000000-0000-4000-8000-000000000001", + "tenant", + 73L, + "10000000-0000-4000-8000-000000000001", + "COMMITTED", + "ACCEPTED", + "2025-03-01T12:00:01.123456"); + assertBackfilledReceipt( + schema, + "30000000-0000-4000-8000-000000000002", + "tenant", + 73L, + "10000000-0000-4000-8000-000000000002", + "MINIMIZED", + "NON_REPLAYABLE", + "2025-03-01T12:00:02.987654"); + assertBackfilledReceipt( + schema, + "40000000-0000-4000-8000-000000000001", + "platform", + null, + "20000000-0000-4000-8000-000000000001", + "COMMITTED", + "ACCEPTED", + "2025-03-01T12:00:03.123456"); + assertBackfilledReceipt( + schema, + "40000000-0000-4000-8000-000000000002", + "platform", + null, + "20000000-0000-4000-8000-000000000002", + "MINIMIZED", + "NON_REPLAYABLE", + "2025-03-01T12:00:04.987654"); + + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (tenant_id, type, message, timestamp) VALUES (?, ?, ?, ?)", + 84L, + "PAYMENT", + "legacy insert", + LocalDateTime.of(2025, 3, 1, 13, 0)); + Long legacyLogId = + dsl.fetchOne( + "SELECT id FROM " + schema + ".log_events WHERE message = ?", "legacy insert") + .get("id", Long.class); + assertThat( + dsl.fetchValue( + "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", + Long.class, + legacyLogId)) + .isEqualTo(0L); + + dsl.execute( + "UPDATE " + schema + ".log_events SET tenant_id = ? WHERE id = ?", 85L, legacyLogId); + assertThat( + dsl.fetchValue( + "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", + Long.class, + legacyLogId)) + .isEqualTo(0L); + + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + + "VALUES (?, ?, ?, ?, ?, ?)", + "tenant", + 86L, + 86L, + "60000000-0000-4000-8000-000000000001", + "ACCOUNT_AUDIT", + "Account audit event 60000000-0000-4000-8000-000000000001"); + assertThat( + dsl.fetchValue( + "SELECT tenant_key FROM " + + schema + + ".log_events WHERE audit_event_id = ?", + Long.class, + "60000000-0000-4000-8000-000000000001")) + .isEqualTo(86L); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + + "VALUES ('tenant', 73, 74, '50000000-0000-4000-8000-000000000001', " + + "'ACCOUNT_AUDIT', 'mismatched key')")) + .isInstanceOf(DataAccessException.class); + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private void seedV2Receipt( + String schema, + UUID receiptId, + String scope, + Long tenantId, + String eventId, + Instant occurredAt, + boolean minimized) { + byte[] originalPayload = "{\"retained\":true}".getBytes(StandardCharsets.UTF_8); + dsl.execute( + "INSERT INTO " + + schema + + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id, " + + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, schema_version, " + + "payload_digest_version, payload_digest, payload, status, outcome) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receiptId, + scope, + tenantId, + tenantId == null ? 0L : tenantId, + eventId, + "account-service", + "ACCOUNT_REGISTRATION", + occurredAt.getEpochSecond(), + occurredAt.getNano(), + 1, + 1, + digest(originalPayload), + minimized ? null : originalPayload, + minimized ? "MINIMIZED" : "COMMITTED", + minimized ? "NON_REPLAYABLE" : "ACCEPTED"); + } + + private void assertBackfilledReceipt( + String schema, + String receiptId, + String scope, + Long tenantId, + String eventId, + String status, + String outcome, + String timestamp) { + var receipt = + dsl.fetchOne( + "SELECT receipt.scope, receipt.tenant_id, receipt.tenant_key, receipt.audit_event_id, " + + "receipt.receipt_id, receipt.producer_service, receipt.event_type, " + + "receipt.occurred_at_seconds, receipt.occurred_at_nanos, receipt.schema_version, " + + "receipt.payload_digest_version, receipt.payload, receipt.payload_digest, " + + "receipt.status, receipt.outcome, receipt.log_event_id, event.id AS projection_id, " + + "event.type, event.message, event.timestamp, event.account_id FROM " + + schema + + ".account_audit_receipts AS receipt JOIN " + + schema + + ".log_events AS event ON event.id = receipt.log_event_id " + + "WHERE receipt.audit_event_id = ?", + eventId); + assertThat(receipt).isNotNull(); + assertThat(receipt.get("scope", String.class)).isEqualTo(scope); + assertThat(receipt.get("tenant_id", Long.class)).isEqualTo(tenantId); + assertThat(receipt.get("tenant_key", Long.class)).isEqualTo(tenantId == null ? 0L : tenantId); + assertThat(receipt.get("audit_event_id", String.class)).isEqualTo(eventId); + assertThat(receipt.get("receipt_id", UUID.class)).isEqualTo(UUID.fromString(receiptId)); + assertThat(receipt.get("producer_service", String.class)).isEqualTo("account-service"); + assertThat(receipt.get("event_type", String.class)).isEqualTo("ACCOUNT_REGISTRATION"); + Instant occurredAt = Instant.parse(timestamp + "Z"); + assertThat(receipt.get("occurred_at_seconds", Long.class)).isEqualTo(occurredAt.getEpochSecond()); + assertThat(receipt.get("occurred_at_nanos", Integer.class)).isEqualTo(occurredAt.getNano()); + assertThat(receipt.get("schema_version", Integer.class)).isEqualTo(1); + assertThat(receipt.get("payload_digest_version", Integer.class)).isEqualTo(1); + assertThat(receipt.get("payload_digest", String.class)) + .isEqualTo(digest("{\"retained\":true}".getBytes(StandardCharsets.UTF_8))); + assertThat(receipt.get("status", String.class)).isEqualTo(status); + assertThat(receipt.get("outcome", String.class)).isEqualTo(outcome); + assertThat(receipt.get("log_event_id", Long.class)) + .isEqualTo(receipt.get("projection_id", Long.class)); + assertThat(receipt.get("type", String.class)).isEqualTo("ACCOUNT_AUDIT"); + assertThat(receipt.get("message", String.class)).isEqualTo("Account audit event " + eventId); + assertThat(receipt.get("message", String.class)).doesNotContain("retained"); + assertThat(receipt.get("timestamp", LocalDateTime.class)) + .isEqualTo(LocalDateTime.parse(timestamp)); + assertThat(receipt.get("account_id", Long.class)).isNull(); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + schema + ".log_events WHERE audit_event_id = ?", + Integer.class, + eventId)) + .isEqualTo(1); + if ("MINIMIZED".equals(status)) { + assertThat(receipt.get("payload", byte[].class)).isNull(); + } else { + assertThat(receipt.get("payload", byte[].class)) + .isEqualTo("{\"retained\":true}".getBytes(StandardCharsets.UTF_8)); + } + } + private AccountAuditReceiptDto createAfter(CountDownLatch start, CreateLogEventRequest request) { try { if (!start.await(10, TimeUnit.SECONDS)) { From c9492c93763d0336b484a0f1da27162f0aabb4d6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:26:48 +1300 Subject: [PATCH 25/55] Satisfy Logging migration test static checks --- .../LoggingAdminApplicationIntegrationTest.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 478ffeb83c..ecf17ecf9d 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -308,8 +308,7 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { .isEqualTo(0L); assertThat( dsl.fetchValue( - "SELECT COUNT(*) FROM " + schema + ".account_audit_receipts", - Integer.class)) + "SELECT COUNT(*) FROM " + schema + ".account_audit_receipts", Integer.class)) .isEqualTo(4); assertThat( dsl.fetchValue( @@ -367,7 +366,7 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { "legacy insert", LocalDateTime.of(2025, 3, 1, 13, 0)); Long legacyLogId = - dsl.fetchOne( + dsl.fetchSingle( "SELECT id FROM " + schema + ".log_events WHERE message = ?", "legacy insert") .get("id", Long.class); assertThat( @@ -399,9 +398,7 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { "Account audit event 60000000-0000-4000-8000-000000000001"); assertThat( dsl.fetchValue( - "SELECT tenant_key FROM " - + schema - + ".log_events WHERE audit_event_id = ?", + "SELECT tenant_key FROM " + schema + ".log_events WHERE audit_event_id = ?", Long.class, "60000000-0000-4000-8000-000000000001")) .isEqualTo(86L); @@ -429,6 +426,7 @@ private void seedV2Receipt( Instant occurredAt, boolean minimized) { byte[] originalPayload = "{\"retained\":true}".getBytes(StandardCharsets.UTF_8); + long tenantKey = tenantId == null ? 0L : tenantId.longValue(); dsl.execute( "INSERT INTO " + schema @@ -439,7 +437,7 @@ private void seedV2Receipt( receiptId, scope, tenantId, - tenantId == null ? 0L : tenantId, + tenantKey, eventId, "account-service", "ACCOUNT_REGISTRATION", @@ -485,7 +483,8 @@ private void assertBackfilledReceipt( assertThat(receipt.get("producer_service", String.class)).isEqualTo("account-service"); assertThat(receipt.get("event_type", String.class)).isEqualTo("ACCOUNT_REGISTRATION"); Instant occurredAt = Instant.parse(timestamp + "Z"); - assertThat(receipt.get("occurred_at_seconds", Long.class)).isEqualTo(occurredAt.getEpochSecond()); + assertThat(receipt.get("occurred_at_seconds", Long.class)) + .isEqualTo(occurredAt.getEpochSecond()); assertThat(receipt.get("occurred_at_nanos", Integer.class)).isEqualTo(occurredAt.getNano()); assertThat(receipt.get("schema_version", Integer.class)).isEqualTo(1); assertThat(receipt.get("payload_digest_version", Integer.class)).isEqualTo(1); From 1ac0fed5b38027dffde55f59c4b7c1682282cd37 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:18:38 +1300 Subject: [PATCH 26/55] Supply saga schema placeholder in Logging migration proof --- .../loggingadmin/LoggingAdminApplicationIntegrationTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index ecf17ecf9d..9f9680cf04 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -239,6 +239,7 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { .locations("classpath:db/migration") .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .target(MigrationVersion.fromVersion("2")) .load() .migrate(); @@ -291,6 +292,7 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { .locations("classpath:db/migration") .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .load() .migrate(); From 1a87bf38f239782b5b7ce12e49ff736979c27c6f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:40:47 +1300 Subject: [PATCH 27/55] Use typed jOOQ reads in Logging migration proof --- ...oggingAdminApplicationIntegrationTest.java | 66 +++++++++---------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 9f9680cf04..2b428bb373 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -297,30 +297,30 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { .migrate(); assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM " + schema + ".log_events WHERE message = ?", - Integer.class, - "legacy payment log")) + dsl.fetchSingle( + "SELECT COUNT(*) FROM " + schema + ".log_events WHERE message = ?", + "legacy payment log") + .get(0, Integer.class)) .isEqualTo(1); assertThat( - dsl.fetchValue( - "SELECT tenant_key FROM " + schema + ".log_events WHERE message = ?", - Long.class, - "legacy payment log")) + dsl.fetchSingle( + "SELECT tenant_key FROM " + schema + ".log_events WHERE message = ?", + "legacy payment log") + .get(0, Long.class)) .isEqualTo(0L); assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM " + schema + ".account_audit_receipts", Integer.class)) + dsl.fetchSingle("SELECT COUNT(*) FROM " + schema + ".account_audit_receipts") + .get(0, Integer.class)) .isEqualTo(4); assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM " - + schema - + ".account_audit_receipts AS receipt LEFT JOIN " - + schema - + ".log_events AS event ON event.id = receipt.log_event_id " - + "WHERE event.id IS NULL", - Integer.class)) + dsl.fetchSingle( + "SELECT COUNT(*) FROM " + + schema + + ".account_audit_receipts AS receipt LEFT JOIN " + + schema + + ".log_events AS event ON event.id = receipt.log_event_id " + + "WHERE event.id IS NULL") + .get(0, Integer.class)) .isEqualTo(0); assertBackfilledReceipt( schema, @@ -372,19 +372,17 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { "SELECT id FROM " + schema + ".log_events WHERE message = ?", "legacy insert") .get("id", Long.class); assertThat( - dsl.fetchValue( - "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", - Long.class, - legacyLogId)) + dsl.fetchSingle( + "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", legacyLogId) + .get(0, Long.class)) .isEqualTo(0L); dsl.execute( "UPDATE " + schema + ".log_events SET tenant_id = ? WHERE id = ?", 85L, legacyLogId); assertThat( - dsl.fetchValue( - "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", - Long.class, - legacyLogId)) + dsl.fetchSingle( + "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", legacyLogId) + .get(0, Long.class)) .isEqualTo(0L); dsl.execute( @@ -399,10 +397,10 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { "ACCOUNT_AUDIT", "Account audit event 60000000-0000-4000-8000-000000000001"); assertThat( - dsl.fetchValue( - "SELECT tenant_key FROM " + schema + ".log_events WHERE audit_event_id = ?", - Long.class, - "60000000-0000-4000-8000-000000000001")) + dsl.fetchSingle( + "SELECT tenant_key FROM " + schema + ".log_events WHERE audit_event_id = ?", + "60000000-0000-4000-8000-000000000001") + .get(0, Long.class)) .isEqualTo(86L); assertThatThrownBy( @@ -503,10 +501,10 @@ private void assertBackfilledReceipt( .isEqualTo(LocalDateTime.parse(timestamp)); assertThat(receipt.get("account_id", Long.class)).isNull(); assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM " + schema + ".log_events WHERE audit_event_id = ?", - Integer.class, - eventId)) + dsl.fetchSingle( + "SELECT COUNT(*) FROM " + schema + ".log_events WHERE audit_event_id = ?", + eventId) + .get(0, Integer.class)) .isEqualTo(1); if ("MINIMIZED".equals(status)) { assertThat(receipt.get("payload", byte[].class)).isNull(); From 1d78cecec785d0f32842cba30598e5878ca7b4e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:00:37 +1300 Subject: [PATCH 28/55] Assert translated Logging audit constraint failure --- .../loggingadmin/LoggingAdminApplicationIntegrationTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 2b428bb373..7c263e4659 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -45,12 +45,12 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; -import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpHeaders; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; @@ -411,7 +411,8 @@ void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + "VALUES ('tenant', 73, 74, '50000000-0000-4000-8000-000000000001', " + "'ACCOUNT_AUDIT', 'mismatched key')")) - .isInstanceOf(DataAccessException.class); + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_scope_tenant"); } finally { dsl.execute("DROP SCHEMA " + schema + " CASCADE"); } From 8f7243577288c3285fac64cd4fecc069c7f679f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:45:31 +1300 Subject: [PATCH 29/55] Deny unsafe email verification RPC and harden local cert paths --- dev-tools/certs/ensure-dev-certs.sh | 39 +++++++++++++++ dev-tools/certs/generate-dev-certs.sh | 36 +++++++++++++ ...ocal-compose-workload-identity-contract.sh | 50 +++++++++++++++++++ .../service/impl/AccountGrpcService.java | 28 ++++------- .../service/impl/AccountGrpcServiceTest.java | 31 ++++++++++++ 5 files changed, 166 insertions(+), 18 deletions(-) diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 184b6a5332..0b15954231 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -8,6 +8,20 @@ WORKLOAD_NAMESPACE="local" WORKLOAD_DIR="$CERT_DIR/workloads" RUNTIME_DIR="$CERT_DIR/local-runtime" +refuse_symlink_path() { + local path="$1" + local description="$2" + local current_path="$path" + + while [[ "$current_path" != "." && "$current_path" != "/" ]]; do + [[ ! -L "$current_path" ]] || { + echo "refusing symlinked $description: $path" >&2 + exit 1 + } + current_path="$(dirname -- "$current_path")" + done +} + required_files=( "$CERT_DIR/ca.crt" "$CERT_DIR/ca.key" @@ -20,6 +34,31 @@ required_files=( "$CERT_DIR/server.key" ) +refuse_symlink_path "$CERT_DIR" "certificate directory" +for file in "${required_files[@]}"; do + refuse_symlink_path "$file" "certificate material" +done + +refuse_symlink_path "$WORKLOAD_DIR" "workload certificate directory" +for workload in account-service game-session-service social-groups-service; do + refuse_symlink_path "$WORKLOAD_DIR/$workload.crt" "workload certificate output" + refuse_symlink_path "$WORKLOAD_DIR/$workload.key" "workload private-key output" +done + +refuse_symlink_path "$RUNTIME_DIR" "local Compose runtime projection" +if [[ -d "$WORKLOAD_DIR" ]]; then + while IFS= read -r -d '' symlink_path; do + echo "refusing symlinked workload certificate path: $symlink_path" >&2 + exit 1 + done < <(find -P "$WORKLOAD_DIR" -mindepth 1 -maxdepth 1 -type l -print0) +fi +if [[ -d "$RUNTIME_DIR" ]]; then + while IFS= read -r -d '' symlink_path; do + echo "refusing symlink in local Compose runtime projection: $symlink_path" >&2 + exit 1 + done < <(find -P "$RUNTIME_DIR" -mindepth 1 -type l -print0) +fi + missing=0 for file in "${required_files[@]}"; do if [[ ! -f "$file" ]]; then diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 0dae8edb9c..ce997a26d2 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -3,6 +3,20 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +refuse_symlink_path() { + local path="$1" + local description="$2" + local current_path="$path" + + while [[ "$current_path" != "." && "$current_path" != "/" ]]; do + [[ ! -L "$current_path" ]] || { + echo "refusing symlinked $description: $path" >&2 + exit 1 + } + current_path="$(dirname -- "$current_path")" + done +} + if [[ "${1:-}" == "--workload" ]]; then umask 077 if [[ $# -ne 7 ]]; then @@ -16,6 +30,10 @@ if [[ "${1:-}" == "--workload" ]]; then output_key="$5" runtime_namespace="$6" workload="$7" + refuse_symlink_path "$ca_cert" "certificate authority source" + refuse_symlink_path "$ca_key" "certificate authority source" + refuse_symlink_path "$output_cert" "workload certificate output" + refuse_symlink_path "$output_key" "workload private-key output" for required_file in "$ca_cert" "$ca_key"; do [[ -f "$required_file" ]] || { echo "missing certificate authority file: $required_file" >&2 @@ -87,6 +105,24 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi +refuse_symlink_path "$CERT_DIR" "certificate directory" +generated_files=( + ca.crt ca.key ca.srl client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem + server.crt server.key server.csr dev-cert.cnf +) +for filename in "${generated_files[@]}"; do + refuse_symlink_path "$CERT_DIR/$filename" "certificate material" +done +if [[ -d "$CERT_DIR" ]]; then + while IFS= read -r -d '' symlink_path; do + echo "refusing symlinked certificate material: $symlink_path" >&2 + exit 1 + done < <(find -P "$CERT_DIR" -mindepth 1 -maxdepth 1 -type l \( \ + -name '*.crt' -o -name '*.key' -o -name '*.pem' -o -name '*.srl' -o -name '*.csr' \ + -o -name 'dev-cert.cnf' \ + \) -print0) +fi + if [ -f "$CERT_DIR/ca.crt" ] && [ -f "$CERT_DIR/ca.key" ] \ && [ -f "$CERT_DIR/client.crt" ] && [ -f "$CERT_DIR/client.key" ] \ && [ -f "$CERT_DIR/server.crt" ] && [ -f "$CERT_DIR/server.key" ] \ diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index 5402d7b673..1b73877332 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -145,6 +145,56 @@ assert_workload_certificate account-service exit 1 } +# Certificate authority sources and workload outputs must not follow symlinks; +# verify rejected paths leave their target content untouched. +symlink_ensure_dir="$CERT_DIR/symlink-ensure" +mkdir -p "$symlink_ensure_dir/workloads" +for file in ca.crt ca.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem server.crt server.key; do + cp "$CERT_DIR/$file" "$symlink_ensure_dir/$file" +done +printf 'protected CA source\n' >"$symlink_ensure_dir/ca-key-target" +rm "$symlink_ensure_dir/ca.key" +ln -s "$symlink_ensure_dir/ca-key-target" "$symlink_ensure_dir/ca.key" +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$symlink_ensure_dir"; then + echo "ensure-dev-certs accepted a symlinked CA source" >&2 + exit 1 +fi +[[ "$(<"$symlink_ensure_dir/ca-key-target")" == "protected CA source" ]] || { + echo "ensure-dev-certs modified a symlinked CA source target" >&2 + exit 1 +} +rm "$symlink_ensure_dir/ca.key" +cp "$CERT_DIR/ca.key" "$symlink_ensure_dir/ca.key" + +printf 'protected workload output\n' >"$symlink_ensure_dir/workload-key-target" +ln -s "$symlink_ensure_dir/workload-key-target" \ + "$symlink_ensure_dir/workloads/account-service.key" +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$symlink_ensure_dir"; then + echo "ensure-dev-certs accepted a symlinked workload output" >&2 + exit 1 +fi +[[ "$(<"$symlink_ensure_dir/workload-key-target")" == "protected workload output" ]] || { + echo "ensure-dev-certs modified a symlinked workload output target" >&2 + exit 1 +} + +symlink_generator_dir="$CERT_DIR/symlink-generator" +mkdir -p "$symlink_generator_dir" +printf 'protected generator key\n' >"$symlink_generator_dir/key-target" +ln -s "$symlink_generator_dir/key-target" "$symlink_generator_dir/output.key" +if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$CERT_DIR/ca.crt" "$CERT_DIR/ca.key" \ + "$symlink_generator_dir/output.crt" "$symlink_generator_dir/output.key" \ + local account-service; then + echo "generate-dev-certs accepted a symlinked workload output" >&2 + exit 1 +fi +[[ "$(<"$symlink_generator_dir/key-target")" == "protected generator key" \ + && ! -e "$symlink_generator_dir/output.crt" ]] || { + echo "generate-dev-certs modified a symlinked output target" >&2 + exit 1 +} + for compose_file in docker-compose.override.yml docker-compose.local-images.override.yml; do compose_path="$ROOT_DIR/docker/$compose_file" rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "false"' "$compose_path" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 343efe3588..146bc552de 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -806,24 +806,16 @@ public void requestEmailVerification( public void verifyEmail( net.firedevops.firemud.account.v1.VerifyEmailRequest request, StreamObserver responseObserver) { - try { - accountService.verifyEmail( - new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest(request.getToken())); - var response = - net.firedevops.firemud.account.v1.VerifyEmailResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.VerifyEmailResponse.newBuilder() - .setSuccess(false) - .setError(appError("VerifyEmail", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.VerifyEmailResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "VerifyEmail", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } private net.firedevops.firemud.shared.v1.ErrorDetail appError( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index ad03bd7c13..bccfe07dd0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -1642,6 +1642,37 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } + @Test + void verifyEmailFailsClosedBeforeTokenConsumption() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + + AtomicReference ref = + new AtomicReference<>(); + service.verifyEmail( + net.firedevops.firemud.account.v1.VerifyEmailRequest.newBuilder() + .setToken("verification-token") + .build(), + new StreamObserver() { + @Override + public void onNext(net.firedevops.firemud.account.v1.VerifyEmailResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertFalse(ref.get().getSuccess()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void deleteAccountRequiresAdminRole() { PingService pingService = Mockito.mock(PingService.class); From fac93d27b3aed1454770b5b5848794e52c2f58e2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 07:17:27 +1300 Subject: [PATCH 30/55] Replay exact terminal JOIN outcomes after scope expiry --- .../service/impl/AccountServiceImpl.java | 4 - .../service/impl/AccountServiceImplTest.java | 282 +++++++++++++----- 2 files changed, 202 insertions(+), 84 deletions(-) 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 5d2b5a7ea7..bbac1a8ee5 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 @@ -786,10 +786,6 @@ private JoinPublicProductionResult pendingJoinFailure( private JoinPublicProductionResult replayTerminalJoin( JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { - if (isConnectScopeExpired(scope)) { - return joinRetryFailure(scope, "CONNECT_SCOPE_INVALID"); - } - JoinEvaluation evaluation; try { evaluation = evaluateJoin(scope); 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 0911dd1bcf..3d9c84c957 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 @@ -932,8 +932,17 @@ void expiredPersistedPendingJoinRemainsPendingWithoutAuthorityOrMembershipReads( subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); } - @Test - void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { + @ParameterizedTest + @CsvSource({ + "COMMITTED, JOINED, true, active, true", + "FAILED, PUBLIC_PRODUCTION_ADMISSION_DENIED, false, grace, false" + }) + void exactTerminalJoinRetryReplaysAfterConnectScopeExpiry( + String status, + String outcome, + boolean allowPublicJoin, + String entitlementStatus, + boolean expectedSuccess) { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -950,42 +959,18 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { AtomicReference retainedOperation = new AtomicReference<>(); retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = "expired-committed-connect-scope"; + Subscription currentPolicy = new Subscription(); + currentPolicy.setId(22L); + currentPolicy.setTenantId(7L); + currentPolicy.setStatus(entitlementStatus); + currentPolicy.setEntitlementVersion(1L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn(java.util.List.of(currentPolicy)); + + String connectScopeId = expiredConnectScopeId(); JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-expired-committed-1"); - VerifiedJoinScope unsignedExpiredScope = - new VerifiedJoinScope( - connectScopeId, - 11L, - 7L, - UUID.fromString(REALM_ID), - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L, - "1999-12-31T23:59:00Z", - "2000-01-01T00:00:00Z", - ""); - VerifiedJoinScope expiredScope = - new VerifiedJoinScope( - unsignedExpiredScope.connectScopeId(), - unsignedExpiredScope.accountId(), - unsignedExpiredScope.tenantId(), - unsignedExpiredScope.realmId(), - unsignedExpiredScope.worldSlug(), - unsignedExpiredScope.realmSlug(), - unsignedExpiredScope.playableStateNamespaceId(), - unsignedExpiredScope.playableStateScope(), - unsignedExpiredScope.gameInstanceId(), - unsignedExpiredScope.catalogRevision(), - unsignedExpiredScope.pointerVersion(), - unsignedExpiredScope.evaluatedAt(), - unsignedExpiredScope.connectScopeExpiresAt(), - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( - unsignedExpiredScope)); + new JoinPublicProductionRequest(connectScopeId, "join-expired-terminal-1"); + VerifiedJoinScope expiredScope = expiredVerifiedJoinScope(connectScopeId); retainedScope.set(expiredScope); String callerBinding = new JwtUtil(JWT_SECRET, 300000L) @@ -993,56 +978,48 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { .getPayload() .get("jti") .toString(); - var committedOperation = - new AccountJoinOperationRepository.JoinOperation( + var terminalOperation = + terminalJoinOperation( request.requestId(), - expiredScope.accountId(), - expiredScope.tenantId(), - expiredScope.realmId(), - expiredScope.worldSlug(), - expiredScope.realmSlug(), - expiredScope.playableStateNamespaceId(), - expiredScope.playableStateScope(), - expiredScope.gameInstanceId(), - expiredScope.catalogRevision(), - expiredScope.pointerVersion(), + expiredScope, callerBinding, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), - expiredScope.snapshotDigest(), - "AVAILABLE", - true, - 1L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( - expiredScope, callerBinding, true, 1L), - "COMMITTED", - "JOINED", - 701L, - 1L, - 1L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - request.requestId(), expiredScope, callerBinding), - null, - "AVAILABLE", - 0, - null, - null, - java.time.Instant.now()); - retainedOperation.set(committedOperation); + status, + outcome, + allowPublicJoin, + false); + retainedOperation.set(terminalOperation); JoinPublicProductionResult retry = service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertFalse(retry.success()); - assertFalse(retry.replayed()); - assertEquals("CONNECT_SCOPE_INVALID", retry.outcomeCode()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals("COMMITTED", retainedOperation.get().status()); - assertEquals("JOINED", retainedOperation.get().outcome()); - assertEquals(701L, retainedOperation.get().membershipId()); + assertEquals(expectedSuccess, retry.success()); + assertTrue(retry.replayed()); + assertEquals(outcome, retry.outcomeCode()); + assertEquals(terminalOperation, retainedOperation.get()); + assertEquals(status, retainedOperation.get().status()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + verifyNoInteractions(accountAuditOutboxRepository); + + var mismatchedIntent = + terminalJoinOperation( + request.requestId(), + expiredScope, + callerBinding, + status, + outcome, + allowPublicJoin, + true); + retainedOperation.set(mismatchedIntent); + AuthenticationException intentConflict = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + + assertEquals("IDEMPOTENCY_CONFLICT", intentConflict.getCode()); + assertEquals(mismatchedIntent, retainedOperation.get()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantIdForUpdate(7L); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) .finish( org.mockito.ArgumentMatchers.anyString(), @@ -1051,7 +1028,152 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { org.mockito.ArgumentMatchers.nullable(Long.class), org.mockito.ArgumentMatchers.nullable(Long.class), org.mockito.ArgumentMatchers.nullable(Long.class)); - verifyNoInteractions(subscriptionRepository, accountAuditOutboxRepository); + } + + @Test + void newJoinRejectsExpiredConnectScopeBeforePersistingIntent() { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException expiredScope = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest( + expiredConnectScopeId(), "join-expired-new-1"))); + + assertEquals("CONNECT_SCOPE_INVALID", expiredScope.getCode()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + verifyNoInteractions( + accountConnectScopeRepository, + accountTenantMembershipRepository, + subscriptionRepository, + accountAuditOutboxRepository); + } + + private VerifiedJoinScope expiredVerifiedJoinScope(String connectScopeId) { + VerifiedJoinScope unsignedScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + return new VerifiedJoinScope( + unsignedScope.connectScopeId(), + unsignedScope.accountId(), + unsignedScope.tenantId(), + unsignedScope.realmId(), + unsignedScope.worldSlug(), + unsignedScope.realmSlug(), + unsignedScope.playableStateNamespaceId(), + unsignedScope.playableStateScope(), + unsignedScope.gameInstanceId(), + unsignedScope.catalogRevision(), + unsignedScope.pointerVersion(), + unsignedScope.evaluatedAt(), + unsignedScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(unsignedScope)); + } + + private String expiredConnectScopeId() { + return new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "11", + -1000L, + 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", "production"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", 44L), + Map.entry("catalogRevision", 23L), + Map.entry("pointerVersion", 17L), + Map.entry("evaluatedAt", "1999-12-31T23:59:00Z"), + Map.entry("connectScopeExpiresAt", "2000-01-01T00:00:00Z"), + Map.entry("jti", "expired-connect-scope"))); + } + + private AccountJoinOperationRepository.JoinOperation terminalJoinOperation( + String requestId, + VerifiedJoinScope scope, + String callerBinding, + String status, + String outcome, + boolean allowPublicJoin, + boolean corruptIntentDigest) { + String intentDigest = + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + requestId, scope, callerBinding); + if (corruptIntentDigest) { + intentDigest = "corrupt-" + intentDigest; + } + boolean committed = "COMMITTED".equals(status); + return new AccountJoinOperationRepository.JoinOperation( + requestId, + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId()), + scope.snapshotDigest(), + "AVAILABLE", + allowPublicJoin, + 1L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( + scope, callerBinding, allowPublicJoin, 1L), + status, + outcome, + committed ? 701L : null, + committed ? 1L : null, + committed ? 1L : null, + 1, + intentDigest, + null, + "AVAILABLE", + 0, + null, + null, + java.time.Instant.now()); } @Test From 70ff376508b2e0724efbdb29f4da5e75ea1f5ce6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 07:17:49 +1300 Subject: [PATCH 31/55] Qualify PLAY proof behind contained Account runtime reads --- .../account-service/runtime-and-data.md | 8 ++++---- .../microservices/tcp-proxy-service/README.md | 4 ++-- .../microservices/tcp-proxy-service/protocols.md | 16 ++++++++-------- .../player-access-and-session.md | 4 ++-- ...ayer-experience-commands-and-communication.md | 4 ++-- .../realm-routing-and-playable-state.md | 6 +++--- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index cc9c5c3327..33bcefbf84 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -20,7 +20,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 are denied before Account reads until a typed verified player/target contract and consumer are implemented. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks caller-bound membership existence and admission after fresh entitlement and target checks. For Account connect-token issuance and character discovery, only missing membership on an eligible public-production target may return `JOIN_REQUIRED`; a present non-admitting membership is denied without `JOIN_REQUIRED`, and the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Current text `PLAY` also consumes the four runtime fields and still may return `JOIN_REQUIRED` for missing or present non-admitting membership on an eligible public-production target, as tracked for Unit 1B, before fresh entitlement-availability and `allowPublicJoin` checks; unavailable or denied authority must not be classified as a join opportunity. These paths do not create or restore membership. 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 runtime membership proto/response shape carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The live gRPC membership, realm-grant, and entitlement handlers require the trusted Game Session peer and then return `FAILED_PRECONDITION` before reading Account data because the current requests cannot prove caller/target binding. Response-classification branches exercised with supplied authority in local unit tests therefore do not establish a live admission snapshot; the complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` also remain absent. 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. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks caller-bound membership existence and admission after fresh entitlement and target checks. For Account connect-token issuance and character discovery, only missing membership on an eligible public-production target may return `JOIN_REQUIRED`; a present non-admitting membership is denied without `JOIN_REQUIRED`, and the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Game Session `PLAY` contains conditional response-classification logic for missing or `INACTIVE` public-production membership, but the live Account handlers return `FAILED_PRECONDITION`, which Game Session maps to `WORLD_ACCESS_DENIED`; no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. These paths do not create or restore membership. 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 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. @@ -141,7 +141,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 runtime requires existing caller-bound membership for character discovery, connect-token issuance, and text `PLAY` and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. For a publicly visible public-production target whose joining policy permits entry, `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED` without creating or restoring membership; the latter response 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. Current Account character discovery and connect-token issuance have local membership checks; the live Game Session runtime membership/entitlement/grant gRPC handlers reject before reading Account data. Game Session `PLAY` has focused response-classification branches for supplied authority, but the live membership failure maps to `WORLD_ACCESS_DENIED`, so a composed public `JOIN_REQUIRED` is not established. World and realm discovery remain available before membership. Explicit `JOIN` is a separate local action and does not establish complete direct-text admission. - 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. - 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. @@ -178,7 +178,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`. Although the proto and service response model include `membershipLifecycleState` and the opaque generation, the live gRPC handler rejects before reading and does not return that response. Focused consumer unit tests use supplied authority; they do not prove runtime enforcement. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. - `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. @@ -270,7 +270,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### Runtime Implementation Status and Drift -Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED` from Account connect-token issuance or character discovery. A present non-admitting membership is denied without `JOIN_REQUIRED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Current text `PLAY` still may return `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target, as tracked for Unit 1B. The local explicit `JOIN`/`Join & Play` operation, Account route/RPC, controller, and Game Session text dispatch exist, but they do not prove the complete direct text-client flow. Current non-public mappings differ by surface: Account connect-token issuance and character discovery return `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. A bounded Account-owned worker revisits abandoned `PENDING` JOIN intents and terminalizes only exact positive operation/scope/membership/audit readback; it does not infer a prior transition from expiry alone or absent evidence, and absent or uncertain evidence remains pending with capped attempt diagnostics and caller retry. PostgreSQL exact-final-head and lost-acknowledgement/concurrency proof, recovery/reconciliation after unknown JOIN commit outcomes, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. +Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED` from Account connect-token issuance or character discovery. A present non-admitting membership is denied without `JOIN_REQUIRED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. The runtime membership, entitlement, and grant gRPC handlers reject with `FAILED_PRECONDITION` before Account reads after trusted-peer validation. Game Session text `PLAY` response-classification and private-grant branches have focused unit coverage with supplied authority, but a live Account rejection is mapped to `WORLD_ACCESS_DENIED`; no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. The local explicit `JOIN`/`Join & Play` operation, Account route/RPC, controller, and Game Session text dispatch exist, but they do not prove the complete direct text-client flow. The remaining target gaps and proof status are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) and canonical admission behavior is owned by [Authentication](../../system-architecture-authentication.md#implementation-status). A bounded Account-owned worker revisits abandoned `PENDING` JOIN intents and terminalizes only exact positive operation/scope/membership/audit readback; it does not infer a prior transition from expiry alone or absent evidence, and absent or uncertain evidence remains pending with capped attempt diagnostics and caller retry. PostgreSQL exact-final-head and lost-acknowledgement/concurrency proof, recovery/reconciliation after unknown JOIN commit outcomes, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. ## Monetization and Notification Domain Notes diff --git a/design/architecture/microservices/tcp-proxy-service/README.md b/design/architecture/microservices/tcp-proxy-service/README.md index 21929ea379..69de6f99df 100644 --- a/design/architecture/microservices/tcp-proxy-service/README.md +++ b/design/architecture/microservices/tcp-proxy-service/README.md @@ -24,7 +24,7 @@ When code, tests, and docs diverge, align implementation to this doc set and the | Area | Target behaviour | Current status | Tracked in | | --- | --- | --- | --- | -| Telnet login-first flow | All Telnet clients must issue anonymous `WORLDS` before credential-bearing `LOGIN [secret]`; `LOGIN ` starts the email challenge. For public production, missing or `INACTIVE` membership must issue `JOIN` before `PLAY`; only an existing `ACTIVE` public-production member skips `JOIN`. Telnet shares the same admission pipeline as WebSocket clients. Any future classic-client semantic adapter is optional and cannot replace the plain-text flow or carry authority. `LOGIN` / `LOGON` semantics remain canonical in the Authentication & Authorization doc; this row only describes how Telnet traffic is forwarded into that flow. | `LOGIN [secret]` and `PLAY` are implemented with focused proof for currently supported, already-authorized admission. The current proxy still bootstraps a hidden default and does not enforce `WORLDS` before `LOGIN`; that is an implementation gap. For a publicly visible public-production target whose joining policy permits entry, missing or non-admitting membership returns `JOIN_REQUIRED` from `PLAY` without implicit membership mutation; other targets retain their own visibility and grant checks. The Account JOIN RPC and direct-text REALMS-scope/JOIN dispatch now exist locally, but PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and membership lifecycle/generation rereads remain unproved. The connect-token membership-authority-generation reread also remains a gap. Manual end-to-end QA remains outstanding. | [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) | +| Telnet login-first flow | All Telnet clients must issue anonymous `WORLDS` before credential-bearing `LOGIN [secret]`; `LOGIN ` starts the email challenge. For public production, missing or `INACTIVE` membership must issue `JOIN` before `PLAY`; only an existing `ACTIVE` public-production member skips `JOIN`. Telnet shares the same admission pipeline as WebSocket clients. Any future classic-client semantic adapter is optional and cannot replace the plain-text flow or carry authority. `LOGIN` / `LOGON` semantics remain canonical in the Authentication & Authorization doc; this row only describes how Telnet traffic is forwarded into that flow. | Local `PLAY` response-classification tests exercise supplied Account authority, and the Account JOIN RPC plus direct-text REALMS-scope/JOIN dispatch exist locally. The live Account membership, entitlement, and grant handlers return `FAILED_PRECONDITION` before reading data, which Game Session maps to `WORLD_ACCESS_DENIED`; no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. The proxy still bootstraps a hidden default and does not enforce `WORLDS` before `LOGIN`. PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and membership lifecycle/generation rereads remain unproved. | [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) | | Proxy -> Gateway WebSocket mTLS | TCP Proxy is the WebSocket mTLS client: it presents the dedicated `FIREMUD_GATEWAY_WS_CLIENT_CERT_CHAIN_PATH` and `FIREMUD_GATEWAY_WS_CLIENT_PRIVATE_KEY_PATH` identity to the Gateway server, with `FIREMUD_GATEWAY_WS_CA_CERT_PATH` for trust, while Gateway verifies the exclusive environment-bound identity required by [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). This client identity is distinct from TCP Proxy's internal gRPC server mTLS identity and from the separate Telnet server-TLS identity. | TCP Proxy now loads and rotates the dedicated PEM client identity and Gateway CA into one hostname-verifying client shared by gameplay bridges and Gateway readiness, rejects plaintext unless an explicit local/dev/test profile is active, and fails new admission closed after an invalid reload. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with the dedicated authenticated Gateway listener, separate Gateway-server/TCP-Proxy-client Secret mounts, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending; controller-owned certificate issuance/projection and live peer-handshake, rotation/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. | [Platform Operations and Delivery](../../../project-management/implementation-tracking/platform-operations-and-delivery.md) | | Optional classic-client semantic extensions | Plain text remains universal. MCP/GMCP/Telnet semantic negotiation and package support are deferred, unadvertised, and unsupported in shared, player-facing, and prod-like profiles; an explicit local/development/test profile may enable only the legacy marker/greeting seam for bounded development use. If a future adapter is selected, Game Session owns semantics while TCP Proxy remains a generic bounded bridge. | The current `TCP_PROXY_MCP_ENABLED` marker/greeting seam is implementation drift, not semantic support. Target startup rejects it in shared, player-facing, and prod-like profiles; only explicit local/development/test profiles may enable the marker, and the profile rejection is not yet proved. No interoperability or end-to-end extension proof exists. | [MCP-01](../../decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | | Connection limits and abuse protection | Connection caps, idle timeouts, input size limits, buffering, and generic opaque-marker safety protect the DMZ boundary. TCP Proxy does not parse or maintain classic-client semantic state. Accepted input that exceeds a generic limit or cannot be forwarded under backpressure receives an explicit error/close rather than a keep-open silent discard. | Core limit handling is implemented; tuning and additional metrics may evolve as production behaviour is observed. | [Platform Operations and Delivery](../../../project-management/implementation-tracking/platform-operations-and-delivery.md) | @@ -47,7 +47,7 @@ Public Telnet TLS is configured as one of two mutually exclusive modes: a dedica - `readiness` is traffic-admission safety for new Telnet sessions. The service is ready only when: - the Telnet listener is bound; - the proxy can reach Spring Cloud Gateway’s readiness surface for the gameplay route; and - - the downstream gameplay admission path supports the currently implemented admission path `connect -> LOGIN [secret] -> PLAY -> first LOOK` for callers with the required existing membership and target-specific visibility/grant authority. + - the downstream gameplay admission path supports the currently implemented admission path `connect -> LOGIN [secret] -> PLAY -> first LOOK` when its required Account authority is available. Current Account runtime membership/entitlement/grant handlers reject before reading, so successful composed gameplay admission through that path is not established. - While unready, the proxy must reject new Telnet sessions immediately with an explicit startup/unavailable message and close the connection. It must not silently accept the socket and let the first gameplay command discover startup races later. - Loss of downstream readiness after a session is already established blocks new sessions but does not by itself imply that the proxy process is dead. - Readiness transition observability uses the shared contract from [Deployment Environments](../../infrastructure/deployment-environments.md): `firemud.readiness.current`, `firemud.readiness.transitions`, and structured logs keyed by the curated dependency names `telnetListener` and `gatewayGameplayPath`. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index 3896d82fc3..38f68ea65b 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -6,13 +6,13 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory ## Implementation Status -The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. +The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache. Its handler requests a fresh Account membership read, but Account's live runtime handler returns `FAILED_PRECONDITION` before reading data; Game Session maps that response to `WORLD_ACCESS_DENIED`, so the entitlement and realm-grant reads do not establish a composed live admission path. -The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof, and the target independent issuance baseline/generation/version reread remains unproved. Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check; for public-production missing or non-admitting membership it evaluates fresh entitlement/public policy before `JOIN_REQUIRED`, and for private/playtest targets it performs the applicable current realm-grant check. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. -The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` always performs fresh membership and applicable private/playtest grant checks, regardless of any connect-token replay-cache state. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). +The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof, and the target independent issuance baseline/generation/version reread remains unproved. Text `PLAY` is independent of connect-token replay-cache state, but its live Account membership RPC returns `FAILED_PRECONDITION` before reading and Game Session maps that response to `WORLD_ACCESS_DENIED`; downstream entitlement and realm-grant branches are not reached through the live handlers. Local unit response-classification coverage with supplied authority does not establish `JOIN_REQUIRED` or successful composed public `PLAY`. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. +The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` does not use that cache, but its live Account membership request fails before data access, so applicable entitlement and private/playtest grant checks are not reached. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). The Telnet credential form is `LOGIN [secret]`. `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. -The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but the target independent issuance baseline/reread and private/playtest grant check remain implementation and proof gaps. For an eligible public-production target with missing or non-admitting membership, text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or policy denial wins. These local gaps do not change the Authentication-owned admission outcomes. -The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients have a local `LOGIN` -> `PLAY` -> `LOOK` path for existing admitting members; when `PLAY` returns `JOIN_REQUIRED`, the client can issue `JOIN` and retry `PLAY` before `LOOK`. Focused local JOIN proof exists, while full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Missing or existing non-admitting eligible public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement/public policy permits joining, and direct text can invoke the Account-backed writer. Missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. +Game Session `PLAY` contains response-classification logic for Account membership and later entitlement/grant evidence, and focused unit tests exercise those branches with supplied authority. In the live composition, Account's runtime membership handler rejects with `FAILED_PRECONDITION` before reading data and Game Session maps that response to `WORLD_ACCESS_DENIED`, so no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. Connect-token issuance and the typed runtime-read contract have separate implementation and proof gaps. Canonical admission outcomes remain owned by [Authentication](../../system-architecture-authentication.md#implementation-status). +The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct-text `JOIN` dispatch and the Account writer exist locally, but the live runtime membership handler's `FAILED_PRECONDITION` currently maps `PLAY` to `WORLD_ACCESS_DENIED` before entitlement, grant, or `JOIN_REQUIRED` branches can run. Unit-level classification with supplied Account responses is not proof of live admission; full Telnet discovery/bridge and PostgreSQL/recovery proof also remain open. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. ## Cross-Path Connectivity Contract @@ -24,13 +24,13 @@ The following are canonical contracts across Telnet and WebSocket paths: ## Recommended Telnet Client Flows -These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. Direct-text `JOIN` is implemented and focused locally, but full Telnet discovery/bridge proof remains open. Current text `PLAY` validates the lifecycle/version/generation membership evidence and evaluates fresh public entitlement/policy before returning `JOIN_REQUIRED` for an otherwise eligible missing or `INACTIVE` public-production membership; only an existing `ACTIVE` member skips `JOIN`. The target connect-token membership-authority-generation/version baseline reread remains a separate gap. +These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. Direct-text `JOIN` is implemented and focused locally, but full Telnet discovery/bridge proof remains open. The `PLAY` handler's lifecycle/version/generation and entitlement classifications are conditional local branches; the live Account membership handler rejects before reading, and Game Session maps that to `WORLD_ACCESS_DENIED`. No live `JOIN_REQUIRED` or successful composed public `PLAY` is established through these handlers. The target connect-token membership-authority-generation/version baseline reread remains a separate gap. - **Target canonical player flow** - Connect to the TCP Proxy Service. - Perform fresh public-world discovery with `WORLDS`. This direct text flow does not consume a first-party WebSocket discovery snapshot. - Use `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` authenticates immediately. Complete the applicable secret or verified-email-code response before continuing, then perform authenticated `REALMS` discovery as needed. - - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; its local Account route/RPC and Game Session text dispatch exist, while the full discovery-first sequence and end-to-end proof remain incomplete. Current text reconnect may stop with non-actionable `JOIN_REQUIRED` when the current response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false` for an eligible public-production request; the latter cannot be classified as `INACTIVE`. Target behavior also returns `JOIN_REQUIRED` for `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, while target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. + - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; its local Account route/RPC and Game Session text dispatch exist, while the full discovery-first sequence and end-to-end proof remain incomplete. The live Account membership handler currently rejects before reading, so text reconnect maps that response to `WORLD_ACCESS_DENIED`; local unit classification for supplied missing or `INACTIVE` membership does not establish a live `JOIN_REQUIRED`. Target behavior returns `JOIN_REQUIRED` for missing or `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. - If no valid selected character exists after the conditional membership step, use `CHARS [realm]` or the character-creation flow to select or create it; then enter gameplay with `PLAY [realm] [character]`. - The Telnet wire never carries `connectScopeId`, `PlayerExecutionContext`, `playableStateScope`, or storage keys. Game Session retains any target-bound scope locally and derives `playableStateScope` for the character query from the exact server-side realm snapshot; Account separately validates the authenticated caller context, and the proxy only forwards the player-facing selectors and commands. - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. @@ -103,7 +103,7 @@ Typed `SESSION` gameplay lines are no longer part of the Telnet contract. TCP Pr Current rules: -- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`, but its local text flow supports `LOGIN` -> `PLAY` -> `LOOK` for existing admitting members or `LOGIN` -> `PLAY` (`JOIN_REQUIRED`) -> `JOIN` -> `PLAY` -> `LOOK` when joining is required. It validates Account membership lifecycle/version/generation evidence and, for an otherwise eligible public-production missing or `INACTIVE` membership, fresh entitlement/public policy before returning `JOIN_REQUIRED`; direct text can then invoke the implemented Account-backed writer. Current private/playtest text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED` and checks the current realm grant; the complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remains unproved end to end; +- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`. Game Session's local `PLAY` branches classify supplied Account membership/lifecycle and entitlement responses, but the live Account membership handler rejects before reading and Game Session maps `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`; the live path does not reach `JOIN_REQUIRED` or the later realm-grant check. Direct-text `JOIN` dispatch and the Account writer exist locally, but successful composed public `PLAY` and the complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remain unproved; - the proxy bootstraps hidden default gameplay instance and tenant metadata for the connection and, when configured coherently, forwards the server-owned `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` routing bundle only across the authenticated Proxy -> Gateway hop; Gateway validates the all-or-none bundle and forwards it as advisory Game Session context without replacing direct `LOGIN` / `PLAY` admission; - current proxy behavior forwards `WORLDS` but also bootstraps hidden default routing and does not enforce the discovery command, so the fresh-discovery requirement remains a target gap; - typed attach hints and semantic extension negotiation do not exist on the player-facing wire contract; 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 1fea9d0f21..95af0dfc6a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -57,11 +57,11 @@ These links add decision provenance only; they do not upgrade player-access or s | `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 gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; 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. Missing or `INACTIVE` public membership receives `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` permit joining; an `ACTIVE` non-admitting member is denied without JOIN advice, and unavailable evidence remains retryable. Current `PLAY` loads the character roster through the authenticated account, tenant, selected instance, and playable-state scope, then validates those identities on each returned character. This focused implementation and test evidence does not establish namespace-aware actor revalidation or target binding-generation fencing. Account runtime admission reads currently deny before data access pending the typed caller/target contract, so these handler checks do not prove a successful live admission flow. Explicit JOIN exists locally through Account's public-production writer and Game Session dispatch, but direct text-client proof remains open; the membership-authority-generation reread at connect-token issuance and generic prompt-mode login remain gaps. Account's bounded readback worker revisits abandoned JOIN `PENDING` operations; PostgreSQL recovery/concurrency and direct-text proof remain unexecuted 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 and account-first bootstrap exist. 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 prior gameplay context; an exact same-account reconnect may preserve only a candidate context for fresh admission checks. `PlayCommandHandler` contains membership/lifecycle and later entitlement/grant response-classification branches, with focused unit coverage using supplied authority. Live Account membership, entitlement, and grant handlers reject with `FAILED_PRECONDITION` before reading data, so Game Session maps the live membership response to `WORLD_ACCESS_DENIED`; no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. Connect-token issuance and character discovery have separate Account-owned behavior. `PLAY` roster loading has focused proof for authenticated account, tenant, selected instance, and playable-state scope, but this does not establish namespace-aware actor revalidation or target binding-generation fencing. Explicit JOIN exists locally through Account's public-production writer and Game Session dispatch, but direct text-client proof remains open; the membership-authority-generation reread at connect-token issuance and generic prompt-mode login remain gaps. Account's bounded readback worker revisits abandoned JOIN `PENDING` operations; PostgreSQL recovery/concurrency and direct-text proof remain unexecuted 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, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current text handling rejects `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. This fail-closed behavior is partial progress, not durable logout/replay completion: namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. 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) | Current player text handling rejects `LOGOUT` before side effects; this is a fail-closed boundary and does not provide seamless logout. The durable successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account player-bootstrap character discovery checks caller-bound membership after fresh entitlement and target checks: only missing membership on an eligible public-production target returns `JOIN_REQUIRED`; an existing non-admitting membership is denied without `JOIN_REQUIRED` and cannot currently be classified as `INACTIVE`. Pre-membership world and realm discovery remains available. Text `PLAY` likewise returns `JOIN_REQUIRED` only for missing or `INACTIVE` membership on an eligible public-production target, after fresh entitlement and `allowPublicJoin` checks; active non-admitting membership is denied without JOIN advice, and unavailable evidence remains retryable. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, and a bounded Account-owned readback worker now revisits abandoned `PENDING` intents; PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account player-bootstrap character discovery checks caller-bound membership after fresh entitlement and target checks: only missing membership on an eligible public-production target returns `JOIN_REQUIRED`; an existing non-admitting membership is denied without `JOIN_REQUIRED` and cannot currently be classified as `INACTIVE`. Pre-membership world and realm discovery remains available. Text `PLAY` has focused unit response-classification coverage for supplied missing/`INACTIVE` membership and fresh entitlement/policy, but live Account membership/entitlement/grant handlers reject before reading, and Game Session maps that response to `WORLD_ACCESS_DENIED`; no composed live `JOIN_REQUIRED` or successful public `PLAY` through these handlers is established. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is implemented locally through Account, and a bounded Account-owned readback worker revisits abandoned `PENDING` intents; PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 9a6d5de8df..d0fbe26e21 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -49,9 +49,9 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the direct gameplay-binding path for existing members. Realm and character discovery helpers are currently not required ceremony. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. An unambiguous eligible `PLAY` enters directly; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path. Realm and character discovery helpers are currently not required ceremony. `PlayCommandHandler` has focused unit response-classification coverage for supplied missing/`INACTIVE` public membership and fresh entitlement/policy evidence. In the live composition, Account's trusted-peer runtime membership, entitlement, and grant handlers return `FAILED_PRECONDITION` before reading; Game Session maps the membership response to `WORLD_ACCESS_DENIED`, and no successful composed public `PLAY` or live `JOIN_REQUIRED` through those handlers is established. Account connect-token issuance has separate current checks and outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority retains the applicable unavailable/invalid-authority outcome. An unambiguous eligible `PLAY` branch enters directly when its required authority is supplied; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical admission behavior and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispatch now exist locally; the browser bootstrap facade is present, but its public Gateway route remains denied and target-only. Account's transactional audit outbox and Logging receipt handling are also implemented locally. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, and direct text-to-Logging end-to-end coverage; a bounded Account worker now reads back abandoned JOIN `PENDING` intents, but that does not prove those runtime/recovery outcomes. The Account producer exposes lifecycle/generation snapshot evidence and the implemented `PLAY` checks consume that boundary; complete event/authority-tuple propagation and reconnect-freshness proof remain incomplete, as does the connect-token membership-authority-generation reread. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings are implemented and covered by focused `PlayCommandHandlerTest` and `AccountServiceImplTest` cases; that focused proof does not establish the complete JOIN flow. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispatch now exist locally; the browser bootstrap facade is present, but its public Gateway route remains denied and target-only. Account's transactional audit outbox and Logging receipt handling are also implemented locally. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, and direct text-to-Logging end-to-end coverage; a bounded Account worker now reads back abandoned JOIN `PENDING` intents, but that does not prove those runtime/recovery outcomes. The proto/producer exposes lifecycle/generation fields, and focused `PlayCommandHandlerTest` cases exercise `JOIN_REQUIRED` classification with supplied membership and fresh entitlement/policy responses. Live Account runtime readers still reject before data access, so that conditional unit behavior does not establish a live `JOIN_REQUIRED` or successful public `PLAY`; Game Session maps the live `FAILED_PRECONDITION` response to `WORLD_ACCESS_DENIED`. Complete event/authority-tuple propagation and reconnect-freshness proof remain incomplete, as does the connect-token membership-authority-generation reread. Connect-token missing-membership/policy-denial mappings have focused `AccountServiceImplTest` coverage. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation 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 ce731393de..27a3339322 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 @@ -55,9 +55,9 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed; the canonical `JoinPublicProductionMembership` writer is implemented locally, including lifecycle-aware membership fields, policy-bound idempotency, and the membership/audit outbox transaction. Current Account membership reads and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; `PLAY` admits only an exact safe active snapshot. Missing or `INACTIVE` public membership receives `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` permit joining; an `ACTIVE` non-admitting member is denied without JOIN advice, and unavailable evidence remains retryable. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. Game Session's direct-text `JOIN` path now retrieves the retained REALMS scope/request state and invokes that Account writer; this local invocation and writer do not establish the complete first-party `Join & Play` or direct-text/Telnet flow. Account has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but its PostgreSQL lost-acknowledgement/concurrency and recovery/reconciliation proof remains open; expiry or absent evidence does not create terminal outcomes. Account runtime membership, entitlement, and grant handlers deny before data reads until typed caller/target binding is available; this containment is not live runtime admission. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed; the canonical `JoinPublicProductionMembership` writer is implemented locally, including lifecycle-aware membership fields, policy-bound idempotency, and the membership/audit outbox transaction. The runtime proto and Game Session handler contain membership/lifecycle and subsequent entitlement/grant response-classification branches; focused unit coverage uses supplied authority. Live Account membership, entitlement, and grant handlers validate the trusted peer, then return `FAILED_PRECONDITION` before reading data. Game Session maps the membership failure to `WORLD_ACCESS_DENIED`, so no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. For non-public realms, current connect-token issuance has its own mapping, but text `PLAY` does not reach its grant check through the live handlers. Game Session's direct-text `JOIN` path retrieves the retained REALMS scope/request state and invokes the Account writer locally; this does not establish the complete first-party `Join & Play` or direct-text/Telnet flow. Account has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but its PostgreSQL lost-acknowledgement/concurrency and recovery/reconciliation proof remains open; expiry or absent evidence does not create terminal outcomes. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; canonical admission behavior and its current status remain owned by [Authentication](../../architecture/system-architecture-authentication.md#implementation-status). -First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. +First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. Current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate the applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; the current bare-world-slug selection re-resolves current authority only when unique in the catalog. Canonical tenant-scoped stable selector resolution remains a separate gap. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, terminal-outcome recovery, and direct text-to-Logging proof remain unproved. Account's bounded readback-only worker for abandoned JOIN `PENDING` intents is implemented, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and complete pending-operation recovery/reconciliation remain open. This is distinct from the browser/WebSocket bootstrap snapshot. @@ -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. -- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. The producer and `PLAY` checks establish a local lifecycle/generation snapshot boundary, not complete event/authority-tuple propagation or reconnect-freshness proof. Account runtime membership, entitlement, and grant handlers deny before data reads until typed caller/target binding is available, and focused direct text-to-Logging end-to-end proof remains open. +- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers deny before data reads, and Game Session maps the membership failure to `WORLD_ACCESS_DENIED`. Focused direct text-to-Logging end-to-end proof remains open. - 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. From ebf8b3c0e9631252d54a71a814fca9ed3c9c6b3c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 07:48:03 +1300 Subject: [PATCH 32/55] Align transport and player status with contained PLAY authority --- .../architecture/system-architecture-protocol-bridging.md | 2 +- design/architecture/system-architecture-reconnection.md | 6 +++--- design/product/user-journeys/players.md | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index ccc36fb015..3eea4fd8e7 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: an eligible public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`. The local Account JOIN route/RPC and Game Session text dispatch now exist, but the full direct-text and first-party path and membership lifecycle/generation reread remain incomplete and unproved. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains `JOIN_REQUIRED`. The separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from the Account endpoint's same-named current error. +The precedence and error rows below are the normative target inventory. In current Game Session `PLAY`, focused unit tests exercise conditional response classification using supplied Account membership and entitlement evidence. The live Account membership, entitlement, and grant RPCs require the trusted Game Session peer but return `FAILED_PRECONDITION` before reading data; Game Session maps the membership failure to `WORLD_ACCESS_DENIED`. Thus those tests do not establish live `JOIN_REQUIRED` or successful composed public `PLAY` through these handlers. The local Account JOIN operation and Game Session text dispatch exist, while direct-text end-to-end proof and membership lifecycle/generation rereads remain incomplete; the public Gateway `/api/account/auth/bootstrap/join` route remains denied. Account connect-token issuance remains a separate Account-owned surface: current public membership/policy and non-public enrollment/access outcomes belong to that endpoint and do not establish text `PLAY` results. In particular, `CONNECT_TOKEN_REJECTED` is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from an Account endpoint error with the same name. Detailed current implementation and proof status remains with [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md). Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index cc6752269a..b9cddacaa4 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -211,14 +211,14 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Text `PLAY` still returns non-actionable `JOIN_REQUIRED` when otherwise eligible public-production membership is missing or non-admitting; local direct-text REALMS-scope/JOIN dispatch and Account RPC exist, but PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. An existing non-admitting response is not classified specifically as `INACTIVE`. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. -- Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. The local browser bootstrap join facade exists, while full first-party browser/mobile flow and proof remain incomplete. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). +- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). `PlayCommandHandler` has focused unit response-classification coverage using supplied Account authority, but live Account membership/entitlement/grant RPCs fail before data access and Game Session maps the membership failure to `WORLD_ACCESS_DENIED`; no live `JOIN_REQUIRED` or successful composed public `PLAY` through these handlers is established. Local direct-text REALMS-scope/JOIN dispatch and the Account RPC exist, but the public Gateway JOIN route remains denied; PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. +- Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. A local browser bootstrap JOIN facade exists, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied; the full first-party browser/mobile flow and proof remain incomplete. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text `PLAY` returns non-actionable `JOIN_REQUIRED` when otherwise eligible public-production membership is missing or non-admitting. The local direct-text dispatch and Account JOIN RPC exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Current `PLAY` response-classification unit tests use supplied Account authority; live Account runtime readers reject before data access and Game Session maps the membership failure to `WORLD_ACCESS_DENIED`, so live `JOIN_REQUIRED` and successful composed public `PLAY` are not established through these handlers. The local direct-text dispatch and Account JOIN RPC exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: diff --git a/design/product/user-journeys/players.md b/design/product/user-journeys/players.md index 9dd5a944ff..b93580f704 100644 --- a/design/product/user-journeys/players.md +++ b/design/product/user-journeys/players.md @@ -41,7 +41,7 @@ These journeys define observable product behavior and user-facing outcomes; tech ## Implementation Status -The target journeys below are primary. Current runtime status is concise: the local Account `JOIN` / `Join & Play` operation and global-only registration seam are implemented, but the complete realm-scoped character gate remains unimplemented and direct text/first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and downstream lifecycle/authority-generation admission proof remain incomplete. Existing credential-bearing clients may still use direct `LOGIN` -> `PLAY` when they already have usable membership and a character. Connect-token issuance and text `PLAY` require existing membership and return `JOIN_REQUIRED` for an eligible missing or non-admitting public-production membership; the current adapter cannot classify the latter specifically as `INACTIVE`. Realm-aware discovery is implemented at the backend boundary, but the richer character-creation descriptor remains a gap. Account export is still Account/profile-only, and the complete cross-service deletion workflow is not yet proved. See the [Account Service export contract](../../architecture/microservices/account-service/api-contracts.md#current-vs-target-export-lifecycle), [ADR 0043](../../architecture/decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md#decision), and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#decision) for those implementation boundaries. +The target journeys below are primary. Current runtime status is concise: the local Account `JOIN` writer and Game Session text dispatch, along with the global-only registration seam, are implemented, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied. The complete realm-scoped character gate remains unimplemented, and direct-text/first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and downstream lifecycle/authority-generation admission proof remain incomplete. `PlayCommandHandler` has focused unit response-classification coverage with supplied membership and entitlement evidence, but live Account runtime membership, entitlement, and grant RPCs return `FAILED_PRECONDITION` before data reads; Game Session maps the membership failure to `WORLD_ACCESS_DENIED`. This does not establish live `JOIN_REQUIRED` or successful composed public `PLAY` through those handlers. Account `/auth/connect-token` retains separate Account-owned public membership/policy and non-public enrollment/access outcomes; they are not text `PLAY` outcomes (see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift)). Realm-aware discovery is implemented at the backend boundary, but the richer character-creation descriptor remains a gap. Account export is still Account/profile-only, and the complete cross-service deletion workflow is not yet proved. See the [Account Service export contract](../../architecture/microservices/account-service/api-contracts.md#current-vs-target-export-lifecycle), [ADR 0043](../../architecture/decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md#decision), and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#decision) for those implementation boundaries. Current gameplay supports room views, movement, foundational inventory/container/equipment commands, and room-local `SAY`, `WHISPER`, and `TELL`. Guild chat and mail remain deferred target behavior and are not current player-runtime capabilities. The shared current communication path includes metadata-only whisper observers and recipient-side delivery for generic WebSocket and Telnet clients; broader audible scopes and first-party/MCP-aware presentation remain gaps. The target player-facing report ingress is not currently available; current support is limited to an internal service-to-service report-persistence seam, not player ingress. From eb017db27c5209e8349ca7146e3342a94650113f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 08:08:27 +1300 Subject: [PATCH 33/55] Deduplicate Logging namespace projection and reject repeated env names --- ...d-identity-controller-manifest-contract.sh | 139 ++++++++++++++++-- k8s/base/logging-admin-service.yaml | 4 - k8s/helm/firemud/templates/apps.yaml | 6 - 3 files changed, 125 insertions(+), 24 deletions(-) diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index f3b80593b7..83fce7cbef 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -4693,11 +4693,39 @@ def env_map(container, service): entries = container.get("env") if not isinstance(entries, list): fail(f"Deployment/{service} container has no env list") - return { - entry.get("name"): entry - for entry in entries - if isinstance(entry, dict) and entry.get("name") - } + result = {} + for entry in entries: + if not isinstance(entry, dict) or not entry.get("name"): + continue + name = entry["name"] + if name in result: + fail(f"Deployment/{service} has duplicate env name {name}") + result[name] = entry + return result + + +synthetic_duplicate_env_rejections = 0 +duplicate_namespace_env = { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, +} +try: + env_map( + {"env": [duplicate_namespace_env, duplicate_namespace_env]}, + "synthetic duplicate fixture", + ) +except SystemExit as error: + if "duplicate env name FIREMUD_GRPC_WORKLOAD_NAMESPACE" not in str(error): + raise + synthetic_duplicate_env_rejections += 1 +else: + fail("synthetic duplicate env fixture was not rejected") +if synthetic_duplicate_env_rejections != 1: + fail( + "synthetic duplicate env proof expected one rejection, found " + f"{synthetic_duplicate_env_rejections}" + ) +print(f"synthetic duplicate env fixtures rejected: {synthetic_duplicate_env_rejections}") def assert_paths_and_mount(container, service, cert_path, key_path, ca_path): @@ -4916,27 +4944,34 @@ if base_logging_admin_grpc_volume.get("secret", {}).get("secretName") != "firemu ) PY -python3 - "$resolved_values" "$namespace_gate_values" <<'PY' +for certificate_identity_mode in standalone hosted-controller; do + for logging_spring_profile in true false; do + python3 - "$resolved_values" "$namespace_gate_values" "$certificate_identity_mode" "$logging_spring_profile" <<'PY' import sys from pathlib import Path import yaml values = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) +certificate_identity_mode = sys.argv[3] +logging_spring_profile = sys.argv[4] == "true" +values["previewStack"]["certificateIdentity"]["mode"] = certificate_identity_mode services = values["previewStack"]["services"] by_name = {service["name"]: service for service in services} +by_name["logging-admin-service"]["springProfile"] = logging_spring_profile +by_name["logging-admin-service"]["mountGrpcTls"] = True by_name["game-design-service"]["springProfile"] = False by_name["game-design-service"]["mountGrpcTls"] = True by_name["world-management-service"]["mountGrpcTls"] = False Path(sys.argv[2]).write_text(yaml.safe_dump(values, sort_keys=False), encoding="utf-8") PY -if ! helm template hosted-identity-namespace-gates "$ROOT_DIR/k8s/helm/firemud" \ - -f "$namespace_gate_values" \ - >"$namespace_gate_rendered"; then - fail "Helm chart render failed for gRPC namespace gate fixture" -fi -python3 - "$namespace_gate_rendered" <<'PY' + if ! helm template "ns-gate-${certificate_identity_mode}-${logging_spring_profile}" "$ROOT_DIR/k8s/helm/firemud" \ + -f "$namespace_gate_values" \ + >"$namespace_gate_rendered"; then + fail "Helm chart render failed for gRPC namespace gate fixture (${certificate_identity_mode}, springProfile=${logging_spring_profile})" + fi + python3 - "$namespace_gate_rendered" "$certificate_identity_mode" "$logging_spring_profile" <<'PY' import sys from pathlib import Path @@ -4952,6 +4987,8 @@ deployments = { for document in yaml.safe_load_all(Path(sys.argv[1]).read_text(encoding="utf-8")) if isinstance(document, dict) and document.get("kind") == "Deployment" } +certificate_identity_mode = sys.argv[2] +logging_spring_profile = sys.argv[3] == "true" def env_map(service): @@ -4962,8 +4999,80 @@ def env_map(service): container = next((item for item in containers if item.get("name") == service), None) if container is None: fail(f"container/{service} is missing") - return {entry.get("name"): entry for entry in container.get("env", []) if entry.get("name")} - + entries = container.get("env") + if not isinstance(entries, list): + fail(f"container/{service} has no env list") + result = {} + for entry in entries: + if not isinstance(entry, dict) or not entry.get("name"): + continue + name = entry["name"] + if name in result: + fail(f"Deployment/{service} has duplicate env name {name}") + result[name] = entry + return result + + +logging_env = env_map("logging-admin-service") +logging_deployment = deployments["logging-admin-service"] +logging_container = next( + item + for item in logging_deployment["spec"]["template"]["spec"]["containers"] + if item.get("name") == "logging-admin-service" +) +namespace_entries = [ + entry + for entry in logging_container["env"] + if isinstance(entry, dict) + and entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" +] +if len(namespace_entries) != 1: + fail( + "logging-admin-service must render exactly one " + "FIREMUD_GRPC_WORKLOAD_NAMESPACE, found " + f"{len(namespace_entries)}" + ) +namespace = logging_env.get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") +if namespace != { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, +}: + fail(f"logging-admin-service must derive namespace from metadata.namespace, found {namespace!r}") +if logging_spring_profile: + if logging_env.get("SPRING_PROFILES_ACTIVE") != { + "name": "SPRING_PROFILES_ACTIVE", + "value": "prod", + }: + fail("springProfile=true logging-admin-service must enable the prod profile") +elif "SPRING_PROFILES_ACTIVE" in logging_env: + fail("springProfile=false logging-admin-service unexpectedly enables the Spring profile") + +expected_paths = { + "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/client.crt", + "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/client.key", + "FIREMUD_GRPC_CA_CERT_PATH": "/tls/ca.crt", +} +for name, value in expected_paths.items(): + if logging_env.get(name, {}).get("value") != value: + fail( + f"{certificate_identity_mode} logging-admin-service must retain shared " + f"{name}={value!r}, found {logging_env.get(name)!r}" + ) +pod_spec = logging_deployment["spec"]["template"]["spec"] +grpc_mounts = [ + mount + for mount in logging_container.get("volumeMounts", []) + if isinstance(mount, dict) and mount.get("name") == "grpc-tls" +] +if len(grpc_mounts) != 1 or grpc_mounts[0].get("mountPath") != "/tls" or grpc_mounts[0].get("readOnly") is not True: + fail(f"{certificate_identity_mode} logging-admin-service must retain its read-only shared /tls mount") +grpc_volumes = [ + volume + for volume in pod_spec.get("volumes", []) + if isinstance(volume, dict) and volume.get("name") == "grpc-tls" +] +if len(grpc_volumes) != 1 or grpc_volumes[0].get("secret", {}).get("secretName") != "firemud-grpc-tls": + fail(f"{certificate_identity_mode} logging-admin-service must retain the shared firemud-grpc-tls Secret") mounted_without_spring = env_map("game-design-service") namespace = mounted_without_spring.get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") @@ -4979,5 +5088,7 @@ without_mount = env_map("world-management-service") if "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in without_mount: fail("publication workload without a gRPC TLS mount unexpectedly declares namespace") PY + done +done echo "hosted identity controller manifest contract passed" diff --git a/k8s/base/logging-admin-service.yaml b/k8s/base/logging-admin-service.yaml index 6d3ff027f3..324c6fb73a 100644 --- a/k8s/base/logging-admin-service.yaml +++ b/k8s/base/logging-admin-service.yaml @@ -34,10 +34,6 @@ spec: value: /tls/client.key - name: FIREMUD_GRPC_CA_CERT_PATH value: /tls/ca.crt - - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace envFrom: - configMapRef: name: firemud-config diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index 85c1d37a10..210a8f9dec 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -182,12 +182,6 @@ spec: {{- if $service.springProfile }} - name: SPRING_PROFILES_ACTIVE value: "prod" - {{- if eq $service.name "logging-admin-service" }} - - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace - {{- end }} {{- end }} - name: SPRING_FLYWAY_TABLE value: {{ printf "flyway_schema_history_%s" (default (replace "-" "_" $service.name) $service.schema) | quote }} From 0f522ccea48cde3d48eae1aebf30dfeae7313257 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:52:07 +1300 Subject: [PATCH 34/55] Continue bounded exact JOIN readback beyond diagnostic threshold --- ...yer-authentication-and-gameplay-binding.md | 2 +- ...025-explicit-open-enrollment-membership.md | 4 +- .../account-service/runtime-and-data.md | 4 +- .../game-session-service/protocols.md | 4 +- ...ystem-architecture-authz-route-matrix.yaml | 2 +- .../system-architecture-reconnection.md | 6 +- .../decision-inventory-cross-cutting.md | 4 +- .../player-access-and-session.md | 2 +- .../AccountJoinOperationRepository.java | 26 ++- .../AccountJoinReconciliationService.java | 52 +++--- ...ReconciliationPostgresIntegrationTest.java | 139 +++++++++++++- .../AccountJoinReconciliationServiceTest.java | 173 +++++++++++++++--- 12 files changed, 339 insertions(+), 79 deletions(-) diff --git a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md index c526ac277b..34aa6cd605 100644 --- a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md +++ b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. The local `POST /auth/bootstrap/join`, `JoinPublicProductionMembership` operation, and Game Session text `JOIN` dispatch now exist. Complete direct-text and first-party runtime/deployment proof remains open, including PostgreSQL execution and pending-operation recovery/reconciliation. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance and text `PLAY` require the four-field Account admission response, never invoke an implicit membership writer, and may return non-actionable `JOIN_REQUIRED` for an eligible fresh authoritative public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`; the obsolete writer seam has been removed. The current response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains unavailable to consumers. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven. The target first-party admission gate therefore remains incomplete until the joining-policy gate, active-state check, generation reread, unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the local JOIN endpoint and operation; its remaining `known_drift` names the unresolved runtime proof and admission snapshot checks. +Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. Public non-browser issuance and dedicated header carriage remain target-only and unavailable. The current browser/mobile response still exposes internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target metadata-only response is implemented; protected secure storage plus the header is target contract only. The local `POST /auth/bootstrap/join`, `JoinPublicProductionMembership` operation, and Game Session text `JOIN` dispatch exist, but the public Gateway join route remains denied. Game Session validates supplied membership lifecycle, authority generation, version, and evaluation time in its local `PLAY` response-classification path. That local path returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so no live `JOIN_REQUIRED` or successful composed public `PLAY` is established; the current live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership classification branches with the same fresh entitlement and policy gates, but its independent membership-version and authority-generation issuance rereads remain unproved and live admission is unavailable. The connect-token replay-cache revalidation gaps also remain; the exact ADR 0030 admission-lease commit, PostgreSQL execution, and pending-operation recovery/reconciliation remain incomplete. First-party browser and text target sequences remain distinct: browser bootstrap/discovery -> conditional explicit join -> character selection/creation -> connect token -> WebSocket `LOGIN` -> `PLAY`; text credential-bearing `LOGIN` -> conditional explicit `JOIN` -> character selection/creation -> `PLAY`. Grant-backed private/playtest admission requires existing `ACTIVE` membership plus the current grant, skips `JOIN`, and never creates membership. See [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status), [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention), and the route matrix for canonical authority and proof limits. The current `GameplayHandshakeFilter` accepts one cookie or header, rejects simultaneous carriers, and consumes an untagged replay marker through the generic Cache-bound client, but does not implement ADR 0029's tagged Coordination Redis readiness/fence and quarantine contract. Target player-facing admission remains quarantined until that cutover and proof complete. That current parser support does not establish public non-browser issuance or an accepted target non-first-party route/carrier. diff --git a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md index 3acf67a60e..46d1f1a629 100644 --- a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md +++ b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The accepted explicit-join decision remains the target contract, with a local Account implementation now present. Global-only registration creates global account state and a platform-scoped audit outbox record without membership or profile authority; `JoinPublicProductionMembership` is the sole local public-production membership writer, with a policy-independent durable intent followed by a policy-bound digest, membership transition, operation outcome, and tenant-scoped audit/outbox evidence committed by the Account transaction. Current first-party connect-token issuance and text `PLAY` require existing membership and do not invoke an implicit membership writer; fresh authoritative missing or non-admitting public-production membership fails closed with `JOIN_REQUIRED` where the current adapter can establish that predicate. The obsolete differently named writer RPC and service implementation remain removed rather than retained as compatibility behavior. This local seam has focused unit and repository proof, and a bounded Account-owned worker now revisits `PENDING` intents for exact positive operation and membership/audit readback. PostgreSQL execution is unavailable locally, unknown-commit-outcome reconciliation proof and direct text-to-Logging end-to-end proof remain open, and the complete lifecycle snapshot plus independent `membershipVersion` and `membershipAuthorityGeneration` reread at every connect-token issuance remain incomplete. ADR 0025 therefore does not claim complete runtime or production proof. +The accepted explicit-join decision remains the target contract, with a local Account implementation now present. Global-only registration creates global account state and a platform-scoped audit outbox record without membership or profile authority; `JoinPublicProductionMembership` is the sole local public-production membership writer, with a policy-independent durable intent followed by a policy-bound digest, membership transition, operation outcome, and tenant-scoped audit/outbox evidence committed by the Account transaction. The obsolete differently named writer RPC and service implementation remain removed. Game Session locally validates supplied lifecycle, authority-generation, membership-version, and evaluation-time fields; its response-classification branch returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so this local classification does not establish live `JOIN_REQUIRED` or successful composed public `PLAY`; the live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same fresh policy gates, but live membership reads and its independent membership-version/authority-generation issuance rereads remain unavailable or unproved. A bounded Account-owned worker revisits `PENDING` intents for exact positive operation and membership/audit readback. PostgreSQL execution is unavailable locally, unknown-commit-outcome reconciliation and direct text-to-Logging end-to-end proof remain open. ADR 0025 does not claim complete runtime or production proof; see [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for owning detail. ## Decision Record @@ -24,7 +24,7 @@ The accepted explicit-join decision remains the target contract, with a local Ac A tenant may deliberately expose one default production realm for public discovery. Joining that game should create a durable Account-owned player membership: the relationship powers the player's game library, later discovery, return-to-game flows, creator membership views, moderation, and account/tenant data handling. -The earlier admission flow created membership implicitly during first-party connect-token issuance or text-client `PLAY` through an obsolete membership writer. Current admission callers have been corrected to require existing membership and return `JOIN_REQUIRED`, and that writer RPC/service seam has been removed without introducing a compatibility path. The accepted explicit-join boundary, policy-bound Account transaction, local durable audit/outbox seam, and bounded `PENDING`-intent readback worker now exist; PostgreSQL execution, unknown-commit-outcome reconciliation proof, downstream snapshot-generation, and end-to-end transport proof remain incomplete. +The earlier admission flow created membership implicitly during first-party connect-token issuance or text-client `PLAY` through an obsolete membership writer. That writer RPC/service seam has been removed without introducing a compatibility path. Local admission response classification uses supplied Account authority and preserves the target distinction between missing/`INACTIVE` eligible public membership, `ACTIVE` but non-admitting membership, and non-public denial; live Account runtime readers still fail before data access and no successful composed public `PLAY` is established. The accepted explicit-join boundary, policy-bound Account transaction, local durable audit/outbox seam, and bounded `PENDING`-intent readback worker now exist; PostgreSQL execution, unknown-commit-outcome reconciliation proof, downstream snapshot-generation, and end-to-end transport proof remain incomplete. ## Decision diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 33bcefbf84..6c56780296 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. Six focused unit cases in `ExpiredCredentialCleanupJobTest` executed locally; seven PostgreSQL integration cases in `CredentialCleanupRepositoryIntegrationTest` passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. -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 currently records retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the bounded worker can terminalize only exact positive prior-commit evidence. A malformed or missing bearer is rejected without inventing a terminal operation result. An exact caller retry cannot rerun JOIN with the expired scope, and automatic readback attempts reaching their cap leave the intent `PENDING` rather than inventing a terminal failure. 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 currently records retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the bounded worker can terminalize only exact positive prior-commit evidence. A malformed or missing bearer is rejected without inventing a terminal operation result. An exact caller retry cannot rerun JOIN with the expired scope. 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 diagnostics with a reason and backoff when evidence is incomplete. It terminalizes only a positively proved prior transition; unresolved rows remain visible and caller-retryable, and due readbacks continue after the configured diagnostic threshold. 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. 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 runtime membership proto/response shape carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The live gRPC membership, realm-grant, and entitlement handlers require the trusted Game Session peer and then return `FAILED_PRECONDITION` before reading Account data because the current requests cannot prove caller/target binding. Response-classification branches exercised with supplied authority in local unit tests therefore do not establish a live admission snapshot; the complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` also remain absent. 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. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks caller-bound membership existence and admission after fresh entitlement and target checks. For Account connect-token issuance and character discovery, only missing membership on an eligible public-production target may return `JOIN_REQUIRED`; a present non-admitting membership is denied without `JOIN_REQUIRED`, and the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Game Session `PLAY` contains conditional response-classification logic for missing or `INACTIVE` public-production membership, but the live Account handlers return `FAILED_PRECONDITION`, which Game Session maps to `WORLD_ACCESS_DENIED`; no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. These paths do not create or restore membership. 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 runtime membership proto/response shape carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The live gRPC membership, realm-grant, and entitlement handlers require the trusted Game Session peer and then return `FAILED_PRECONDITION` before reading Account data because the current requests cannot prove caller/target binding. Response-classification branches exercised with supplied authority in local unit tests therefore do not establish a live admission snapshot; the complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` also remain absent. 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. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks caller-bound membership existence and admission after fresh entitlement and target checks. For Account connect-token issuance and character discovery, only missing membership on an eligible public-production target may return `JOIN_REQUIRED`; a present non-admitting membership is denied without `JOIN_REQUIRED`, and the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Game Session `PLAY` contains conditional response-classification logic for missing or `INACTIVE` public-production membership, but the live Account handlers return `FAILED_PRECONDITION`, which Game Session maps to `WORLD_ACCESS_DENIED`; no successful composed public `PLAY` or live `JOIN_REQUIRED` through these handlers is established. These paths do not create or restore membership. 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 revisits `PENDING` JOIN operations without a caller; it terminalizes only exact positive operation/membership/audit proof, continues due reads after its configured diagnostic threshold, and keeps absent or uncertain evidence pending with backoff. 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/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 1cb516da42..a317083e9a 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -114,7 +114,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration` alongside the four admission fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`), but the current Game Session consumer does not enforce lifecycle or generation and therefore cannot classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; the latter cannot currently be classified specifically as `INACTIVE` because lifecycle state is not consumed by the admission path. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Game Session validates supplied `membershipLifecycleState`, `membershipAuthorityGeneration`, `membershipVersion`, and `evaluatedAt` in its local `PLAY` response-classification path. That path classifies missing or `INACTIVE` public-production membership as `JOIN_REQUIRED` only after fresh positive entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership is denied without JOIN advice. These supplied-response branches do not establish a successful live read or composed admission: Account membership, entitlement, and grant handlers currently return `FAILED_PRECONDITION` before data access until typed caller/target binding exists, and the resulting live membership failure maps to `WORLD_ACCESS_DENIED`. No successful public `PLAY` is established. Current text `PLAY` checks the applicable private/playtest grant when authority is supplied; current connect-token grant validation remains a gap. Connect-token issuance has separate local missing/`INACTIVE` public-membership classification branches that require fresh positive entitlement and `allowPublicJoin`; its independent membership-version and authority-generation issuance rereads remain unproved. See [Authentication Implementation Status](../../system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the owning authority and proof limits. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. @@ -164,7 +164,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – bootstrap-backed `LOGIN` resolved to an account different from the validated connect-context subject. -- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. The local Account route/RPC and Game Session text dispatch now exist, but the current result remains fail-closed and non-actionable to consumers until lifecycle-aware admission and end-to-end/runtime proof are complete. Account now emits lifecycle state and authority generation, but the existing non-admitting case cannot be classified as `INACTIVE` because those fields are not yet consumed by the admission path. +- `JOIN_REQUIRED` – local `PLAY` response classification is limited to a selected public-production target whose membership is confirmed missing or `INACTIVE` after fresh positive entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account and Game Session explicit JOIN seams exist, but Account runtime readers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so this local classification does not establish a live `JOIN_REQUIRED` response or successful public `PLAY`. The current live membership failure maps to `WORLD_ACCESS_DENIED`. See [Authentication Implementation Status](../../system-architecture-authentication.md#implementation-status) for the canonical status and remaining proof limits. - `WORLD_ACCESS_DENIED` – current runtime behavior for a private, playtest, or other non-public target whose Account-exposed membership/admission predicate or existing grant check denies access; no public join action is offered. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 43154b2134..85d1e2c9d7 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -393,7 +393,7 @@ required_live_check_vocabulary: - security_lock_export_action_family implementation_status: known_drift: - - direct_text_explicit_public_production_JOIN_is_implemented_locally; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_response_exposes_membershipLifecycleState_and_membershipAuthorityGeneration_and_current_PLAY_consumer_validates_membershipLifecycleState_membershipAuthorityGeneration_membershipVersion_and_evaluatedAt; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_INACTIVE_public_production_membership_only_after_fresh_entitlement_and_allowPublicJoin_checks; ACTIVE_non_admitting_membership_is_denied_without_JOIN_advice; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented; PostgreSQL_execution_and_bounded_pending_operation_readback_proof_remain_incomplete + - direct_text_explicit_public_production_JOIN_is_implemented_locally; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_entitlement_and_grant_handlers_fail_closed_with_FAILED_PRECONDITION_before_reads_until_typed_caller_target_binding_exists; Game_Session_PLAY_validates_supplied_membershipLifecycleState_membershipAuthorityGeneration_membershipVersion_and_evaluatedAt_and_classifies_missing_or_INACTIVE_eligible_public_membership_as_JOIN_REQUIRED_and_ACTIVE_non_admitting_membership_as_denied_without_JOIN_advice; live_composed_membership_reads_and_successful_public_PLAY_are_not_established; live_membership_failure_maps_to_WORLD_ACCESS_DENIED; connect_token_local_missing_or_INACTIVE_public_membership_branches_require_fresh_positive_entitlement_and_allowPublicJoin_while_live_reads_remain_unavailable; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_and_membership_version_issuance_rereads_remain_unproved; PostgreSQL_execution_and_bounded_pending_operation_readback_proof_remain_incomplete - protected_cookie_ws_game_and_bootstrap_bare_LOGIN_are_implemented_but_non_promotable_until_Gateway_carrier_requirements_replay_marker_durability_replay_quarantine_continuity_and_Account_planned_rotation_compromise_cutover_evidence_are_complete - privileged_control_is_target_only_and_unavailable_in_current_runtime; platformAdmin_and_cross_tenant_billingAdmin_branches_requiring_it_fail_closed_while_the_support_branch_does_not_require_it - operator_mutation_rows_are_normative_target_contracts_not_current_availability; action_schema_mutationDigest_v1_vectors_and_account_issued_authorization_reference_flow_are_required_before_external_support diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index b9cddacaa4..298c5e5cee 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,7 +10,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current first-party connect-token issuance and text `PLAY` use the fresh current Account fields `membershipExists` and `gameplayAdmissionAllowed` and admit only when both are true; an otherwise eligible public-production request with `membershipExists=false` fails closed with non-actionable `JOIN_REQUIRED`, while an existing response with `gameplayAdmissionAllowed=false` remains the established denial. The current response has no lifecycle state, so current admission is not classified as `ACTIVE` or `INACTIVE`; this boolean predicate is not proof of the target `ACTIVE` lifecycle requirement. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch exist locally; PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and the required connect-token membership-authority/version rereads remain unproved. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Game Session locally validates lifecycle, authority-generation, membership-version, and evaluation-time fields when supplied by its `PLAY` authority response. Its local response-classification branches permit `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks; `ACTIVE` but non-admitting membership is denied without JOIN advice, and non-public denial does not offer public JOIN. These branches do not establish live composed admission: Account membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before reads until typed caller/target binding exists, and the resulting live membership failure maps to `WORLD_ACCESS_DENIED`. No successful public `PLAY` or first-party browser `JOIN` is established. Account's explicit JOIN operation and direct-text scope/dispatch seams exist locally, while the public Gateway join route remains denied. PostgreSQL execution, direct text-to-Logging proof, unknown-outcome recovery, and the independent connect-token membership-version/authority-generation issuance reread remain open; connect-token issuance retains its separate local response classification and grant-validation gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; the target authority and error detail remain in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). - **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -78,7 +78,7 @@ A retained-edge upstream rebind, including a qualifying hidden Game Session rest Reconnection uses two distinct client flows: -- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its `JOIN` procedure; local direct-text REALMS-scope/JOIN dispatch and the Account JOIN RPC exist, while PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and lifecycle/generation rereads remain unproved. Ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Current text `PLAY` still returns non-actionable `JOIN_REQUIRED` when eligible public membership is missing or non-admitting; completion of the local JOIN path does not establish the whole flow. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. +- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its `JOIN` procedure; local direct-text REALMS-scope/JOIN dispatch and the Account JOIN RPC exist, while PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and lifecycle/generation rereads remain unproved. Ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session's local `PLAY` response classification uses supplied authority and returns `JOIN_REQUIRED` only when eligible public-production membership is missing or `INACTIVE`; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, and the resulting live membership failure maps to `WORLD_ACCESS_DENIED`; local classification does not establish live `JOIN_REQUIRED` or successful public `PLAY`. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. - **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the browser bootstrap join facade exists locally, but the complete frontend/runtime flow and proof remain incomplete. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. @@ -218,7 +218,7 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Current `PLAY` response-classification unit tests use supplied Account authority; live Account runtime readers reject before data access and Game Session maps the membership failure to `WORLD_ACCESS_DENIED`, so live `JOIN_REQUIRED` and successful composed public `PLAY` are not established through these handlers. The local direct-text dispatch and Account JOIN RPC exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Current `PLAY` response-classification proof uses supplied Account authority and confirms lifecycle/generation/version/evaluation-time validation plus the local `JOIN_REQUIRED` classification for missing or `INACTIVE` eligible public membership. Live Account runtime readers still reject with `FAILED_PRECONDITION` before data access, and Game Session maps that live membership failure to `WORLD_ACCESS_DENIED`; live `JOIN_REQUIRED` and successful composed public `PLAY` are not established through these handlers. The local direct-text dispatch and Account JOIN operation exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: diff --git a/design/project-management/design-alignment/decision-inventory-cross-cutting.md b/design/project-management/design-alignment/decision-inventory-cross-cutting.md index 8a01c45a99..dfaed2d834 100644 --- a/design/project-management/design-alignment/decision-inventory-cross-cutting.md +++ b/design/project-management/design-alignment/decision-inventory-cross-cutting.md @@ -94,11 +94,11 @@ The first 22 source-index entries are the counted cross-cutting partition. `WE`, | Key | Primary capability | Secondary capabilities | Question -> current choice | Status | I/R | Sources / explicit ADR | Strongest alternative | ADR recommendation | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `AUTH-01` | `AA-3.1` | `AA-2.1`, `AA-3.3`, `SF-1.2` | What identifies gameplay selection/admission and controller ownership? Stable `worldSlug`/`realmSlug` and snapshot-bound ordinals are lobby selectors. Selection/admission resolves the authoritative gameplay binding `{tenantId, realmId, gameInstanceId, characterId}` plus the applicable pointer/fence, `playableStateNamespaceId`, and server-derived scope evidence; `gameInstanceId` remains the active-runtime fence/value, and slugs and ordinals never grant authority. Separately, the single-controller uniqueness key is exactly `{tenantId, playableStateNamespaceId, characterId}`; `gameInstanceId` is not part of controller uniqueness. | `accepted-explicit` | H/hard | `AU § Contract Decisions (Normative)`; `MT § Identity & Tenant Model`; [ADR 0168](../../architecture/decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [Session Behavior](../../architecture/system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) | Opaque handles for every selection, durable slug authority, fresh-catalog ordinal reuse, or per-instance controller identity. | Human review revised and superseded ADR 0005 on 2026-07-21. ADRs 0122 and 0132 continue to own stable playable-state namespaces and namespace-scoped controller transfer. | -| `AUTH-02` | `AA-2.1` | `PO-2.2`, `PO-2.1`, `SF-1.3`, `EA-3.1` | What is the player authentication sequence? Public `WORLDS` remains a browse-only pre-authentication mode. The target authenticated WebSocket flow is player bootstrap -> membership-aware discovery -> conditional explicit `JOIN` for first public-production entry -> character selection or creation -> single-use connect token -> WebSocket -> bare `LOGIN` -> `PLAY`. Browsers carry the token in the protected cookie; explicitly classified non-browser WebSocket clients use the dedicated handshake header. Returning members skip the public-production `JOIN` step only after the target current `ACTIVE` membership and exact reread evidence pass. Grant-backed admission requires existing durable `membershipLifecycleState=ACTIVE` membership and separately validates the applicable realm grant; a grant never creates or substitutes for membership. A nonmember must use the Account-owned membership lifecycle, such as explicit `JOIN`/`Join & Play` for eligible public production, before admission. Telnet and other non-WebSocket text clients retain credential-bearing protocol `LOGIN`. Ordinary gameplay supports `PASSWORD` or verified-email `EMAIL_OTP` without mandatory TOTP. **Current state:** the dedicated non-browser WebSocket handshake header is target-only and unavailable; unsupported header use is rejected as `CONNECT_TOKEN_REJECTED` without cookie fallback or carrier inference. Both text `PLAY` and `POST /auth/connect-token` admit only when `membershipExists && gameplayAdmissionAllowed`; neither response classifies `ACTIVE` versus `INACTIVE`. Text `PLAY` returns `JOIN_REQUIRED` for a public-production target when either boolean is false and `WORLD_ACCESS_DENIED` for a non-public target; direct-text REALMS-scope/JOIN dispatch now exists locally. Connect-token issuance returns `JOIN_REQUIRED` for a non-admitting public-production target when `allowPublicJoin=true`, `PUBLIC_PRODUCTION_ADMISSION_DENIED` when public joining is disabled, `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership, and `CONNECT_TOKEN_REJECTED` for existing but non-admitting non-public membership. The Account explicit `JOIN` path, including browser `POST /auth/bootstrap/join`, also exists locally. Full workflow/deployment/PostgreSQL/direct text-to-Logging proof, pending unknown-outcome reconciliation, and membership lifecycle/generation rereads remain open. | `accepted-explicit` | H/hard | [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0029](../../architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md); `AU § Login and Session Flow`; `GW § Tenant-Aware Edge Connect Token (Gameplay Handshake)`; `RC § When Reauthentication Is Required` | Complete WebSocket login at the handshake, replay credentials in WebSocket `LOGIN`, or require TOTP/WebAuthn for every gameplay connection. | Revised and accepted by human decision; ADR 0021 records the sequence and factors, while ADR 0029 subsequently standardizes connect-token carriage for every public non-proxy WebSocket. | +| `AUTH-02` | `AA-2.1` | `PO-2.2`, `PO-2.1`, `SF-1.3`, `EA-3.1` | What is the player authentication sequence? Public `WORLDS` remains a browse-only pre-authentication mode. The target authenticated WebSocket flow is player bootstrap -> membership-aware discovery -> conditional explicit `JOIN` for first public-production entry -> character selection or creation -> single-use connect token -> WebSocket -> bare `LOGIN` -> `PLAY`. Browsers carry the token in the protected cookie; explicitly classified non-browser WebSocket clients use the dedicated handshake header. Returning members skip the public-production `JOIN` step only after the target current `ACTIVE` membership and exact reread evidence pass. Grant-backed admission requires existing durable `membershipLifecycleState=ACTIVE` membership and separately validates the applicable realm grant; a grant never creates or substitutes for membership. A nonmember must use the Account-owned membership lifecycle, such as explicit `JOIN`/`Join & Play` for eligible public production, before admission. Telnet and other non-WebSocket text clients retain credential-bearing protocol `LOGIN`. Ordinary gameplay supports `PASSWORD` or verified-email `EMAIL_OTP` without mandatory TOTP. **Current state:** the dedicated non-browser WebSocket handshake header is target-only and unavailable; unsupported header use is rejected as `CONNECT_TOKEN_REJECTED` without cookie fallback or carrier inference. Game Session validates lifecycle, authority-generation, membership-version, and evaluation-time fields in local `PLAY` response classification. Supplied-authority local classification returns `JOIN_REQUIRED` only for missing or `INACTIVE` eligible public-production membership after fresh positive entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so no live `JOIN_REQUIRED` or successful public `PLAY` is established; the resulting live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same policy gates, while its membership-version/authority-generation issuance rereads remain unproved. Account `JOIN` and direct-text dispatch/scope seams exist locally, but the public Gateway JOIN route remains denied. PostgreSQL, pending-outcome recovery, and direct text-to-Logging proof remain open. | `accepted-explicit` | H/hard | [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0029](../../architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md); `AU § Login and Session Flow`; `GW § Tenant-Aware Edge Connect Token (Gameplay Handshake)`; `RC § When Reauthentication Is Required` | Complete WebSocket login at the handshake, replay credentials in WebSocket `LOGIN`, or require TOTP/WebAuthn for every gameplay connection. | Revised and accepted by human decision; ADR 0021 records the sequence and factors, while ADR 0029 subsequently standardizes connect-token carriage for every public non-proxy WebSocket. | | `AUTH-03` | `AA-1.3` | `AA-1.2`, `AA-1.5`, `AA-2.3`, `SF-1.3`, `SF-2.2` | Who owns identity, revocation, entitlements, and gameplay bindings? Account owns durable account, token, revocation, membership, entitlement, and the single issued-token registry authority; JWT-presenting registry-backed control-plane, bootstrap, and admission operations perform exactly one registry lookup, while Game Session owns gameplay bindings and derives typed execution context and Gateway has only bounded edge checks. The dedicated `gameplay-connect` artifact remains outside the issued-token registry and uses its own single-use replay fence. | `accepted-explicit` | H/hard | [ADR 0022](../../architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); `AU § Responsibility Split`; `OV § Authentication Modes and Boundaries`; `RM § Notes on Movement and Moderation Contracts` | Introduce a dedicated IAM service, make Gateway the general identity authority, or use TTL-only tokens. | Affirmed by human decision; ADR 0022 records one writer per authority and separates accepted design from revocation/session implementation gaps. | | `AUTH-04` | `SF-1.3` | `AA-1.2`, `PO-1.1`, `PO-2.1`, `PO-4.4` | How are protected routes authorized? One machine-readable route policy governs strict token profiles, explicit tenant/cross-tenant scopes, generated completeness checks, and runtime denial of unclassified routes; services retain domain checks. | `accepted-explicit` | H/hard | [ADR 0023](../../architecture/decisions/adr-0023-central-route-authorization-governance.md); `AU § Auth Middleware Algorithm (Normative)`; `AU § Global Role to Route-Class Matrix (Normative)`; `OV § Admin Entry Points and Traffic Surfaces` | Service-local role checks, Gateway-only authorization, or a general-purpose external policy engine. | Revised and accepted by human decision; policy/proof upkeep is an accepted security tradeoff and current enforcement gaps are explicit. | | `AUTH-05` | `SF-1.3` | `SF-1.2`, `SF-1.1`, `GR-1.1`, `PO-3.2` | How is internal player delegation trusted? Concrete mTLS workload identity and exact method caller allowlists authorize the trusted gameplay service; unsigned typed `PlayerExecutionContext` carries validated scope, while mutations retain operation-specific idempotency. | `accepted-explicit` | H/hard | [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md); `AU § Gameplay Player Execution Context Contract (Normative)`; `SE § Gameplay Workload Trust`; `GR § TLS Requirements` | Per-RPC signed/replay-guarded attestations, signed attestations without replay storage, or generic backend JWTs carrying player identity. | Revised and accepted by human decision after two-sided adversarial review; the current first-party trust domain explicitly accepts allowlisted-intermediary impersonation risk to avoid universal hot-path attestation cost. | -| `AUTH-06` | `AA-1.2` | `AA-1.1`, `AA-3.2`, `AA-2.1`, `EA-3.1` | What does first public-production join mean? **Target:** one explicit `JOIN`/`Join & Play` action creates the durable Account-owned player membership used for the player's game library and future return; token issuance and `PLAY` never create it implicitly. **Current state:** both text `PLAY` and `POST /auth/connect-token` admit only when `membershipExists && gameplayAdmissionAllowed`; neither response classifies `ACTIVE` versus `INACTIVE`. Text `PLAY` returns `JOIN_REQUIRED` for a public-production target when either boolean is false and `WORLD_ACCESS_DENIED` for a non-public target; direct-text REALMS-scope/JOIN dispatch now exists locally. Connect-token issuance returns `JOIN_REQUIRED` for a non-admitting public-production target when `allowPublicJoin=true`, `PUBLIC_PRODUCTION_ADMISSION_DENIED` when public joining is disabled, `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership, and `CONNECT_TOKEN_REJECTED` for existing but non-admitting non-public membership. The obsolete implicit membership-writer seam has been removed, and the Account explicit `JOIN` path, including browser `POST /auth/bootstrap/join`, exists locally. Full workflow/deployment/PostgreSQL/direct text-to-Logging proof, pending unknown-outcome reconciliation, and membership lifecycle/generation rereads remain open. For private/playtest targets, target text behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED` and requires existing `ACTIVE` membership plus the applicable grant. | `accepted-explicit` | H/hard | [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); `AU § Login and Session Flow`; `MT § Account-to-Game Relationships` | Implicit membership during connect/`PLAY`, invitation/approval, or ephemeral visitors. | Revised and accepted by human decision; durable membership is a product feature, with explicit intent, transactional audit/outbox, leave lifecycle, and abuse controls. | +| `AUTH-06` | `AA-1.2` | `AA-1.1`, `AA-3.2`, `AA-2.1`, `EA-3.1` | What does first public-production join mean? **Target:** one explicit `JOIN`/`Join & Play` action creates the durable Account-owned player membership used for the player's game library and future return; token issuance and `PLAY` never create it implicitly. **Current state:** Game Session's local supplied-authority `PLAY` classification validates lifecycle, authority-generation, membership-version, and evaluation time; it returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks, and denies an `ACTIVE` but non-admitting membership without JOIN advice. Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so no live `JOIN_REQUIRED` or successful public `PLAY` is established; live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same fresh policy gates, but its independent membership-version and authority-generation issuance rereads remain unproved. The obsolete implicit membership-writer seam has been removed; Account's explicit `JOIN` operation and direct-text dispatch/scope seams exist locally, while the public Gateway JOIN route remains denied. Full PostgreSQL, pending-outcome recovery, and direct text-to-Logging proof remain open. For private/playtest targets, the target contract requires existing `ACTIVE` membership plus the applicable grant and never offers public `JOIN`; see the linked ADR and Authentication status for detail. | `accepted-explicit` | H/hard | [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); `AU § Login and Session Flow`; `MT § Account-to-Game Relationships` | Implicit membership during connect/`PLAY`, invitation/approval, or ephemeral visitors. | Revised and accepted by human decision; durable membership is a product feature, with explicit intent, transactional audit/outbox, leave lifecycle, and abuse controls. | | `AUTH-07` | `AA-1.2` | `AA-2.1`, `PO-1.1`, `PO-1.2`, `EA-3.3` | Can global roles grant gameplay authority? No: global roles cannot admit or elevate gameplay, staff join as ordinary players unless given explicit tenant-scoped gameplay capabilities, and the target has no impersonation or hidden observation. | `accepted-explicit` | H/hard | [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); `AU § Role Model`; `AU § Global Role to Route-Class Matrix (Normative)`; `OV § Moderation, Restriction, and Appeal Authority (Canonical)` | Global-role gameplay bypass, audited time-bounded impersonation, or read-only live observation. | Revised and accepted by human decision; current global `platformAdmin` to in-game `ADMIN` classification is implementation drift, while support remains on purpose-built control-plane and diagnostic surfaces. | | `TENANT-01` | `AA-3.3` | `AA-3.1`, `AA-3.2`, `AR-3.2`, `GR-2.1`, `GR-1.1` | How is a realm admitted? A Game Session-owned route is `OPEN` on exactly one instance or explicitly `CLOSED`; atomic pointer versions govern new/renewed bindings, while active source sessions end through bounded drain rather than per-action revalidation. | `accepted-explicit` | H/hard | [ADR 0027](../../architecture/decisions/adr-0027-single-realm-admission-target.md); `MT § Realm Catalog and Admission-Pointer Contract`; `VR § Realm Routing Contract For Player-Addressable Realms`; `OV § Design-Time vs Runtime World Data` | An instance-placement pool behind one realm, mutable latest-version lookup, or client-selected instance. | Revised and accepted by human decision; one shared world scales inside one instance, while explicit realms represent separate worlds and implementation must converge on tenant-qualified atomic CAS and cutover bookkeeping. | | `TENANT-02` | `AA-1.5` | `PO-3.1`, `PO-3.2`, `SF-2.2`, `GR-1.3` | Shared services, PostgreSQL, Coordination Redis, Cache/Rate-Limit Redis, and cluster capacity are the only supported normal multi-tenant topology; logical tenant scoping, authorization, quotas, and service ownership provide isolation. The environment-wide incident and recovery blast radius is accepted. A demonstrated future hard-isolation requirement uses a separately reviewed complete environment, not a hybrid selectively dedicated tenant data plane. | `accepted-explicit` | H/med | [ADR 0041](../../architecture/decisions/adr-0041-shared-tenant-infrastructure-with-full-environment-isolation-gate.md); `MT § Data Separation per Service`; `MT § Tenant Configuration & Scaling`; `OV § Multi-Tenancy Enforcement` | Dedicated tenant clusters, databases, Redis partitions, or a hybrid shared/dedicated routing tier. | Human review completed 2026-07-19; `revised`. | 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 95af0dfc6a..96e7144e3d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents; its configured attempt count is a diagnostic threshold, and due exact-evidence readbacks continue with backoff after that threshold. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. 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. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index c8eb47ab96..b5daad6efb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -53,23 +53,19 @@ public Optional findForUpdate(String requestId) { .fetchOptional(AccountJoinOperationRepository::toJoinOperation); } - /** Returns a stable, bounded page of due PENDING operations below the caller's attempt cap. */ - public List findDuePendingReconciliation(Instant now, int limit, int maxAttempts) { + /** Returns a stable, bounded page of all due PENDING operations. */ + public List findDuePendingReconciliation(Instant now, int limit) { if (now == null) { throw new IllegalArgumentException("JOIN reconciliation time is required"); } if (limit < 1 || limit > MAX_RECONCILIATION_PAGE_SIZE) { throw new IllegalArgumentException("JOIN reconciliation page size must be between 1 and 100"); } - if (maxAttempts < 1) { - throw new IllegalArgumentException("JOIN reconciliation attempt limit must be positive"); - } return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) .where( ACCOUNT_JOIN_OPERATIONS .STATUS .eq("PENDING") - .and(ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.lt(maxAttempts)) .and( ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.le( toLocalDateTime(now)))) @@ -83,19 +79,21 @@ public List findDuePendingReconciliation(Instant now, int limit, /** * Records one reconciliation attempt only if the pending row still has the observed attempt count - * and remains below the caller's cap. A false result means another worker changed it. + * and due time. The count saturates at the configured diagnostic threshold. A false result means + * another worker changed or rescheduled the row. */ public boolean recordReconciliationAttempt( String requestId, int expectedAttemptCount, int maxAttempts, + Instant expectedNextAttemptAt, Instant attemptedAt, String reason, Instant nextAttemptAt) { if (requestId == null || requestId.isBlank()) { throw new IllegalArgumentException("JOIN request ID is required"); } - if (expectedAttemptCount < 0 || maxAttempts < 1 || expectedAttemptCount >= maxAttempts) { + if (expectedAttemptCount < 0 || maxAttempts < 1 || expectedNextAttemptAt == null) { throw new IllegalArgumentException("JOIN reconciliation attempt count is outside its limit"); } if (attemptedAt == null || nextAttemptAt == null || nextAttemptAt.isBefore(attemptedAt)) { @@ -109,7 +107,13 @@ public boolean recordReconciliationAttempt( dsl.update(ACCOUNT_JOIN_OPERATIONS) .set( ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT, - ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.plus(1)) + org.jooq + .impl + .DSL + .when( + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.lt(maxAttempts), + ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.plus(1)) + .otherwise(ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT)) .set( ACCOUNT_JOIN_OPERATIONS.LAST_RECONCILIATION_ATTEMPT_AT, toLocalDateTime(attemptedAt)) @@ -126,7 +130,9 @@ public boolean recordReconciliationAttempt( .and( ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.eq( expectedAttemptCount)) - .and(ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.lt(maxAttempts))) + .and( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.eq( + toLocalDateTime(expectedNextAttemptAt)))) .execute(); return updated == 1; } 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..d689a03d60 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 @@ -103,8 +103,7 @@ public void reconcileDueOperations(Instant now) { Objects.requireNonNull(now, "JOIN reconciliation time is required"); final List dueOperations; try { - dueOperations = - joinOperationRepository.findDuePendingReconciliation(now, batchSize, maxAttempts); + dueOperations = joinOperationRepository.findDuePendingReconciliation(now, batchSize); } catch (RuntimeException ex) { failures.increment(); logger.warn( @@ -143,7 +142,13 @@ private void reconcileOne(JoinOperation candidate, Instant now) { "JOIN reconciliation readback failed for request {} ({})", candidate.requestId(), ex.getClass().getSimpleName()); - recordUnavailableAttempt(candidate, now); + ReconciliationResult fallbackResult = recordUnavailableAttempt(candidate, now); + if (fallbackResult == ReconciliationResult.ATTEMPT_RECORDED) { + unresolved.increment(); + } else if (fallbackResult == ReconciliationResult.MAX_ATTEMPTS_REACHED) { + unresolved.increment(); + maxAttemptsReached.increment(); + } } } @@ -155,7 +160,6 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no if (operation == null || operation.accountId() != candidate.accountId() || !"PENDING".equals(operation.status()) - || operation.reconciliationAttemptCount() >= maxAttempts || operation.nextReconciliationAttemptAt() == null || operation.nextReconciliationAttemptAt().isAfter(now)) { return ReconciliationResult.SKIPPED; @@ -372,15 +376,17 @@ private ReconciliationResult recordUnresolvedAttempt( operation.requestId(), operation.reconciliationAttemptCount(), maxAttempts, + operation.nextReconciliationAttemptAt(), now, reason, nextAttemptAt(now)); if (!recorded) { return ReconciliationResult.SKIPPED; } - if (operation.reconciliationAttemptCount() + 1 >= maxAttempts) { + if (operation.reconciliationAttemptCount() < maxAttempts + && operation.reconciliationAttemptCount() + 1 >= maxAttempts) { logger.warn( - "JOIN reconciliation reached its attempt limit for request {}; it remains PENDING and caller-retryable (reason {})", + "JOIN reconciliation reached its diagnostic attempt threshold for request {}; exact readback will continue with backoff while it remains PENDING (reason {})", operation.requestId(), reason); return ReconciliationResult.MAX_ATTEMPTS_REACHED; @@ -392,28 +398,30 @@ private ReconciliationResult recordUnresolvedAttempt( return ReconciliationResult.ATTEMPT_RECORDED; } - private void recordUnavailableAttempt(JoinOperation candidate, Instant now) { + private ReconciliationResult recordUnavailableAttempt(JoinOperation candidate, Instant now) { try { - joinTransactionTemplate.execute( - transactionStatus -> { - joinOperationRepository.lockAccount(candidate.accountId()); - JoinOperation operation = - joinOperationRepository.findForUpdate(candidate.requestId()).orElse(null); - if (operation == null - || operation.accountId() != candidate.accountId() - || !"PENDING".equals(operation.status()) - || operation.reconciliationAttemptCount() >= maxAttempts - || operation.nextReconciliationAttemptAt() == null - || operation.nextReconciliationAttemptAt().isAfter(now)) { - return ReconciliationResult.SKIPPED; - } - return recordUnresolvedAttempt(operation, now, "JOIN_READBACK_UNAVAILABLE"); - }); + ReconciliationResult result = + joinTransactionTemplate.execute( + transactionStatus -> { + joinOperationRepository.lockAccount(candidate.accountId()); + JoinOperation operation = + joinOperationRepository.findForUpdate(candidate.requestId()).orElse(null); + if (operation == null + || operation.accountId() != candidate.accountId() + || !"PENDING".equals(operation.status()) + || operation.nextReconciliationAttemptAt() == null + || operation.nextReconciliationAttemptAt().isAfter(now)) { + return ReconciliationResult.SKIPPED; + } + return recordUnresolvedAttempt(operation, now, "JOIN_READBACK_UNAVAILABLE"); + }); + return result == null ? ReconciliationResult.SKIPPED : result; } catch (RuntimeException ex) { logger.warn( "JOIN reconciliation could not persist a retry diagnostic for request {} ({})", candidate.requestId(), ex.getClass().getSimpleName()); + return ReconciliationResult.SKIPPED; } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index f67c20479b..dbd67d5256 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -22,6 +22,8 @@ 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.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.service.AccountJoinReconciliationService; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; @@ -81,6 +83,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; @Autowired private AccountJoinReconciliationService reconciliationService; + @Autowired private AccountJoinOperationRepository joinOperationRepository; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -98,13 +101,13 @@ void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplica // This is a synthetic ambiguous row assembled from a genuine committed JOIN. The current // atomic terminal transaction cannot naturally commit membership/audit while leaving the // operation PENDING; this fixture tests the exact readback branch without inventing evidence. - makeOperationPendingWithRetainedEvidence(fixture); + makeOperationPendingWithRetainedEvidence(fixture, 2); Instant scopeExpiry = expireScopeBeforeReconciliationButAfterEvaluation(fixture); Instant now = scopeExpiry.plusSeconds(1); reconciliationService.reconcileDueOperations(now); - assertOperation(fixture, "COMMITTED", "JOINED", 0, null); + assertOperation(fixture, "COMMITTED", "JOINED", 2, null); assertThat( dsl.resultQuery( "SELECT COUNT(*) FROM account_join_operations WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED' AND membership_id = ? AND outcome_membership_version = 1 AND outcome_membership_authority_generation = 1", @@ -128,7 +131,7 @@ void absentScopeAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostic dsl.execute( "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", AccountJoinDigest.tokenHash(absentScope.connectScopeId())); - assertUnresolved(absentScope, "JOIN_SCOPE_EVIDENCE_ABSENT"); + assertUnresolvedAtThreshold(absentScope, "JOIN_SCOPE_EVIDENCE_ABSENT"); assertThat(countMemberships(absentScope)).isEqualTo(1L); assertThat(countJoinOutbox(absentScope)).isEqualTo(1L); @@ -137,8 +140,10 @@ void absentScopeAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostic "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", expiredWithoutMembership.accountId(), expiredWithoutMembership.tenantId()); - expireScopeBeforeReconciliationButAfterEvaluation(expiredWithoutMembership); - assertUnresolved(expiredWithoutMembership, "MEMBERSHIP_EVIDENCE_ABSENT"); + Instant scopeExpiry = + expireScopeBeforeReconciliationButAfterEvaluation(expiredWithoutMembership); + assertUnresolvedAtThreshold( + expiredWithoutMembership, "MEMBERSHIP_EVIDENCE_ABSENT", scopeExpiry.plusSeconds(1)); assertThat(countMemberships(expiredWithoutMembership)).isZero(); assertThat(countJoinOutbox(expiredWithoutMembership)).isEqualTo(1L); } @@ -196,7 +201,7 @@ void concurrentCallerRetryAndReconcilerKeepSingleMembershipTransitionAndAudit() } @Test - void naturallyAbandonedPendingIntentStaysVisibleAndStopsAtConfiguredAttemptLimit() { + void naturallyAbandonedPendingIntentRemainsDueAfterConfiguredDiagnosticThreshold() { JoinFixture fixture = fixture("active"); when(gameSessionClient.getAdmissionPointer(fixture.tenantId(), WORLD_SLUG, REALM_SLUG)) .thenThrow(new IllegalStateException("simulated unavailable admission authority")); @@ -221,10 +226,101 @@ void naturallyAbandonedPendingIntentStaysVisibleAndStopsAtConfiguredAttemptLimit reconciliationService.reconcileDueOperations(firstAttemptAt.plusSeconds(5)); assertOperation(fixture, "PENDING", null, 2, "JOIN_OPERATION_POLICY_UNPROVEN"); + reconciliationService.reconcileDueOperations(firstAttemptAt.plusSeconds(7)); + assertOperation(fixture, "PENDING", null, 2, "JOIN_OPERATION_POLICY_UNPROVEN"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + } + + @Test + void aboveThresholdAttemptCountIsPreservedWithoutOverflowAndKeepsScheduling() { + JoinFixture fixture = fixture("active"); + when(gameSessionClient.getAdmissionPointer(fixture.tenantId(), WORLD_SLUG, REALM_SLUG)) + .thenThrow(new IllegalStateException("simulated unavailable admission authority")); + join(fixture); + setReconciliationAttempts(fixture, Integer.MAX_VALUE); + + Instant now = Instant.now().plusSeconds(2); + reconciliationService.reconcileDueOperations(now); + assertOperation(fixture, "PENDING", null, Integer.MAX_VALUE, "JOIN_OPERATION_POLICY_UNPROVEN"); + reconciliationService.reconcileDueOperations(now.plusSeconds(2)); + assertOperation(fixture, "PENDING", null, Integer.MAX_VALUE, "JOIN_OPERATION_POLICY_UNPROVEN"); assertThat(countMemberships(fixture)).isZero(); assertThat(countJoinOutbox(fixture)).isZero(); } + @Test + void staleDueTimestampFencesLostUpdateAfterCounterSaturatesAtThreshold() { + JoinFixture fixture = fixture("active"); + when(gameSessionClient.getAdmissionPointer(fixture.tenantId(), WORLD_SLUG, REALM_SLUG)) + .thenThrow(new IllegalStateException("simulated unavailable admission authority")); + accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.requestId())); + setReconciliationAttempts(fixture, 2); + JoinOperation observed = joinOperationRepository.find(fixture.requestId()).orElseThrow(); + Instant firstAttemptAt = Instant.now().plusSeconds(2); + Instant firstNextAttemptAt = firstAttemptAt.plusMillis(1_000); + + boolean firstUpdated = + joinOperationRepository.recordReconciliationAttempt( + fixture.requestId(), + observed.reconciliationAttemptCount(), + 2, + observed.nextReconciliationAttemptAt(), + firstAttemptAt, + "FIRST_THRESHOLD_ATTEMPT", + firstNextAttemptAt); + assertThat(firstUpdated).isTrue(); + + boolean staleUpdated = + joinOperationRepository.recordReconciliationAttempt( + fixture.requestId(), + observed.reconciliationAttemptCount(), + 2, + observed.nextReconciliationAttemptAt(), + firstNextAttemptAt, + "STALE_RECONCILIATION_CANDIDATE", + firstNextAttemptAt.plusMillis(1_000)); + + assertThat(staleUpdated).isFalse(); + assertOperation(fixture, "PENDING", null, 2, "FIRST_THRESHOLD_ATTEMPT"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + } + + @Test + void twoWorkersRecoverThresholdPendingEvidenceWithoutDuplicatingMembershipOrAudit() + throws Exception { + JoinFixture fixture = committedEvidencePendingFixture(); + setReconciliationAttempts(fixture, 2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Instant now = Instant.now().plusSeconds(1); + Future first = + executor.submit( + () -> { + await(start); + reconciliationService.reconcileDueOperations(now); + }); + Future second = + executor.submit( + () -> { + await(start); + reconciliationService.reconcileDueOperations(now); + }); + start.countDown(); + first.get(30, TimeUnit.SECONDS); + second.get(30, TimeUnit.SECONDS); + + assertOperation(fixture, "COMMITTED", "JOINED", 2, null); + assertMembershipAndAuditOnce(fixture, originalMembershipId(fixture)); + } finally { + executor.shutdownNow(); + } + } + private JoinFixture committedEvidencePendingFixture() { JoinFixture fixture = fixture("active"); JoinPublicProductionResult committed = join(fixture); @@ -235,15 +331,31 @@ private JoinFixture committedEvidencePendingFixture() { } private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture) { + makeOperationPendingWithRetainedEvidence(fixture, 0); + } + + private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture, int attempts) { int updated = dsl.execute( - "UPDATE account_join_operations SET status = 'PENDING', outcome = NULL, membership_id = NULL, outcome_membership_version = NULL, outcome_membership_authority_generation = NULL, reconciliation_attempt_count = 0, last_reconciliation_attempt_at = NULL, last_reconciliation_attempt_reason = NULL, next_reconciliation_attempt_at = CURRENT_TIMESTAMP - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED'", + "UPDATE account_join_operations SET status = 'PENDING', outcome = NULL, membership_id = NULL, outcome_membership_version = NULL, outcome_membership_authority_generation = NULL, reconciliation_attempt_count = ?, last_reconciliation_attempt_at = CASE WHEN ? = 0 THEN NULL ELSE CURRENT_TIMESTAMP - INTERVAL '2 seconds' END, last_reconciliation_attempt_reason = CASE WHEN ? = 0 THEN NULL ELSE 'PRIOR_RECONCILIATION_ATTEMPT' END, next_reconciliation_attempt_at = CURRENT_TIMESTAMP - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED'", + attempts, + attempts, + attempts, fixture.requestId()); assertThat(updated).isEqualTo(1); assertThat(countMemberships(fixture)).isEqualTo(1L); assertThat(countJoinOutbox(fixture)).isEqualTo(1L); } + private void setReconciliationAttempts(JoinFixture fixture, int attempts) { + int updated = + dsl.execute( + "UPDATE account_join_operations SET reconciliation_attempt_count = ?, last_reconciliation_attempt_at = CURRENT_TIMESTAMP - INTERVAL '2 seconds', last_reconciliation_attempt_reason = 'PRIOR_RECONCILIATION_ATTEMPT', next_reconciliation_attempt_at = CURRENT_TIMESTAMP - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'PENDING'", + attempts, + fixture.requestId()); + assertThat(updated).isEqualTo(1); + } + private Instant expireScopeBeforeReconciliationButAfterEvaluation(JoinFixture fixture) { String expiresAt = dsl.resultQuery( @@ -263,6 +375,19 @@ private void assertUnresolved(JoinFixture fixture, String reason) { assertOperation(fixture, "PENDING", null, 1, reason); } + private void assertUnresolvedAtThreshold(JoinFixture fixture, String reason) { + assertUnresolvedAtThreshold(fixture, reason, Instant.now().plusSeconds(2)); + } + + private void assertUnresolvedAtThreshold(JoinFixture fixture, String reason, Instant now) { + setReconciliationAttempts(fixture, 2); + reconciliationService.reconcileDueOperations(now); + assertOperation(fixture, "PENDING", null, 2, reason); + + reconciliationService.reconcileDueOperations(now.plusMillis(1_500)); + assertOperation(fixture, "PENDING", null, 2, reason); + } + private void assertOperation( JoinFixture fixture, String status, String outcome, int attempts, String reason) { var row = 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..6dd71e97a6 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 @@ -54,8 +54,8 @@ class AccountJoinReconciliationServiceTest { @Test void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { Fixture fixture = fixture(5); - JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); - stubDue(fixture, pending, 5); + JoinOperation pending = pendingOperation(5, NOW.minusSeconds(1)); + stubDue(fixture, pending); 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))); @@ -78,40 +78,54 @@ void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { MEMBERSHIP_VERSION, MEMBERSHIP_AUTHORITY_GENERATION); verify(fixture.joinOperations, never()) - .recordReconciliationAttempt(anyString(), anyInt(), anyInt(), any(), anyString(), any()); + .recordReconciliationAttempt( + anyString(), anyInt(), anyInt(), any(), any(), anyString(), any()); assertThat(reconciliationCounter(fixture, "committed")).isEqualTo(1); } @Test - void missingMembershipAfterScopeExpiryStaysPendingAndRecordsBackoffReason() { + void missingMembershipAfterScopeExpiryStaysPendingAndReschedulesAtTheAttemptThreshold() { Fixture fixture = fixture(3); - JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); - stubDue(fixture, pending, 3); + JoinOperation pending = pendingOperation(3, NOW.minusSeconds(1)); + stubDue(fixture, pending); 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.empty()); when(fixture.joinOperations.recordReconciliationAttempt( - REQUEST_ID, 0, 3, NOW, "MEMBERSHIP_EVIDENCE_ABSENT", NOW.plusMillis(5_000))) + REQUEST_ID, + 3, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + NOW.plusMillis(5_000))) .thenReturn(true); fixture.service.reconcileDueOperations(NOW); verify(fixture.joinOperations) .recordReconciliationAttempt( - REQUEST_ID, 0, 3, NOW, "MEMBERSHIP_EVIDENCE_ABSENT", NOW.plusMillis(5_000)); + REQUEST_ID, + 3, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + NOW.plusMillis(5_000)); verify(fixture.joinOperations, never()) .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); verifyNoInteractions(fixture.auditOutbox); assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); + assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isZero(); } @Test - void absentJoinAuditStaysPendingAndLogsAttemptLimitMetric() { + void attemptThresholdIsReportedOnceAndCappedCountStillReschedules() { Fixture fixture = fixture(1); JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); - stubDue(fixture, pending, 1); + stubDue(fixture, pending); 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))); @@ -120,24 +134,94 @@ void absentJoinAuditStaysPendingAndLogsAttemptLimitMetric() { when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn(Optional.empty()); when(fixture.joinOperations.recordReconciliationAttempt( - REQUEST_ID, 0, 1, NOW, "JOIN_AUDIT_ENVELOPE_ABSENT", NOW.plusMillis(5_000))) + REQUEST_ID, + 0, + 1, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_ABSENT", + NOW.plusMillis(5_000))) .thenReturn(true); fixture.service.reconcileDueOperations(NOW); + JoinOperation atThreshold = pendingOperation(1, NOW.plusMillis(5_000)); + when(fixture.joinOperations.findDuePendingReconciliation(NOW.plusMillis(6_000), 10)) + .thenReturn(List.of(atThreshold)); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(atThreshold)); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 1, + 1, + NOW.plusMillis(5_000), + NOW.plusMillis(6_000), + "JOIN_AUDIT_ENVELOPE_ABSENT", + NOW.plusMillis(11_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW.plusMillis(6_000)); + verify(fixture.joinOperations) .recordReconciliationAttempt( - REQUEST_ID, 0, 1, NOW, "JOIN_AUDIT_ENVELOPE_ABSENT", NOW.plusMillis(5_000)); + REQUEST_ID, + 0, + 1, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_ABSENT", + NOW.plusMillis(5_000)); verify(fixture.joinOperations, never()) .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isEqualTo(1); + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 1, + 1, + NOW.plusMillis(5_000), + NOW.plusMillis(6_000), + "JOIN_AUDIT_ENVELOPE_ABSENT", + NOW.plusMillis(11_000)); + } + + @Test + void readbackExceptionAtTheThresholdStillSchedulesAnotherAttempt() { + Fixture fixture = fixture(2); + JoinOperation pending = pendingOperation(2, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)) + .thenThrow(new IllegalStateException("transient read failure")) + .thenReturn(Optional.of(pending)); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 2, + 2, + NOW.minusSeconds(1), + NOW, + "JOIN_READBACK_UNAVAILABLE", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 2, + 2, + NOW.minusSeconds(1), + NOW, + "JOIN_READBACK_UNAVAILABLE", + NOW.plusMillis(5_000)); + assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); + assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isZero(); } @Test void wrongPayloadDigestStaysPending() { Fixture fixture = fixture(3); JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); - stubDue(fixture, pending, 3); + stubDue(fixture, pending); 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))); @@ -146,14 +230,26 @@ void wrongPayloadDigestStaysPending() { when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, sha256("wrong")))); when(fixture.joinOperations.recordReconciliationAttempt( - REQUEST_ID, 0, 3, NOW, "JOIN_AUDIT_ENVELOPE_UNCLEAR", NOW.plusMillis(5_000))) + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_UNCLEAR", + NOW.plusMillis(5_000))) .thenReturn(true); fixture.service.reconcileDueOperations(NOW); verify(fixture.joinOperations) .recordReconciliationAttempt( - REQUEST_ID, 0, 3, NOW, "JOIN_AUDIT_ENVELOPE_UNCLEAR", NOW.plusMillis(5_000)); + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_UNCLEAR", + NOW.plusMillis(5_000)); verify(fixture.joinOperations, never()) .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); } @@ -162,7 +258,7 @@ void wrongPayloadDigestStaysPending() { void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { Fixture fixture = fixture(3); JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); - stubDue(fixture, pending, 3); + stubDue(fixture, pending); 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))); @@ -175,14 +271,26 @@ void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { joinAuditEnvelope( "other-world", TENANT_ID, AccountAuditDigest.ofPayload(mismatchedPayload)))); when(fixture.joinOperations.recordReconciliationAttempt( - REQUEST_ID, 0, 3, NOW, "JOIN_AUDIT_ENVELOPE_UNCLEAR", NOW.plusMillis(5_000))) + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_UNCLEAR", + NOW.plusMillis(5_000))) .thenReturn(true); fixture.service.reconcileDueOperations(NOW); verify(fixture.joinOperations) .recordReconciliationAttempt( - REQUEST_ID, 0, 3, NOW, "JOIN_AUDIT_ENVELOPE_UNCLEAR", NOW.plusMillis(5_000)); + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_ENVELOPE_UNCLEAR", + NOW.plusMillis(5_000)); verify(fixture.joinOperations, never()) .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); } @@ -191,19 +299,31 @@ void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { void wrongRetainedTargetStaysPending() { Fixture fixture = fixture(3); JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); - stubDue(fixture, pending, 3); + stubDue(fixture, pending); when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PRIVATE", TENANT_ID, WORLD_SLUG))); when(fixture.joinOperations.recordReconciliationAttempt( - REQUEST_ID, 0, 3, NOW, "JOIN_SCOPE_EVIDENCE_MISMATCH", NOW.plusMillis(5_000))) + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_SCOPE_EVIDENCE_MISMATCH", + NOW.plusMillis(5_000))) .thenReturn(true); fixture.service.reconcileDueOperations(NOW); verify(fixture.joinOperations) .recordReconciliationAttempt( - REQUEST_ID, 0, 3, NOW, "JOIN_SCOPE_EVIDENCE_MISMATCH", NOW.plusMillis(5_000)); + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + 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); @@ -213,7 +333,7 @@ void wrongRetainedTargetStaysPending() { void repeatedRunDoesNotFinishSameJoinTwice() { Fixture fixture = fixture(3); JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); - when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10, 3)) + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)) .thenReturn(List.of(pending), List.of()); when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) @@ -244,7 +364,7 @@ void concurrentCallerTerminalizationIsSkippedAfterAccountAndOperationLocks() { Fixture fixture = fixture(3); JoinOperation pendingSnapshot = pendingOperation(0, NOW.minusSeconds(1)); JoinOperation terminalOperation = terminalOperation(); - stubDue(fixture, pendingSnapshot, 3); + stubDue(fixture, pendingSnapshot); when(fixture.joinOperations.findForUpdate(REQUEST_ID)) .thenReturn(Optional.of(terminalOperation)); @@ -256,7 +376,8 @@ void concurrentCallerTerminalizationIsSkippedAfterAccountAndOperationLocks() { verify(fixture.joinOperations, never()) .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); verify(fixture.joinOperations, never()) - .recordReconciliationAttempt(anyString(), anyInt(), anyInt(), any(), anyString(), any()); + .recordReconciliationAttempt( + anyString(), anyInt(), anyInt(), any(), any(), anyString(), any()); verifyNoInteractions(fixture.connectScopes, fixture.memberships, fixture.auditOutbox); } @@ -284,8 +405,8 @@ private static Fixture fixture(int maxAttempts) { service, joinOperations, connectScopes, memberships, auditOutbox, meterRegistry); } - private static void stubDue(Fixture fixture, JoinOperation operation, int maxAttempts) { - when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10, maxAttempts)) + private static void stubDue(Fixture fixture, JoinOperation operation) { + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)) .thenReturn(List.of(operation)); } From 4d75a94ff38372de71574b7adb5df678a26263ed Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:52:48 +1300 Subject: [PATCH 35/55] Validate retained development TLS bundles without rotating identity --- .../system-architecture-overview.md | 2 +- .../system-architecture-protocol-bridging.md | 4 +- .../system-architecture-reconnection.md | 4 +- .../consequential-decision-inventory.md | 2 +- dev-tools/certs/README.md | 1 + dev-tools/certs/ensure-dev-certs.sh | 20 +-- dev-tools/certs/generate-dev-certs.sh | 124 ++++++++++++++- ...ocal-compose-workload-identity-contract.sh | 150 ++++++++++++++++++ 8 files changed, 284 insertions(+), 23 deletions(-) diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index 7ae77bec21..8ecea2bafb 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -529,7 +529,7 @@ Gameplay authentication is transport-specific. Credential-bearing Telnet and oth The receiver token is the exact `game-session-account-delegation` JWT profile with audience `account-service`; it is an Account-issued private backend credential, never a client gameplay credential. Its registry and rotation rules do not define the active gameplay-session lifetime or the bounded continuity/reconnect cache lifetime. If the Account response is lost during credential-bearing text login, Game Session retries with the same `requestId` and exact request digest. Account resumes matching pending work or returns the stored committed result/terminal outcome; it must not mint a second token merely because the first response was not observed. A confirmed binding-CAS conflict or superseded binding causes Game Session to keep the candidate unusable and issue Account's idempotent retire request for that exact operation and token identity. An ambiguous timeout instead remains fail-closed and provisional while Game Session reconciles the expected binding generation plus operation identity against the authoritative binding: it retires the candidate only after proving that the CAS did not commit, and completes installation or the canonical superseded outcome when the committed operation is found. Account performs bounded orphan cleanup after the operation's lease/expiry horizon; an orphan registry record is never sufficient to make a gameplay binding admissible. Proof must cover Account success followed by response loss, confirmed binding-CAS conflict, ambiguous CAS reconciliation for both committed and uncommitted outcomes, retry with the same request ID, retry with a conflicting digest, and cleanup/reconciliation after each cross-service failure window. The protocol uses ordered durable evidence, idempotent owner-side operations, and fail-closed provisional state; it does not claim a cross-store transaction. -After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Current eligible public missing or existing non-admitting membership still returns non-actionable `JOIN_REQUIRED` from `PLAY`. The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch now exist locally, but this does not establish frontend or production readiness: PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and membership lifecycle/generation rereads remain unproved. Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). +After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Current admission-reader containment and local response-classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding; Game Session maps a live membership-read failure to `WORLD_ACCESS_DENIED`. Its locally supplied-authority `JOIN_REQUIRED` classification is not live admission proof. The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch now exist locally, but this does not establish frontend or production readiness: PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and membership lifecycle/generation rereads remain unproved. Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Session recovery/takeover is authorized by the gameplay binding plus current Account identity, membership, entitlement, and revocation authority; it does not require the previous backend token registry record to remain valid. When transport-specific reauthentication is required, the client must complete the applicable fresh credential/bootstrap and connect-context steps before backend calls resume. A missing or expired prior token therefore causes replacement or reauthentication, not acceptance of stale token state. > 🔗 See [Authentication & Authorization](./system-architecture-authentication.md) and [Reconnection Strategy](./system-architecture-reconnection.md) for detailed JWT format and session flow. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 3eea4fd8e7..184004a0f9 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete; the current path can still stop with non-actionable `JOIN_REQUIRED` when membership/admission evidence is not admitting. Private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Current admission-reader containment and local classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status): Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`. A supplied-authority `JOIN_REQUIRED` classification does not establish live admission. Private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. The local `Join & Play` endpoint and Account writer exist, but lifecycle-aware admission, the required issuance reread, and complete runtime/deployment proof remain incomplete; the Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`, while current consumers do not enforce those fields. An eligible public-production membership that is missing (`membershipExists=false`) or existing but non-admitting (`gameplayAdmissionAllowed=false`) therefore remains non-actionable `JOIN_REQUIRED` with no mutation; the latter cannot be classified specifically as `INACTIVE` by the current admission path. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients may still stop with the same non-actionable `JOIN_REQUIRED` outcome when membership evidence is not admitting, despite the local join dispatch existing. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. Current admission-reader containment and local response-classification status are owned by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account runtime membership, entitlement, and grant readers fail closed before data access pending typed caller/target binding; a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`, while a supplied-authority `JOIN_REQUIRED` classification is not proof of live admission. Complete runtime/deployment and lifecycle-aware issuance-reread proof remain incomplete. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 298c5e5cee..3a86f01d46 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,7 +10,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Game Session locally validates lifecycle, authority-generation, membership-version, and evaluation-time fields when supplied by its `PLAY` authority response. Its local response-classification branches permit `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks; `ACTIVE` but non-admitting membership is denied without JOIN advice, and non-public denial does not offer public JOIN. These branches do not establish live composed admission: Account membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before reads until typed caller/target binding exists, and the resulting live membership failure maps to `WORLD_ACCESS_DENIED`. No successful public `PLAY` or first-party browser `JOIN` is established. Account's explicit JOIN operation and direct-text scope/dispatch seams exist locally, while the public Gateway join route remains denied. PostgreSQL execution, direct text-to-Logging proof, unknown-outcome recovery, and the independent connect-token membership-version/authority-generation issuance reread remain open; connect-token issuance retains its separate local response classification and grant-validation gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; the target authority and error detail remain in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission authority and local classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding; Game Session maps a live membership-read failure to `WORLD_ACCESS_DENIED`. Its locally supplied-authority `JOIN_REQUIRED` classification is not live admission proof. No successful public `PLAY` or first-party browser `JOIN` is established. Account's explicit JOIN operation and direct-text scope/dispatch seams exist locally, while the public Gateway join route remains denied. PostgreSQL execution, direct text-to-Logging proof, unknown-outcome recovery, and the independent connect-token membership-version/authority-generation issuance reread remain open; connect-token issuance retains its separate local response classification and grant-validation gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; the target authority and error detail remain in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). - **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -89,7 +89,7 @@ A client must not infer current membership or target identity from a stale Redis ### Public membership repair during reconnect (normative) -Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete; text `PLAY` still returns non-actionable `JOIN_REQUIRED` until explicit membership is joined. +Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete. Current authority-reader containment and local response classification are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift): Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before reads pending typed caller/target binding, so the local `JOIN_REQUIRED` branch does not establish live `JOIN_REQUIRED`; Game Session maps the live membership-read failure to `WORLD_ACCESS_DENIED`. Redis-backed session state allows resumable recovery when the gameplay binding is still logically valid, or a fresh login when it is not. The canonical continuity anchor, resume episode, physical TTL rules, token refresh, and transcript authority are defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Reconnection retains only this transport consequence: Redis key presence alone never authorizes resume, and a new transport never replays prior bytes. diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 05a176e356..0fee2e6a3f 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -149,7 +149,7 @@ No implementation-blocking import override is active. Record an override here wi ### Packet 2: Identity, Authority, And Security -Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`; the Account explicit `JOIN` path, including browser `POST /auth/bootstrap/join`, and direct-text REALMS-scope/JOIN dispatch now exist locally. Current text `PLAY` and connect-token issuance require existing caller-bound membership and return canonical `JOIN_REQUIRED` for eligible missing or `INACTIVE` public-production membership, while the obsolete implicit membership-writer RPC/client/service seam has been removed. Full workflow/deployment/PostgreSQL/direct text-to-Logging proof, pending unknown-outcome reconciliation, and membership lifecycle/generation rereads remain open. The target admission contract retains `JOIN_REQUIRED` for policy-permitted missing or `INACTIVE` membership. `WORLD_ACCESS_DENIED` is reserved for another reachable authoritative world/tenant denial and is mutually exclusive with `JOIN_REQUIRED`. A realm grant never substitutes for membership, and the connect-token membership-version plus membership-authority-generation reread remains a gap. The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices, not proof claims: the owning [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status) records the missing tenant-scoped roles, switching controls, and implementation state, while its [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof) section records focused evidence and remaining proof gaps. +Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`; the Account explicit `JOIN` path, including browser `POST /auth/bootstrap/join`, and direct-text REALMS-scope/JOIN dispatch now exist locally. Current Account authority-reader containment and local `PLAY` classification are recorded in [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status), [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status): runtime membership, entitlement, and grant reads fail closed with `FAILED_PRECONDITION` before Account data access pending typed caller/target binding, and the live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`. The supplied-authority `JOIN_REQUIRED` classification is a local seam, not live admission proof. Full workflow/deployment/PostgreSQL/direct text-to-Logging proof, pending unknown-outcome reconciliation, and membership lifecycle/generation rereads remain open. The target admission contract remains owned by [Authentication](../../architecture/system-architecture-authentication.md#login-and-session-flow); current implementation and proof gaps are tracked in the [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status), including [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof). The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices, not proof claims. Packet 2 count reconciliation: the 31 reviewed decisions are covered by the checked dispositions for ADRs 0020-0050, excluding the historical service-scan alias. The Packet 2 disposition contains exactly those 31 reviewed decisions; the alias is navigation-only and is not a checked disposition row. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index 6e39772235..2b97d27fec 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -7,6 +7,7 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. +- When the complete generic bundle already exists, the generator validates the CA/key pair, the shared client/server leaf certificates and key pairs, their current trust, purposes, and local SANs, plus the `dev-*` aliases. An invalid existing bundle fails closed without changing or rotating the CA or issued leaves. `ensure-dev-certs.sh` uses the same check, so local Compose setup stops until the material is diagnosed or deliberately reissued. To reissue, first back up or intentionally discard the local generated certificate set, then run `dev-tools/certs/clean-dev-certs.sh` followed by `dev-tools/certs/ensure-dev-certs.sh`; unexpected files are preserved by cleanup. - `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only gRPC workload leaf for the five publication services, Account, Game Session, or Social Groups with the exact SPIFFE URI and service DNS SANs. The generic generator keeps workload private keys mode `0600`; `ensure-dev-certs.sh` changes permissions only on its ignored local Compose runtime projection so non-root containers can read their own local keys. Hosted preview and dev-demo do not use this signing mode for runtime issuance; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local Compose entrypoints have the shared cert/key set and distinct Account, Game Session, and Social Groups workload identities before Compose boots. It validates the local CA, URI SAN, DNS SAN, and key pair, then creates `dev-tools/certs/local-runtime/` with only runtime-facing certificate material. The projection is ignored by Git and never contains `ca.key`; the host-side CA private key remains mode `0600`. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 0b15954231..ab255e122d 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -59,17 +59,9 @@ if [[ -d "$RUNTIME_DIR" ]]; then done < <(find -P "$RUNTIME_DIR" -mindepth 1 -type l -print0) fi -missing=0 -for file in "${required_files[@]}"; do - if [[ ! -f "$file" ]]; then - missing=1 - break - fi -done - -if [[ "$missing" != "0" ]]; then - "$GENERATOR" "$CERT_DIR" -fi +# Route complete bundles through the generator's read-only validation path as +# well as routing missing bundles through its existing generation path. +"$GENERATOR" "$CERT_DIR" chmod 600 "$CERT_DIR/ca.key" workloads=(account-service game-session-service social-groups-service) @@ -112,8 +104,10 @@ done # per-service runtime projection copied below; the generic generator output # remains mode 0600. chmod 700 "$WORKLOAD_DIR" -chmod 644 "$WORKLOAD_DIR"/*.crt -chmod 600 "$WORKLOAD_DIR"/*.key +for workload in "${workloads[@]}"; do + chmod 644 "$WORKLOAD_DIR/$workload.crt" + chmod 600 "$WORKLOAD_DIR/$workload.key" +done # Mount only runtime material. Protected callers receive their own leaf, not # the other protected services' private keys. No projection includes ca.key. diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index ce997a26d2..359d940bb2 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -123,10 +123,126 @@ if [[ -d "$CERT_DIR" ]]; then \) -print0) fi -if [ -f "$CERT_DIR/ca.crt" ] && [ -f "$CERT_DIR/ca.key" ] \ - && [ -f "$CERT_DIR/client.crt" ] && [ -f "$CERT_DIR/client.key" ] \ - && [ -f "$CERT_DIR/server.crt" ] && [ -f "$CERT_DIR/server.key" ] \ - && [ -f "$CERT_DIR/dev-cert.pem" ] && [ -f "$CERT_DIR/dev-key.pem" ] && [ -f "$CERT_DIR/dev-ca.pem" ]; then +generic_bundle_files=( + ca.crt ca.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem server.crt server.key +) +local_service_dns_names=( + localhost account-service automation-scripting-service entity-management-service + game-design-service game-logic-service game-session-service logging-admin-service + social-groups-service spring-cloud-gateway tcp-proxy-service world-management-service +) + +certificate_matches_private_key() { + local certificate="$1" + local private_key="$2" + local certificate_public_key private_key_public_key + + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout 2>/dev/null \ + | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null)" || return 1 + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null)" || return 1 + [[ -n "$certificate_public_key" && "$certificate_public_key" == "$private_key_public_key" ]] +} + +validate_existing_leaf() { + local certificate="$1" + local private_key="$2" + local description="$3" + local purpose subject_alt_names dns_name san_pattern + + if ! openssl x509 -in "$certificate" -noout >/dev/null 2>&1; then + echo "existing local $description certificate is malformed: $certificate" >&2 + return 1 + fi + if ! openssl x509 -in "$certificate" -checkend 0 -noout >/dev/null 2>&1; then + echo "existing local $description certificate is expired or expires now: $certificate" >&2 + return 1 + fi + for purpose in sslclient sslserver; do + if ! openssl verify -purpose "$purpose" -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1; then + echo "existing local $description certificate does not verify for $purpose under ca.crt: $certificate" >&2 + return 1 + fi + done + if ! certificate_matches_private_key "$certificate" "$private_key"; then + echo "existing local $description certificate and private key do not match: $certificate / $private_key" >&2 + return 1 + fi + if ! subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName 2>/dev/null)"; then + echo "existing local $description certificate has no readable subject alternative names: $certificate" >&2 + return 1 + fi + for dns_name in "${local_service_dns_names[@]}"; do + san_pattern="DNS:${dns_name}([,[:space:]]|$)" + if [[ ! "$subject_alt_names" =~ $san_pattern ]]; then + echo "existing local $description certificate is missing the expected DNS SAN $dns_name: $certificate" >&2 + return 1 + fi + done + if [[ "$subject_alt_names" != *"IP Address:127.0.0.1"* ]]; then + echo "existing local $description certificate is missing the expected loopback IP SAN: $certificate" >&2 + return 1 + fi +} + +validate_existing_generic_bundle() { + local ca_cert="$CERT_DIR/ca.crt" + local ca_key="$CERT_DIR/ca.key" + + if ! openssl x509 -in "$ca_cert" -noout >/dev/null 2>&1; then + echo "existing local certificate authority certificate is malformed: $ca_cert" >&2 + return 1 + fi + if ! openssl x509 -in "$ca_cert" -checkend 0 -noout >/dev/null 2>&1; then + echo "existing local certificate authority certificate is expired or expires now: $ca_cert" >&2 + return 1 + fi + if ! openssl verify -check_ss_sig -CAfile "$ca_cert" "$ca_cert" >/dev/null 2>&1; then + echo "existing local certificate authority is not a valid trusted self-signed certificate: $ca_cert" >&2 + return 1 + fi + if ! certificate_matches_private_key "$ca_cert" "$ca_key"; then + echo "existing local certificate authority certificate and private key do not match: $ca_cert / $ca_key" >&2 + return 1 + fi + + if ! validate_existing_leaf "$CERT_DIR/server.crt" "$CERT_DIR/server.key" "server"; then + return 1 + fi + if ! validate_existing_leaf "$CERT_DIR/client.crt" "$CERT_DIR/client.key" "client"; then + return 1 + fi + + if ! cmp -s "$CERT_DIR/ca.crt" "$CERT_DIR/dev-ca.pem"; then + echo "existing local legacy CA alias does not match ca.crt: $CERT_DIR/dev-ca.pem" >&2 + return 1 + fi + if ! cmp -s "$CERT_DIR/client.crt" "$CERT_DIR/dev-cert.pem"; then + echo "existing local legacy certificate alias does not match client.crt: $CERT_DIR/dev-cert.pem" >&2 + return 1 + fi + if ! cmp -s "$CERT_DIR/client.key" "$CERT_DIR/dev-key.pem"; then + echo "existing local legacy private-key alias does not match client.key: $CERT_DIR/dev-key.pem" >&2 + return 1 + fi +} + +bundle_present=true +for filename in "${generic_bundle_files[@]}"; do + if [[ ! -f "$CERT_DIR/$filename" ]]; then + bundle_present=false + break + fi +done + +if [[ "$bundle_present" == "true" ]]; then + if ! validate_existing_generic_bundle; then + echo "Existing local certificate bundle is invalid in $CERT_DIR; no files were changed and the CA or issued leaves were not rotated." >&2 + echo "Back up this local certificate set, then deliberately reissue it with:" >&2 + printf ' %q %q\n' "$SCRIPT_DIR/clean-dev-certs.sh" "$CERT_DIR" >&2 + printf ' %q %q\n' "$SCRIPT_DIR/generate-dev-certs.sh" "$CERT_DIR" >&2 + exit 1 + fi echo "Dev certificates already exist in $CERT_DIR" exit 0 fi diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index 1b73877332..580a18929d 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -4,6 +4,9 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" CERT_DIR="$(mktemp -d)" trap 'rm -rf "$CERT_DIR"' EXIT +generic_bundle_files=( + ca.crt ca.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem server.crt server.key +) assert_mode() { local expected_mode="$1" @@ -16,6 +19,64 @@ assert_mode() { } } +copy_generic_bundle() { + local source_dir="$1" + local target_dir="$2" + mkdir -p "$target_dir" + for file in "${generic_bundle_files[@]}"; do + cp "$source_dir/$file" "$target_dir/$file" + done +} + +assert_invalid_existing_bundle_is_preserved() { + local bundle_dir="$1" + local case_name="$2" + local manifest="$CERT_DIR/$case_name.bundle.sha256" + local output="$CERT_DIR/$case_name.output" + local unmanaged_file="$bundle_dir/unmanaged-local.key" + local file + + printf 'unmanaged certificate sentinel\n' >"$unmanaged_file" + chmod 640 "$unmanaged_file" + for file in "${generic_bundle_files[@]}"; do + sha256sum "$bundle_dir/$file" + done >"$manifest" + sha256sum "$unmanaged_file" >>"$manifest" + + if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" "$bundle_dir" >"$output" 2>&1; then + echo "generate-dev-certs accepted an invalid complete bundle: $case_name" >&2 + exit 1 + fi + rg -Fq 'no files were changed' "$output" || { + echo "generate-dev-certs did not report fail-closed preservation for $case_name" >&2 + cat "$output" >&2 + exit 1 + } + sha256sum -c "$manifest" >/dev/null || { + echo "generate-dev-certs changed invalid bundle material: $case_name" >&2 + exit 1 + } + + if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$bundle_dir" >"$output" 2>&1; then + echo "ensure-dev-certs accepted an invalid complete bundle: $case_name" >&2 + exit 1 + fi + rg -Fq 'no files were changed' "$output" || { + echo "ensure-dev-certs did not report fail-closed preservation for $case_name" >&2 + cat "$output" >&2 + exit 1 + } + sha256sum -c "$manifest" >/dev/null || { + echo "ensure-dev-certs changed invalid bundle material: $case_name" >&2 + exit 1 + } + [[ "$(<"$unmanaged_file")" == 'unmanaged certificate sentinel' ]] || { + echo "an invalid bundle path changed or removed an unmanaged file: $case_name" >&2 + exit 1 + } + assert_mode 640 "$unmanaged_file" +} + assert_workload_certificate() { local workload="$1" local certificate="$CERT_DIR/local-runtime/$workload/workloads/$workload.crt" @@ -67,11 +128,100 @@ for profile in default account-service game-session-service social-groups-servic assert_mode 644 "$runtime_dir/$profile/dev-key.pem" done for workload in account-service game-session-service social-groups-service; do + assert_mode 644 "$CERT_DIR/workloads/$workload.crt" assert_mode 600 "$CERT_DIR/workloads/$workload.key" assert_mode 755 "$runtime_dir/$workload/workloads" assert_mode 644 "$runtime_dir/$workload/workloads/$workload.key" done +# Unmanaged regular files under workloads/ retain their own bytes and modes; +# only the three named local Compose identities are normalized by ensure. +mode_case="$CERT_DIR/unmanaged-workload-modes" +copy_generic_bundle "$CERT_DIR" "$mode_case" +mkdir -p "$mode_case/workloads" +printf 'unmanaged certificate sentinel\n' >"$mode_case/workloads/keep-me.crt" +printf 'unmanaged key sentinel\n' >"$mode_case/workloads/keep-me.key" +chmod 711 "$mode_case/workloads/keep-me.crt" +chmod 640 "$mode_case/workloads/keep-me.key" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$mode_case" +[[ "$(<"$mode_case/workloads/keep-me.crt")" == 'unmanaged certificate sentinel' \ + && "$(<"$mode_case/workloads/keep-me.key")" == 'unmanaged key sentinel' ]] || { + echo "ensure-dev-certs changed unmanaged workload certificate contents" >&2 + exit 1 +} +assert_mode 711 "$mode_case/workloads/keep-me.crt" +assert_mode 640 "$mode_case/workloads/keep-me.key" + +# Complete but unhealthy bundles fail closed through both public entrypoints. +# Their CA and issued leaves are left byte-for-byte unchanged for deliberate +# operator diagnosis or full local reissue. +malformed_case="$CERT_DIR/invalid-malformed-bundle" +copy_generic_bundle "$CERT_DIR" "$malformed_case" +printf 'malformed certificate\n' >"$malformed_case/ca.crt" +assert_invalid_existing_bundle_is_preserved "$malformed_case" malformed + +key_mismatch_case="$CERT_DIR/invalid-key-mismatch-bundle" +copy_generic_bundle "$CERT_DIR" "$key_mismatch_case" +cp "$CERT_DIR/workloads/account-service.key" "$key_mismatch_case/client.key" +cp "$key_mismatch_case/client.key" "$key_mismatch_case/dev-key.pem" +assert_invalid_existing_bundle_is_preserved "$key_mismatch_case" key-mismatch + +other_authority="$CERT_DIR/other-authority" +bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" "$other_authority" >/dev/null +wrong_issuer_case="$CERT_DIR/invalid-wrong-issuer-bundle" +copy_generic_bundle "$CERT_DIR" "$wrong_issuer_case" +for file in server.crt server.key client.crt client.key dev-cert.pem dev-key.pem; do + cp "$other_authority/$file" "$wrong_issuer_case/$file" +done +assert_invalid_existing_bundle_is_preserved "$wrong_issuer_case" wrong-issuer + +expired_case="$CERT_DIR/invalid-expired-bundle" +copy_generic_bundle "$CERT_DIR" "$expired_case" +cat >"$expired_case/expired.cnf" <<'EOF' +[req] +distinguished_name = req_distinguished_name +req_extensions = v3_req +prompt = no + +[req_distinguished_name] +CN = firemud-grpc + +[v3_req] +basicConstraints = critical,CA:false +keyUsage = critical,digitalSignature,keyEncipherment +extendedKeyUsage = serverAuth,clientAuth +subjectAltName = @alt_names + +[alt_names] +DNS.1 = localhost +DNS.2 = account-service +DNS.3 = automation-scripting-service +DNS.4 = entity-management-service +DNS.5 = game-design-service +DNS.6 = game-logic-service +DNS.7 = game-session-service +DNS.8 = logging-admin-service +DNS.9 = social-groups-service +DNS.10 = spring-cloud-gateway +DNS.11 = tcp-proxy-service +DNS.12 = world-management-service +IP.1 = 127.0.0.1 +EOF +openssl req -new -key "$expired_case/server.key" -config "$expired_case/expired.cnf" \ + -out "$expired_case/expired.csr" +openssl x509 -req -in "$expired_case/expired.csr" -CA "$expired_case/ca.crt" \ + -CAkey "$expired_case/ca.key" -set_serial 424242 -out "$expired_case/expired.crt" \ + -days 0 -sha256 -extensions v3_req -extfile "$expired_case/expired.cnf" >/dev/null +cp "$expired_case/expired.crt" "$expired_case/server.crt" +cp "$expired_case/expired.crt" "$expired_case/client.crt" +cp "$expired_case/expired.crt" "$expired_case/dev-cert.pem" +assert_invalid_existing_bundle_is_preserved "$expired_case" expired + +legacy_alias_case="$CERT_DIR/invalid-legacy-alias-bundle" +copy_generic_bundle "$CERT_DIR" "$legacy_alias_case" +printf 'wrong legacy alias\n' >"$legacy_alias_case/dev-cert.pem" +assert_invalid_existing_bundle_is_preserved "$legacy_alias_case" legacy-alias + expected_files=( default/ca.crt default/client.crt From 7a4eef4f5f70d24a99852bde90b3c5475d37ef3a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:29:31 +1300 Subject: [PATCH 36/55] Fix UTC JOIN scheduling and exact local workload identity proof --- .../system-architecture-protocol-bridging.md | 2 +- .../system-architecture-reconnection.md | 2 +- design/product/user-journeys/operators.md | 2 +- dev-tools/certs/ensure-dev-certs.sh | 5 +- ...ocal-compose-workload-identity-contract.sh | 59 ++++++++++++++++++- .../V28__account_join_reconciliation.sql | 3 +- ...ReconciliationPostgresIntegrationTest.java | 48 +++++++++++++++ 7 files changed, 113 insertions(+), 8 deletions(-) diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 184004a0f9..8f19cdb2e1 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet runtime-complete; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or end-to-end `JOIN`. The local Account `POST /auth/bootstrap/join` route and `JoinPublicProductionMembership` operation, plus Game Session text `JOIN` dispatch, now exist; PostgreSQL execution, pending-operation recovery, and direct-text/first-party end-to-end proof remain gaps. The required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance also remains unimplemented/unproved. On its fresh Account-authority path, current connect-token issuance and text `PLAY` consume the Account membership response fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but these consumers do not enforce lifecycle or generation. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`. However, the live Account connect-token path checks the Session Redis replay/result cache before calling fresh entitlement or membership authority, so a replay-cache hit can return the stored success or failure without re-evaluating current entitlement or membership. That cache-hit bypass is current implementation drift; it does not satisfy the target fresh authority and durable replay revalidation contract. `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE` because current consumers do not enforce the producer's lifecycle field. The obsolete implicit membership-writer surface has been removed. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains the non-actionable `JOIN_REQUIRED` outcome. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`. Current private/playtest text `PLAY` also requires the current realm grant, while current connect-token issuance validates pointer/visibility but not the private/playtest grant; target-only connect-token grant validation remains implementation drift. A connect token or returning shortcut must not be treated as authorization proof. Returning members may proceed through the current existing-membership path, but that behavior does not prove the target generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. +The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet runtime-complete; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or end-to-end `JOIN`. The local Account `POST /auth/bootstrap/join` route and `JoinPublicProductionMembership` operation, plus Game Session text `JOIN` dispatch, now exist; PostgreSQL execution, pending-operation recovery, and direct-text/first-party end-to-end proof remain gaps. The required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance also remains unimplemented/unproved. The connect-token and text `PLAY` code contain response-classification branches over membership fields, and Game Session's text `PLAY` has supplied-authority unit coverage; these are not proof of live authority reads. Account's live membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, so a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`, not live `JOIN_REQUIRED`; successful public `PLAY` and composed private/playtest grant admission are not established. Game Session's supplied-authority text `PLAY` branch validates `membershipLifecycleState` and `membershipAuthorityGeneration`; connect-token issuance still lacks its independent current membership baseline/generation reread and replay revalidation. Account's live readers remain fail-closed before data access, so that local validation does not establish a live admission snapshot. The live Account connect-token path checks the Session Redis replay/result cache before fresh entitlement or membership authority, so a cache hit can return stored success or failure without current re-evaluation; this does not satisfy the target fresh-authority replay contract. The obsolete implicit membership-writer surface has been removed. Current connect-token grant validation also remains incomplete. A connect token or returning shortcut must not be treated as authorization proof. The target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. For current authority-reader status, see [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift). --- diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 3a86f01d46..a21b6126e0 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -83,7 +83,7 @@ Reconnection uses two distinct client flows: Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. -Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Current non-public membership/admission denial from the available `membershipExists` and `gameplayAdmissionAllowed` fields remains `WORLD_ACCESS_DENIED`; current text `PLAY` also checks the current realm grant, while current connect-token grant validation remains incomplete. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. +Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Game Session's local non-public response and grant checks are exercised with supplied authority; they do not establish a live Account admission path. Account's membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live membership-read failure maps to `WORLD_ACCESS_DENIED`; composed live grant-backed admission is not proved. Connect-token grant validation also remains incomplete. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) for the owner status. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. A client must not infer current membership or target identity from a stale Redis binding, cached tenant/realm fields, or an old `connectScopeId` after `CONNECT_SCOPE_MISMATCH`. For direct text, Game Session may use only the scope retained from the current authenticated `REALMS` exchange; it must not recreate that scope or authority from a stale selector after transport loss or scope failure. diff --git a/design/product/user-journeys/operators.md b/design/product/user-journeys/operators.md index 972414e97c..63888c4ad2 100644 --- a/design/product/user-journeys/operators.md +++ b/design/product/user-journeys/operators.md @@ -17,7 +17,7 @@ The journeys below keep target operator behavior primary. Current and target bou - **Moderation ingress:** Current report creation uses the physically reachable internal service-to-service `CreateReport` seam, which remains unsupported and unproved. Public/player report ingress is currently unavailable until its caller-bound contract exists. The target report and operator-write contracts are defined in the [Logging & Admin API status](../../architecture/microservices/logging-admin-service/api-contracts.md#implementation-status) and the [Platform Operations tracker](../../project-management/implementation-tracking/platform-operations-and-delivery.md#capability-status). - **Safety and appeals:** The target fixed categories, owner-local enforcement, and bounded appeal case are defined in [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md). Current category persistence, owner commands, player notices, and appeal workflow are not implemented or proved. Account is the target enforcement owner for `platform_access_ban` and separately owns the current `security_locked` foundation plus target `account_security_lock` security/recovery; the separate punitive platform-ban enforcement is not current proof. Logging & Admin owns moderation appeals, while Game Session and Social & Groups remain target enforcement owners for their categories. - **Redis/PostgreSQL recovery:** Current recovery uses the fail-closed operator fallback with affected workloads fenced; the durable controller-backed Redis reset and PostgreSQL restore/reopen sequence is target-only. See [Redis Reset & Recovery](../../architecture/system-architecture-redis-reset-and-recovery.md#current-operator-fallback), [Backup & Disaster Recovery](../../architecture/system-architecture-backup-recovery.md#recovery-controller-continuation), and the [Platform Operations tracker](../../project-management/implementation-tracking/platform-operations-and-delivery.md#capability-status). -- **Grant revocation:** Current Account grant persistence and internal lookup can support a grant-backed admission read, but target expiry, revision/tombstone mutation, tenant-admin and break-glass commands, and active-binding ejection are not implemented or end-to-end proved. The target grant contract is canonical in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract). Current text `PLAY` still consumes the existing membership/admission fields; non-public missing or non-admitting membership remains the current `WORLD_ACCESS_DENIED` path. Target denial of discovery, reconnect, and `PLAY`, together with termination of affected fork bindings, applies after grant expiry/revocation only once that target enforcement is implemented; unrelated account access remains available. Expiry and lifecycle automation remain gaps. +- **Grant revocation:** Current Account grant persistence and internal lookup exist, but the live membership, entitlement, and grant readers fail closed with `FAILED_PRECONDITION` before Account data reads pending typed caller/target binding. Game Session's local text `PLAY` membership and grant branches have supplied-authority unit coverage only; a live membership-read failure maps to `WORLD_ACCESS_DENIED`, and composed grant-backed admission is not proved. Current connect-token grant validation is also incomplete. See [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) for the owning runtime status. Target expiry, revision/tombstone mutation, tenant-admin and break-glass commands, and active-binding ejection are not implemented or end-to-end proved. The target grant contract is canonical in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract). Target denial of discovery, reconnect, and `PLAY`, together with termination of affected fork bindings, applies after grant expiry/revocation only once that target enforcement is implemented; unrelated account access remains available. Expiry and lifecycle automation remain gaps. - **Session termination:** Gameplay takeover, `LOGOUT`, and transport idle-close handling are current; Account control-plane revocation/logout, full expiry convergence, and post-logout replay cleanup remain partial. Target termination distinguishes logout from suspension and closes revoked active sockets so the affected session cannot resume; see the [Player Access and Session tracker](../../project-management/implementation-tracking/player-access-and-session.md#capability-status) and [Session Behavior](../../architecture/system-architecture-session-behavior.md#active-socket-auth-revocation). - **Realm lifecycle and replacement:** Target operator diagnostics distinguish preparation, pre-activation failure, termination, and cleanup completion while retaining the stable playable-state namespace alongside the active runtime. World Management lifecycle state and epoch remain admission authority; Temporal reports coordination progress. A failed preparation is not proof of cleanup, and termination is complete only after every owner in the cleanup attempt's frozen required-owner snapshot at its frozen ownership-registry revision acknowledges cleanup. Current operator readback remains partial; see [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md), and the [Platform Operations tracker](../../project-management/implementation-tracking/platform-operations-and-delivery.md#capability-status). - **Script-transition operations:** Game Session currently persists the pin and exposes convergence reads but does not yet provide the target append-only request-idempotent history or direct history read; the live handoff lacks `scriptPinEpoch` and cannot yet reject same-version work from an older epoch; and Automation does not yet persist and propagate the captured `(pluginActivationEpoch, lifecycleRevision)` pair through every plugin work/status/handoff/retry/replay/recovery surface. These target history/readback and exact-fence capabilities remain unimplemented and unproved. Use [Scripting & Automation: Control Plane Operations](../../architecture/system-architecture-scripting-control-plane-operations.md), [Scripting & Automation: Rollout and Rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md), and the [Scripting & Automation: Observability Contract](../../architecture/system-architecture-scripting-observability-contract.md) for the canonical checks, epoch distinction, notification recovery, and sequencing. Current operator-visible gaps also include stale executor `ONLOAD_RUNNING` work not yet being reclaimed or terminalized; for current stale-readiness incidents, use the admin-authorized read-only patch-status and drain diagnostics, keep the readiness barrier in force, and do not infer reclaim, terminalization, or replay from age. The target Automation readiness-owner fenced path remains unimplemented; see [Stale `onLoad` execution](../../architecture/system-architecture-scripting-operations-cookbook.md#stale-onload-execution) for the current-safe response. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index ab255e122d..a8bf56209e 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -73,13 +73,14 @@ workload_certificate_is_valid() { local certificate="$WORKLOAD_DIR/$workload.crt" local private_key="$WORKLOAD_DIR/$workload.key" local expected_uri="spiffe://firemud/ns/$WORKLOAD_NAMESPACE/sa/$workload" - local subject_alt_names certificate_public_key private_key_public_key + local subject_alt_names uri_sans certificate_public_key private_key_public_key [[ -f "$certificate" && -f "$private_key" ]] || return 1 openssl verify -purpose sslclient -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || return 1 openssl verify -purpose sslserver -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || return 1 subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName 2>/dev/null)" || return 1 - [[ "$subject_alt_names" == *"URI:$expected_uri"* && "$subject_alt_names" == *"DNS:$workload"* ]] || return 1 + uri_sans="$(printf '%s\n' "$subject_alt_names" | grep -oE 'URI:[^,[:space:]]+' || true)" + [[ "$uri_sans" == "URI:$expected_uri" && "$subject_alt_names" == *"DNS:$workload"* ]] || return 1 certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null)" || return 1 private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER 2>/dev/null \ diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index 580a18929d..b91667497c 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -81,13 +81,14 @@ assert_workload_certificate() { local workload="$1" local certificate="$CERT_DIR/local-runtime/$workload/workloads/$workload.crt" local private_key="$CERT_DIR/local-runtime/$workload/workloads/$workload.key" - local subject_alt_names extended_key_usage expected_uri certificate_public_key private_key_public_key + local subject_alt_names uri_sans extended_key_usage expected_uri certificate_public_key private_key_public_key expected_uri="spiffe://firemud/ns/local/sa/$workload" openssl verify -purpose sslclient -CAfile "$CERT_DIR/local-runtime/$workload/ca.crt" "$certificate" >/dev/null openssl verify -purpose sslserver -CAfile "$CERT_DIR/local-runtime/$workload/ca.crt" "$certificate" >/dev/null subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName)" - [[ "$subject_alt_names" == *"URI:$expected_uri"* \ + uri_sans="$(printf '%s\n' "$subject_alt_names" | grep -oE 'URI:[^,[:space:]]+' || true)" + [[ "$uri_sans" == "URI:$expected_uri" \ && "$subject_alt_names" == *"DNS:$workload"* \ && "$subject_alt_names" == *"DNS:$workload.local"* \ && "$subject_alt_names" == *"DNS:$workload.local.svc"* \ @@ -111,6 +112,51 @@ assert_workload_certificate() { } } +assert_invalid_workload_uri_is_reissued() { + local case_name="$1" + local subject_alt_name="$2" + local certificate="$CERT_DIR/workloads/account-service.crt" + local private_key="$CERT_DIR/workloads/account-service.key" + local fixture_dir="$CERT_DIR/workload-uri-$case_name" + local config="$fixture_dir/extensions.cnf" + local request="$fixture_dir/workload.csr" + local before_fingerprint after_fingerprint certificate_public_key private_key_public_key + mkdir -p "$fixture_dir" + openssl req -new -key "$private_key" -subj "/CN=firemud-grpc-account-service" \ + -out "$request" >/dev/null 2>&1 + printf '%s\n' \ + '[leaf]' \ + 'basicConstraints=critical,CA:FALSE' \ + 'keyUsage=critical,digitalSignature,keyEncipherment' \ + 'extendedKeyUsage=serverAuth,clientAuth' \ + "subjectAltName=$subject_alt_name" \ + >"$config" + openssl x509 -req -in "$request" -CA "$CERT_DIR/ca.crt" -CAkey "$CERT_DIR/ca.key" \ + -set_serial "0x$(openssl rand -hex 16)" -out "$certificate" -days 30 -sha256 \ + -extfile "$config" -extensions leaf >/dev/null 2>&1 + + # Keep CA trust, both mTLS usages, and key pairing valid so only the URI identity is wrong. + openssl verify -purpose sslclient -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null + openssl verify -purpose sslserver -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ + | openssl pkey -pubin -outform DER | openssl dgst -sha256)" + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER \ + | openssl dgst -sha256)" + [[ "$certificate_public_key" == "$private_key_public_key" ]] || { + echo "invalid URI fixture does not match the account-service key: $case_name" >&2 + exit 1 + } + + before_fingerprint="$(openssl x509 -in "$certificate" -noout -fingerprint -sha256 | cut -d= -f2)" + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" + after_fingerprint="$(openssl x509 -in "$certificate" -noout -fingerprint -sha256 | cut -d= -f2)" + [[ "$after_fingerprint" != "$before_fingerprint" ]] || { + echo "ensure-dev-certs retained an incorrect workload URI identity: $case_name" >&2 + exit 1 + } + assert_workload_certificate account-service +} + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" runtime_dir="$CERT_DIR/local-runtime" @@ -282,6 +328,15 @@ for workload in account-service game-session-service social-groups-service; do seen_certificates[$fingerprint]=1 done +expected_account_uri="spiffe://firemud/ns/local/sa/account-service" +account_dns_sans='DNS:account-service,DNS:account-service.local,DNS:account-service.local.svc,DNS:account-service.local.svc.cluster.local' +assert_invalid_workload_uri_is_reissued \ + duplicate-uri "URI:$expected_account_uri,URI:spiffe://firemud/ns/local/sa/other,$account_dns_sans" +assert_invalid_workload_uri_is_reissued \ + prefix-uri "URI:xURI:$expected_account_uri,$account_dns_sans" +assert_invalid_workload_uri_is_reissued \ + suffix-uri "URI:${expected_account_uri}-shadow,$account_dns_sans" + # A malformed or stale local leaf is replaced only after it fails closed # identity/issuer/key validation; the generic workload generator remains 0600. printf 'invalid local leaf\n' >"$CERT_DIR/workloads/account-service.crt" diff --git a/services/account-service/src/main/resources/db/migration/V28__account_join_reconciliation.sql b/services/account-service/src/main/resources/db/migration/V28__account_join_reconciliation.sql index 2e45cfb936..bbb47b5ed6 100644 --- a/services/account-service/src/main/resources/db/migration/V28__account_join_reconciliation.sql +++ b/services/account-service/src/main/resources/db/migration/V28__account_join_reconciliation.sql @@ -4,7 +4,8 @@ ALTER TABLE account_join_operations ADD COLUMN reconciliation_attempt_count INTEGER NOT NULL DEFAULT 0, ADD COLUMN last_reconciliation_attempt_at TIMESTAMP, ADD COLUMN last_reconciliation_attempt_reason VARCHAR(128), - ADD COLUMN next_reconciliation_attempt_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ADD COLUMN next_reconciliation_attempt_at TIMESTAMP NOT NULL + DEFAULT pg_catalog.timezone('UTC', CURRENT_TIMESTAMP), ADD CONSTRAINT account_join_reconciliation_attempt_count_check CHECK (reconciliation_attempt_count >= 0), ADD CONSTRAINT account_join_reconciliation_attempt_detail_check diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index dbd67d5256..301b65d3e8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -5,6 +5,8 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; import java.util.List; import java.util.Objects; import java.util.UUID; @@ -22,6 +24,8 @@ 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.VerifiedJoinScope; +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.service.AccountJoinReconciliationService; @@ -38,6 +42,8 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -84,12 +90,54 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private AccountService accountService; @Autowired private AccountJoinReconciliationService reconciliationService; @Autowired private AccountJoinOperationRepository joinOperationRepository; + @Autowired private AccountConnectScopeRepository connectScopeRepository; + @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private LoggingAdminClient loggingAdminClient; @MockitoBean private JavaMailSender mailSender; + @Test + void reconciliationIntentDefaultUsesUtcForDueReadbackInNonUtcDatabaseSession() { + JoinFixture fixture = fixture("active"); + VerifiedJoinScope scope = connectScopeRepository.find(fixture.connectScopeId()).orElseThrow(); + String callerBinding = "direct-text-session:" + fixture.caller().sessionId(); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + transaction.executeWithoutResult( + status -> { + dsl.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); + assertThat( + dsl.resultQuery("SELECT current_setting('TimeZone')").fetchOne(0, String.class)) + .isEqualTo("Pacific/Auckland"); + + LocalDateTime expectedUtcDueTime = + dsl.resultQuery("SELECT pg_catalog.timezone('UTC', CURRENT_TIMESTAMP)") + .fetchOne(0, LocalDateTime.class); + String intentDigest = AccountJoinDigest.intent(fixture.requestId(), scope, callerBinding); + assertThat( + joinOperationRepository.insertIntent( + fixture.requestId(), scope, callerBinding, intentDigest)) + .isTrue(); + + var inserted = joinOperationRepository.find(fixture.requestId()).orElseThrow(); + assertThat(inserted.nextReconciliationAttemptAt()) + .isEqualTo(expectedUtcDueTime.toInstant(ZoneOffset.UTC)); + assertThat( + joinOperationRepository + .findDuePendingReconciliation( + expectedUtcDueTime.toInstant(ZoneOffset.UTC), 20) + .stream() + .map(AccountJoinOperationRepository.JoinOperation::requestId)) + .contains(fixture.requestId()); + + // SET LOCAL and the synthetic intent are both discarded, so no pooled session inherits + // the test timezone and no fixture row remains. + status.setRollbackOnly(); + }); + } + @Test void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplicates() { JoinFixture fixture = fixture("active"); From 86bbde658dc9a8ff163318fc97df5fc1a3bcf044 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 17:29:08 +1300 Subject: [PATCH 37/55] Preserve exact inherited V7 migration bytes --- .../db/migration/V7__audit_gameplay_catalog_revision.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql index f310583acc..9eff6e4d00 100644 --- a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql +++ b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql @@ -6,3 +6,4 @@ ALTER TABLE gameplay_admission_pointer_event CHECK (catalog_revision IS NULL OR catalog_revision > 0), ADD CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); + From 602f426a58a07eb15c254061e0db2fc5ff9c3b0c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 17:33:51 +1300 Subject: [PATCH 38/55] Finalize composed recovery proof and tracker hygiene --- .../player-access-and-session.md | 3 ++- .../service/impl/PaymentGrpcServiceTest.java | 10 ++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) 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 8abe5f1ed8..206909fea0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -54,12 +54,13 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `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); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.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. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. 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. Expired unreferenced connect-scope rows are now swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. The Account-owned worker rechecks only exact positive operation/scope/membership/audit evidence before terminalizing; expired scopes on retained `PENDING` intents remain pending and return retryable `AUTH_UNAVAILABLE`, with no scope reissue or terminalization for expiry, attempt limit, absent, or uncertain evidence. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unclaimed; do not mark ADR 0025 complete. 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.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 use normalized email selectors and return the same neutral HTTP success for known and unknown addresses; unknown addresses create no token or delivery attempt, and known-account post-commit SMTP exceptions are contained and logged. Delivery remains synchronous after commit, so timing resistance and durable asynchronous delivery remain unproved; current tests prove error containment only. 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.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 use normalized email selectors and return the same neutral HTTP success for known and unknown addresses; unknown addresses create no token or delivery attempt, and known-account post-commit SMTP exceptions are contained and logged. Delivery remains synchronous after commit, so timing resistance and durable asynchronous delivery remain unproved; current tests prove error containment only. 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. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Focused repeated-call tests prove the three methods create no `PaymentService` or provider interaction. 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); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.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); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java) | [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); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `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, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission. Account connect-token issuance requires existing membership, but a cached-success replay returns before fresh authority reads; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. | | `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, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. 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 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 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.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) | Current player text handling rejects `LOGOUT` before side effects. This is a fail-closed child boundary while the durable successor is absent; it does not provide seamless logout. Current proof asserts `LOGOUT_UNAVAILABLE` and no side effects. The successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | + The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this work does not complete AA-2.1, first-party `Join & Play`, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject `stateScope` values other than exact `SHARED` or `ISOLATED`. Account-owned public-production JOIN writing and Game Session direct text JOIN dispatch are implemented locally. Expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence may terminalize, and absent or uncertain evidence remains readback-only and pending. The live Account membership/grant/entitlement runtime readers still fail closed before data access, so first-party `Join & Play`, direct text-client end-to-end proof, PostgreSQL lost-acknowledgement/concurrency proof, complete authority, and target admission-pointer fields remain open as recorded above. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java index dfee03de7d..06b34067a4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java @@ -26,10 +26,16 @@ void genericPaymentsRemainClosedForRepeatedRequests() { PaymentGrpcService service = new PaymentGrpcService(meterRegistry); CreatePaymentIntentRequest intent = CreatePaymentIntentRequest.newBuilder() - .setTenantId("1").setAccountId("2").setAmountCents(500).build(); + .setTenantId("1") + .setAccountId("2") + .setAmountCents(500) + .build(); CreateDonationRequest donation = CreateDonationRequest.newBuilder() - .setTenantId("1").setAccountId("2").setAmountCents(100).build(); + .setTenantId("1") + .setAccountId("2") + .setAmountCents(100) + .build(); RefundPaymentRequest refund = RefundPaymentRequest.newBuilder().setTenantId("1").setPaymentId("9").build(); List intents = new ArrayList<>(); From 47dfdf841c10b659e74fcca81169dfed9417e98c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 19:19:18 +1300 Subject: [PATCH 39/55] Split Account recovery behind verified receiver projection evidence --- .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 2 + .../logging-admin-service/api-contracts.md | 6 +- .../logging-admin-service/runtime-and-data.md | 3 +- .../player-access-and-session.md | 2 + ...hared-runtime-contracts-and-persistence.md | 2 + dev-tools/certs/ensure-dev-certs.sh | 99 ++-- .../preview/validate-preview-artifact.py | 2 +- ...d-identity-controller-manifest-contract.sh | 304 +---------- ...ocal-compose-workload-identity-contract.sh | 48 ++ docker/README.md | 2 +- k8s/base/logging-admin-service.yaml | 4 - k8s/helm/firemud/templates/apps.yaml | 6 - .../v1/logging_admin_service.proto | 2 + .../client/LoggingAdminClient.java | 4 + .../AccountAuditOutboxRepository.java | 32 +- .../AccountJoinReconciliationService.java | 18 +- ...37__verified_audit_projection_evidence.sql | 6 + ...ReconciliationPostgresIntegrationTest.java | 40 ++ .../AccountRepositoryIntegrationTest.java | 49 ++ .../client/LoggingAdminClientTest.java | 111 ++++ .../AccountJoinReconciliationServiceTest.java | 86 ++- .../AccountAuditGrpcAuthConfiguration.java | 37 -- .../dto/AccountAuditReceiptDto.java | 13 - .../dto/AccountAuditReceiptOutcome.java | 8 - .../dto/AccountAuditReceiptStatus.java | 7 - .../loggingadmin/dto/AccountAuditScope.java | 16 - .../dto/CreateLogEventRequest.java | 24 +- .../entity/AccountAuditReceipt.java | 31 -- .../AccountAuditReceiptInsertResult.java | 3 - .../AccountAuditReceiptRepository.java | 131 ----- .../repository/LogEventRepository.java | 15 +- .../AuditReceiptNotFoundException.java | 7 - .../AuditStorageUnavailableException.java | 7 - .../loggingadmin/service/LogEventService.java | 6 +- .../service/impl/LogEventServiceImpl.java | 213 +------- .../service/impl/LoggingAdminGrpcService.java | 272 +--------- .../migration/V2__account_audit_receipts.sql | 47 -- .../V3__account_audit_receipt_projection.sql | 68 --- ...oggingAdminApplicationIntegrationTest.java | 489 ------------------ .../service/impl/LogEventServiceImplTest.java | 234 --------- .../impl/LoggingAdminGrpcServiceAuthTest.java | 369 ++----------- 42 files changed, 564 insertions(+), 2263 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V37__verified_audit_projection_evidence.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java delete mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java delete mode 100644 services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql delete mode 100644 services/logging-admin-service/src/main/resources/db/migration/V3__account_audit_receipt_projection.sql delete mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index df07309099..0da47de9cf 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,6 +54,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +JOIN readback status: the bounded Account worker may terminalize only after the exact operation, scope, membership, immutable audit envelope, and version-1 COMMITTED receiver receipt/projection identity are all positively proved from the same scoped outbox row. Missing, legacy-unversioned, unsupported-version, or minimized delivery evidence leaves the intent pending with retry diagnostics; expiry and attempt limits do not authorize a JOIN replay or terminalization. + Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 410726a583..f9e2168ea9 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +JOIN reconciliation also requires explicit version-1 COMMITTED receipt/projection evidence and nonblank receiver identities on the exact locked JOIN outbox row. A pending JOIN whose retained COMMITTED outbox row lacks that marker remains pending with retry diagnostics; the historical row is not upgraded or inferred as current projection proof. Deploying the receiver child alone does not promote these historical rows: current exact receipt/projection readback and a guarded evidence-recording path must be proved before they can enable recovery. An unavailable, minimized, or unsupported receiver response cannot enable recovery. + Credential-bearing gameplay authentication accepts the account's configured password or verified-email OTP modes. The gameplay `Authenticate` and challenge protos are tenant-less: authentication establishes global Account identity without requiring membership, and Game Session retains any bootstrap tenant only as local routing context. The current private delegation token still uses the legacy account-scoped session record; this is implementation status, not the target token-registry contract. When a tenant has zero or multiple subscription rows, the entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field). Focused proof covers zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery; it proves only the cardinality/retry guard. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the full entitlement snapshot/freshness contract remain open, including committed status, `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 48233cacc3..06e9755e84 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -8,9 +8,7 @@ The canonical Account-to-Logging & Admin audit ingress is the existing `logging_ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenantId` only for `tenant` scope and never for `platform` scope, stable `auditEventId` generated and persisted by Account, `producerService`, `eventType`, producer `occurredAt`, positive `schemaVersion`, exact UTF-8 `payload`, `payloadDigestVersion` exactly `1` until a later canonical digest-version registry is accepted, and `payloadDigest`. Global registration, `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity events use `platform` scope with no `tenantId`; tenant profile and JOIN events use `tenant` scope with the exact committed `tenantId`. Unsupported digest versions fail before deduplication or persistence. `producerService` is derived from the authenticated Account workload identity and a mismatching request value is rejected. An upstream producer domain-event digest, when present inside `payload`, remains opaque payload evidence and is distinct from the receiver's `payloadDigest`. `payloadDigest` is `sha256:` followed by 64 lowercase hexadecimal characters over the exact UTF-8 payload bytes under `payloadDigestVersion=1`; no JSON reserialization or alternate canonicalization is permitted. Retry equivalence is the complete immutable `(scope, tenantId-if-tenant, auditEventId, producerService, eventType, occurredAt, schemaVersion, payloadDigestVersion, payloadDigest, exact payload bytes)` tuple: while exact payload bytes remain retained, an exact match returns the original receipt, while any changed field or payload bytes fails closed as `IDEMPOTENCY_CONFLICT`. After the safe watermark permits payload minimization, the retained identity and metadata may still detect a changed non-payload field, but the receiver must not claim exact payload equality or replay; a matching late request is a terminal non-replayable result. Timeout, transport failure, or an ambiguous response is not success; the producer retries or reconciles with the same identity and digest and never mints a replacement event. -Each accepted Account audit request commits one `log_events` audit projection in the same PostgreSQL transaction as its durable receipt. `logEventId` is the projection's `log_events.id`, distinct from `receiptId` and the receipt row's database key. The projection is deliberately a bounded identity summary: `type` is the fixed value `ACCOUNT_AUDIT`, `message` is `Account audit event` followed by one ASCII space and `auditEventId`, and `timestamp`, `scope`, and `tenantId` come from the envelope. `account_id` remains unset because the envelope has no typed account-principal field. The exact payload and `eventType` remain in the receipt and are not copied into this projection, so payload minimization does not leave a second permanent payload copy. Platform projections retain `scope=platform` and `tenantId=NULL`; tenant projections retain `scope=tenant` and the exact positive `tenantId`. `QueryLogs` remains tenant-only and excludes platform rows; it can locate a projected audit event by its `auditEventId`, but this contract does not define or imply a platform query route. A scope-qualified `(scope, tenantId-or-zero, auditEventId)` uniqueness boundary ensures an exact retry returns the original receipt and projection IDs, while a changed tuple conflicts without another projection. - -`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. **Current local implementation:** the Account audit request/response schema, Account workload check, exact payload digest validation, atomic scope-aware log projection and durable receipt insert/deduplication, bounded receipt readback, and accepted/duplicate/conflict/minimized outcomes are implemented locally. Account registration and JOIN now produce owner-local outbox entries; Account's delivery client checks returned receipt evidence before marking delivery complete. Focused local unit coverage exists, but PostgreSQL runtime proof and direct text-client-to-Logging end-to-end proof are not claimed. The target contract remains authoritative for full retention/readback horizons and any unresolved runtime edge cases. +`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). @@ -26,7 +24,7 @@ Routine rollback is expected to leave ordinary gameplay available while scoped A ## Implementation Status -- Account-to-Logging audit delivery now uses the existing typed `CreateLogEvent` RPC and `ReadLogEventReceipt` readback, not the legacy generic writer. Logging & Admin validates the exact Account mTLS workload identity and receipt envelope, atomically persists the bounded `log_events` projection with a durable typed receipt, and returns accepted/duplicate/conflict/minimized outcomes; Account retains the same event identity for retries and only marks delivery after matching receipt evidence. Missing receipts and dependency failures remain canonical `NOT_FOUND`/`UNAVAILABLE` responses. Focused unit proof is authored, but PostgreSQL migration/transaction runtime proof and direct text-client-to-Logging end-to-end proof are not claimed. The full receiver retention horizon, safe-watermark, hold, and payload-minimization lifecycle remains governed by the owner contract above and [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). +- Account-to-Logging audit delivery remains partial in this reconstruction: typed `CreateLogEvent` returns gRPC `UNIMPLEMENTED` and never invokes the legacy generic `log_events` writer. The typed receipt receiver implementation and focused proof are owned by [#2848](https://github.com/benhook1013/FireMUD/pull/2848) and are not integrated in this revision; the target contract above is unchanged. Account's post-commit best-effort delivery path does not establish receiver durability or receipt confirmation. - Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live. The current-pointer list forwards only the caller's authorized tenant scopes; an empty owner request remains reserved for global platform administrators and moderators. Each current pointer in the selected scope requires exact latest-audit identity/catalog evidence, and unavailable authority in that scope returns `503`. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. - Availability vocabulary is explicit: **implemented-but-externally-gated** means an executable public controller/owner path exists but the shared mutation gate is incomplete; **target-only absent** means no executable public route exists. Admission-pointer mutation, version-upgrade preparation, and prepared cutover use the latter classification at public HTTP ingress even though internal preparation/cutover implementation remains. Quota-override ingress is also target-only absent. No generic tick-remediation payload or reserved `remediate` route is part of the target; each future recovery operation requires a named typed contract implemented by its authoritative workflow owner. - No forwarded owner mutation is currently supported as a live Logging & Admin capability until its minimum schema/authorization gate and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) are implemented and proved. The service-local `POST /moderation/actions` endpoint and `ApplyModerationAction` gRPC path now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They remain unsupported, nonconformant implementation drift and must not be wired or called as available mutations; separate fixed-category policy/audit evidence and owner enforcement state are absent, and they are not Gateway-forwarded or supported at external ingress. In the target local workflow, once its applicable schema/authorization and local durable intent/audit requirements are implemented, Logging & Admin records durable intent/case/audit evidence and redeems its one Account reference exactly once; it never forwards that reference or performs owner enforcement. A future typed owner-enforcement command uses a separately issued reference redeemed by its receiving owner. Game Session and Social & Groups synchronously consume the live `EvaluateModerationPolicy` read at the `GAMEPLAY_ADMISSION` and `CHAT_SEND` enforcement boundaries, but that evaluation does not make the legacy action route live. Fixed-category owner commands, monotonic owner state, bounded appeals, and broader policy coverage are not implemented. Existing Game Session `/sessions*` lifecycle routes are current owner-local hooks, not a complete external Logging & Admin route family. Separate current read and investigation surfaces include the PostgreSQL-backed log query, saga reads, metrics, and owner/control-plane reads; profile-aware indexed or console/journal query integration and embedded dashboard endpoints remain target-only and unimplemented. diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index 5f0c6de3d8..f58464631b 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -29,7 +29,6 @@ Target external session-lifecycle operator requests enter through Gateway and Lo The current shipped scope is narrower than this target contract: -- The current branch's forward Logging V3 adds the Account audit projection and links retained V2 receipts without rewriting V2. Exact audit projections require a scope-qualified tenant key matching `tenantId` (or zero for platform scope); older ordinary tenant `log_events` writers may omit that new key and leave its compatibility value at zero, while tenant queries continue to use `tenantId`. The V2-to-V3 retained-row migration test compiles but has not executed locally without Docker, so this is not retained-database activation proof. - The service exposes core admin investigation reads, saga inspection of Logging & Admin-local rows only, coordination-health reads, and a narrow log query whose current implementation reads only the service-owned PostgreSQL `log_events` table for an exact tenant plus case-insensitive message containment. Saga inspection does not aggregate adopter-local state; target cross-owner visibility requires owner read APIs plus a bounded aggregation/read model and must distinguish an unknown or unavailable adopter from an empty result. Moderation policy-input and report-persistence paths are only unsupported legacy transport/internal seams that hard fail closed or remain authorization-unproved; they are not exposed current capabilities. The service does not implement the target profile-aware indexed or console/journal query integrations, Kibana/Grafana clients, embedded dashboards, separate admin UI, or the complete target control-plane workflow for every recovery, regional, or aggregate operation. - The moderation policy-input and audit persistence mutation has present legacy transport stubs through `POST /moderation/actions` and the internal `ApplyModerationAction` gRPC ingress; after narrow tenant/admin checks they hard fail closed with HTTP `503 Service Unavailable` or an application-level gRPC `UNAVAILABLE` error, without dispatch or persistence. They are unsupported, nonconformant implementation drift and must not be wired or called as available mutations. They do not provide the target fixed-category policy-input/audit record or Account, Game Session, or Social & Groups enforcement state. Current execution performs no Account authorization-reference issuance or redemption, owner forwarding, or owner enforcement. Once its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin receiving-boundary validation/redemption are complete, Logging & Admin redeems the separate intent-persistence reference exactly once at its receiving boundary; that reference is never forwarded or reused and the path does not require owner-side authorization-reference redemption or enforcement. Any future owner-enforcement command uses a separately issued reference redeemed once by its receiving owner. The separate `EvaluateModerationPolicy` compatibility read remains live at the owner enforcement boundaries and carries no mutation authorization reference. Public administrative report persistence at `POST /admin/reports` is unavailable: the HTTP controller and Gateway route were removed because canonical authorization and live reference validation are not implemented. The internal `CreateReport` gRPC ingress is not public; its interim receiver guard requires an internal-service JWT naming `social-groups-service`, which the Social & Groups client emits, while certificate-derived exact workload/method authorization remains unproved. The reserved player-bootstrap `POST /reports` submission route is separate and also unavailable until its caller-bound subject and live tenant-membership checks exist. - Admission-pointer reads, audit, and prepared-upgrade proof reads are implemented and live. Internal admission-pointer mutation, version-upgrade preparation, and prepared-cutover owner paths have implementation-participating surfaces, but the current pointer writer is read-then-write/nonconformant; the target atomic open/close CAS and prepared cutover remain unimplemented and externally unavailable behind internal trust boundaries, with public HTTP/Gateway write support unavailable and no current UI control. Target-only absent is reserved for operations with no executable owner path at all, such as quota-override mutations or future named typed recovery actions whose owner contracts do not yet exist. @@ -114,7 +113,7 @@ For plugin operations, Automation remains the activation/lifecycle owner and Gam ## Data Model -- `log_events` is the current service-owned PostgreSQL domain table and also holds the Account audit projection defined in [Account Audit Ingress and Receipt](./api-contracts.md#account-audit-ingress-and-receipt). Audit projections retain explicit `platform` or `tenant` scope; platform rows have no `tenantId` and are excluded from tenant queries. `LogQueryServiceImpl` queries tenant-scope rows by exact `tenantId` and case-insensitive message containment and returns only stored messages. No current implementation mirrors this table into Elasticsearch or proves the profile-aware emitter-to-query path; selected-profile indexed, compatible-backend, or console/journal querying remains target-state under [Logging & Monitoring](../../system-architecture-logging-monitoring.md#log-pipeline-queryability-contract). +- `log_events` is the current service-owned PostgreSQL domain table. `LogQueryServiceImpl` queries it by exact `tenantId` and case-insensitive message containment and returns only stored messages. No current implementation mirrors this table into Elasticsearch or proves the profile-aware emitter-to-query path; selected-profile indexed, compatible-backend, or console/journal querying remains target-state under [Logging & Monitoring](../../system-architecture-logging-monitoring.md#log-pipeline-queryability-contract). - `moderation_actions` is the target durable record for accepted moderation policy intent and audit evidence, with the fixed category, normalized explicit scope, actor/case/source request, safe notice/reason, local intent-reference redemption outcome, separate owner command/result linkage when a later enforcement command exists, and the idempotency identity, digest, and timestamps. A linked owner-result revision is recorded only when that result supplies it; the local policy-intent commit never synthesizes owner revision or enforcement epoch. Raw authorization references are never persisted. The legacy `POST /moderation/actions` and `ApplyModerationAction` transport stubs now hard fail closed after narrow checks without persisting their generic legacy row; they are unsupported/nonconformant and not target fixed-category proof. Owner restriction tables and owner-command redemption are separate; Logging & Admin does not mutate them. - `moderation_appeal_cases` and bounded `moderation_appeal_evidence_refs` are target Logging & Admin records for the `SUBMITTED -> UNDER_REVIEW -> DECIDED` lifecycle, exact appealed owner revision/digest, jurisdiction, eligibility policy, safe submission/decision, bounded evidence references, retention/legal-hold/export state, and resulting owner command identity. No complete appeal table or workflow is currently implemented. - `player_reports` is the target durable store for abuse and bug reports accepted through the report-persistence seam, including tenant scope in its `tenant_id` column. Current report persistence is unavailable: both the internal `CreateReport` ingress and the service-layer mutation fail closed before any repository save, and public administrative and target caller-bound external/player submission remain unavailable. 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 206909fea0..0c126321cc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The Account JOIN worker's positive audit evidence now includes an explicit version-1 COMMITTED receipt/projection marker and nonblank receiver identities from the locked scoped outbox row. Retained legacy IDs without that marker remain unresolved; this front stays unavailable until the receiver child supplies the matching versioned capability and proof. + Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, the owner-local Account audit outbox and typed Logging & Admin receipt/readback, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct text `JOIN` dispatch exist locally, but the Gateway still blocks external route exposure and first-party `Join & Play` remains unavailable. Account's bounded JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`, and only exact positive prior-commit evidence can terminalize; absent or uncertain evidence remains pending with capped diagnostics/backoff, never because of expiry or attempt limit. PostgreSQL lost-acknowledgement/concurrency, direct text-client-to-Logging end-to-end, and connect-token membership-version/authority-generation baseline proof remain open. Current `PLAY` and connect-token issuance remain partial: local `PLAY` validates lifecycle/version/generation on supplied-authority branches, but live Account runtime readers fail closed before data access. Account membership and realm-grant authorities remain separately owned. Namespace-aware binding, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. 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. 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 a04e379a4d..ec98994b16 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 @@ -119,6 +119,8 @@ The [gRPC outcome and transport classification](../../architecture/system-archit ### Audit, Moderation, and Authority Boundaries +Account's readback-only JOIN recovery requires an explicit version-1 COMMITTED receipt/projection marker plus nonblank receiver identities from the exact scoped outbox row. The Account front stays closed until the Logging receiver child supplies and proves that capability. Historical COMMITTED rows without the marker remain unverified even after receiver deployment; exact current readback and guarded evidence recording are a separate retained-data activation gate, not an inferred upgrade. + Logging & Admin exposes dedicated non-destructive `CreateLogEvent` ingress. Global registration and explicit JOIN now append Account-owned audit outbox entries in their local transactions, and Logging & Admin retains receipt/deduplication evidence; delivery and readback are still partial until the audit projection, uncertain-commit reconciliation, and PostgreSQL/end-to-end proof are complete. The normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt); see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for the producer's current implementation, proof, and gap status. Account logging for payment uses the existing RPC and `LogEvent` persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. Focused tests prove the current log-event behavior and the absence of destructive account/session effects. Current status only: Logging & Admin exposes the non-destructive `EvaluateModerationPolicy` read and a gated/unavailable moderation-action seam; current focused proof is partial and covers bounded read, denied, and validation paths only. It does not cover target mutation or appeal workflows, or focused `CHAT_SEND` stale/unavailable dependency and owner-read failure cases. The remaining implementation and proof gaps are tracked against [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md) and [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md). diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index a5feaf2096..517de72401 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -286,54 +286,57 @@ done # Mount only runtime material. Protected callers receive their own leaf, not # the other protected services' private keys. No projection includes ca.key. -[[ ! -L "$RUNTIME_DIR" ]] || { - echo "refusing symlink as local Compose runtime projection: $RUNTIME_DIR" >&2 - exit 1 -} -mkdir -p "$RUNTIME_DIR" -chmod 755 "$RUNTIME_DIR" runtime_files=(ca.crt client.crt client.key server.crt server.key dev-ca.pem dev-cert.pem dev-key.pem) runtime_profiles=(default "${workloads[@]}") -while IFS= read -r -d '' existing_path; do - [[ ! -L "$existing_path" ]] || { - echo "refusing symlink in local Compose runtime projection: $existing_path" >&2 - exit 1 - } - profile_name="${existing_path##*/}" - approved=false - for profile in "${runtime_profiles[@]}"; do - if [[ "$profile_name" == "$profile" && -d "$existing_path" ]]; then - approved=true - break - fi - done - [[ "$approved" == "true" ]] || { - echo "refusing unapproved entry in local Compose runtime projection: $profile_name" >&2 +if [[ -e "$RUNTIME_DIR" || -L "$RUNTIME_DIR" ]]; then + [[ ! -L "$RUNTIME_DIR" && -d "$RUNTIME_DIR" ]] || { + echo "refusing symlink or non-directory local Compose runtime projection: $RUNTIME_DIR" >&2 exit 1 } -done < <(find "$RUNTIME_DIR" -mindepth 1 -maxdepth 1 -print0) - -for workload in "${workloads[@]}"; do - profile_dir="$RUNTIME_DIR/$workload" - [[ ! -L "$profile_dir" ]] || { - echo "refusing symlink in local Compose runtime projection: $profile_dir" >&2 - exit 1 - } - mkdir -p "$profile_dir/workloads" -done + while IFS= read -r -d '' existing_path; do + [[ ! -L "$existing_path" ]] || { + echo "refusing symlink in local Compose runtime projection: $existing_path" >&2 + exit 1 + } + profile_name="${existing_path##*/}" + approved=false + for profile in "${runtime_profiles[@]}"; do + if [[ "$profile_name" == "$profile" && -d "$existing_path" ]]; then + approved=true + break + fi + done + [[ "$approved" == "true" ]] || { + echo "refusing unapproved entry in local Compose runtime projection: $profile_name" >&2 + exit 1 + } + done < <(find "$RUNTIME_DIR" -mindepth 1 -maxdepth 1 -print0) +fi +# Preflight every existing destination across all profiles before any +# projection directory chmod or file copy can mutate an aliased inode. for profile in "${runtime_profiles[@]}"; do profile_dir="$RUNTIME_DIR/$profile" - [[ ! -L "$profile_dir" && ! -L "$profile_dir/workloads" ]] || { + [[ ! -L "$profile_dir" ]] || { echo "refusing symlink in local Compose runtime projection: $profile_dir" >&2 exit 1 } - mkdir -p "$profile_dir" - chmod 755 "$profile_dir" + if [[ -e "$profile_dir" && ! -d "$profile_dir" ]]; then + echo "refusing unapproved entry in local Compose runtime projection: $profile_dir" >&2 + exit 1 + fi + [[ -d "$profile_dir" ]] || continue + expected_profile_files=(ca.crt client.crt client.key server.crt server.key dev-ca.pem dev-cert.pem dev-key.pem) if [[ "$profile" != "default" ]]; then - mkdir -p "$profile_dir/workloads" - chmod 755 "$profile_dir/workloads" + if [[ -L "$profile_dir/workloads" ]]; then + echo "refusing symlink in local Compose runtime projection: $profile_dir/workloads" >&2 + exit 1 + fi + if [[ -e "$profile_dir/workloads" && ! -d "$profile_dir/workloads" ]]; then + echo "refusing unapproved file in local Compose runtime projection: $profile/workloads" >&2 + exit 1 + fi expected_profile_files+=(workloads "workloads/$profile.crt" "workloads/$profile.key") fi @@ -358,8 +361,31 @@ for profile in "${runtime_profiles[@]}"; do echo "refusing unapproved file in local Compose runtime projection: $profile/$relative_path" >&2 exit 1 } + if [[ -f "$existing_path" ]]; then + link_count="$(stat -c '%h' -- "$existing_path")" + if ((link_count > 1)); then + echo "refusing hard-linked file in local Compose runtime projection: $existing_path" >&2 + exit 1 + fi + fi done < <(find "$profile_dir" -mindepth 1 -print0) +done +# The complete existing projection passed preflight, so directory setup and +# copy/chmod operations can now proceed without changing unrelated hard links. +mkdir -p "$RUNTIME_DIR" +chmod 755 "$RUNTIME_DIR" +for workload in "${workloads[@]}"; do + mkdir -p "$RUNTIME_DIR/$workload/workloads" +done + +for profile in "${runtime_profiles[@]}"; do + profile_dir="$RUNTIME_DIR/$profile" + mkdir -p "$profile_dir" + chmod 755 "$profile_dir" + if [[ "$profile" != "default" ]]; then + chmod 755 "$profile_dir/workloads" + fi for file in "${runtime_files[@]}"; do [[ -f "$CERT_DIR/$file" ]] || { echo "missing runtime certificate material: $CERT_DIR/$file" >&2 @@ -370,7 +396,6 @@ for profile in "${runtime_profiles[@]}"; do if [[ "$profile" != "default" ]]; then cp "$WORKLOAD_DIR/$profile.crt" "$profile_dir/workloads/$profile.crt" cp "$WORKLOAD_DIR/$profile.key" "$profile_dir/workloads/$profile.key" - chmod 755 "$profile_dir/workloads" chmod 644 "$profile_dir/workloads/$profile.crt" "$profile_dir/workloads/$profile.key" fi chmod 644 "$profile_dir"/*.crt "$profile_dir"/*.key "$profile_dir"/*.pem diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 3045ce83b9..d38f4648e9 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -1565,7 +1565,7 @@ def validate_service_consumers( fail(f"Deployment/{service} has an unexpected container layout") container = containers[0] - if service in DISTINCT_GRPC_WORKLOADS or service == "logging-admin-service": + if service in DISTINCT_GRPC_WORKLOADS: workload_namespace_entries = [ entry for entry in container.get("env", []) diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index feaeb973d7..804ce78ee1 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -3968,27 +3968,17 @@ def service_consumer_documents(): }, ] elif service != "spring-cloud-gateway": - container["env"] = [] - if service == "logging-admin-service": - container["env"].append( - { - "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", - "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, - } - ) - container["env"].extend( - [ - { - "name": "FIREMUD_GRPC_CERT_CHAIN_PATH", - "value": "/tls/client.crt", - }, - { - "name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", - "value": "/tls/client.key", - }, - {"name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/tls/ca.crt"}, - ] - ) + container["env"] = [ + { + "name": "FIREMUD_GRPC_CERT_CHAIN_PATH", + "value": "/tls/client.crt", + }, + { + "name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", + "value": "/tls/client.key", + }, + {"name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/tls/ca.crt"}, + ] if service == "spring-cloud-gateway": container["env"] = validator._expected_gateway_container_env("pr-42") container["envFrom"] = copy.deepcopy(validator.EXPECTED_GATEWAY_ENV_FROM) @@ -4013,68 +4003,6 @@ def service_consumer_documents(): valid_consumers = service_consumer_documents() validator.validate_service_consumers(valid_consumers, "pr-42", "standalone", "public") -logging_namespace_failure = ( - "Deployment/logging-admin-service must bind " - "FIREMUD_GRPC_WORKLOAD_NAMESPACE to metadata.namespace" -) -missing_logging_namespace = copy.deepcopy(valid_consumers) -logging_deployment = next( - document - for document in missing_logging_namespace - if document["metadata"]["name"] == "logging-admin-service" -) -logging_container = logging_deployment["spec"]["template"]["spec"]["containers"][0] -logging_container["env"] = [ - entry - for entry in logging_container["env"] - if entry.get("name") != "FIREMUD_GRPC_WORKLOAD_NAMESPACE" -] -assert_rejected( - lambda: validator.validate_service_consumers( - missing_logging_namespace, "pr-42", "standalone", "public" - ), - logging_namespace_failure, -) - -duplicate_logging_namespace = copy.deepcopy(valid_consumers) -logging_deployment = next( - document - for document in duplicate_logging_namespace - if document["metadata"]["name"] == "logging-admin-service" -) -logging_container = logging_deployment["spec"]["template"]["spec"]["containers"][0] -logging_namespace = next( - entry - for entry in logging_container["env"] - if entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" -) -logging_container["env"].append(copy.deepcopy(logging_namespace)) -assert_rejected( - lambda: validator.validate_service_consumers( - duplicate_logging_namespace, "pr-42", "standalone", "public" - ), - logging_namespace_failure, -) - -wrong_logging_namespace = copy.deepcopy(valid_consumers) -logging_deployment = next( - document - for document in wrong_logging_namespace - if document["metadata"]["name"] == "logging-admin-service" -) -logging_container = logging_deployment["spec"]["template"]["spec"]["containers"][0] -next( - entry - for entry in logging_container["env"] - if entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" -)["valueFrom"] = {"fieldRef": {"fieldPath": "metadata.name"}} -assert_rejected( - lambda: validator.validate_service_consumers( - wrong_logging_namespace, "pr-42", "standalone", "public" - ), - logging_namespace_failure, -) - missing_publication_trust_mount = copy.deepcopy(valid_consumers) publication_deployment = next( document @@ -4755,39 +4683,11 @@ def env_map(container, service): entries = container.get("env") if not isinstance(entries, list): fail(f"Deployment/{service} container has no env list") - result = {} - for entry in entries: - if not isinstance(entry, dict) or not entry.get("name"): - continue - name = entry["name"] - if name in result: - fail(f"Deployment/{service} has duplicate env name {name}") - result[name] = entry - return result - - -synthetic_duplicate_env_rejections = 0 -duplicate_namespace_env = { - "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", - "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, -} -try: - env_map( - {"env": [duplicate_namespace_env, duplicate_namespace_env]}, - "synthetic duplicate fixture", - ) -except SystemExit as error: - if "duplicate env name FIREMUD_GRPC_WORKLOAD_NAMESPACE" not in str(error): - raise - synthetic_duplicate_env_rejections += 1 -else: - fail("synthetic duplicate env fixture was not rejected") -if synthetic_duplicate_env_rejections != 1: - fail( - "synthetic duplicate env proof expected one rejection, found " - f"{synthetic_duplicate_env_rejections}" - ) -print(f"synthetic duplicate env fixtures rejected: {synthetic_duplicate_env_rejections}") + return { + entry.get("name"): entry + for entry in entries + if isinstance(entry, dict) and entry.get("name") + } def assert_paths_and_mount(container, service, cert_path, key_path, ca_path): @@ -4812,34 +4712,6 @@ def assert_paths_and_mount(container, service, cert_path, key_path, ca_path): fail(f"Deployment/{service} grpc-tls must mount read-only at /tls") -def allows_shared_namespace_identity(service, env): - namespace_identity = env.get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") - expected_namespace_identity = { - "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", - "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, - } - if service == "logging-admin-service": - return namespace_identity == expected_namespace_identity - return namespace_identity is None - - -# The exact downward-API namespace identity is valid only for Logging & Admin -# among shared transports; every other shared service must reject this shape. -negative_shared_namespace_fixture = { - "FIREMUD_GRPC_WORKLOAD_NAMESPACE": { - "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", - "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, - } -} -for service in shared_services: - if service != "logging-admin-service" and allows_shared_namespace_identity( - service, negative_shared_namespace_fixture - ): - fail( - f"shared namespace identity fixture unexpectedly accepted for {service}" - ) - - def assert_distinct_workload_service(service, deployment_map, source): deployment = deployment_for(service, deployment_map) container, pod_spec = workload_container(deployment, service) @@ -4923,14 +4795,7 @@ for service in shared_services: assert_paths_and_mount( container, service, "/tls/client.crt", "/tls/client.key", "/tls/ca.crt" ) - env = env_map(container, service) - if service == "logging-admin-service": - if not allows_shared_namespace_identity(service, env): - fail( - f"Deployment/{service} must derive FIREMUD_GRPC_WORKLOAD_NAMESPACE " - "from metadata.namespace" - ) - elif "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in env: + if "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in env_map(container, service): fail( f"Deployment/{service} shared transport unexpectedly declares " "FIREMUD_GRPC_WORKLOAD_NAMESPACE" @@ -4971,70 +4836,29 @@ for service in ( fail(f"Kustomize base Deployment/{service} must use non-rolling Recreate strategy") for service in distinct_workload_services: assert_distinct_workload_service(service, base_deployments, "Kustomize base") - -base_logging_admin = deployment_for("logging-admin-service", base_deployments) -base_logging_admin_container, base_logging_admin_pod = workload_container( - base_logging_admin, "logging-admin-service" -) -assert_paths_and_mount( - base_logging_admin_container, - "logging-admin-service", - "/tls/client.crt", - "/tls/client.key", - "/tls/ca.crt", -) -base_logging_admin_namespace = env_map( - base_logging_admin_container, "logging-admin-service" -).get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") -if base_logging_admin_namespace != { - "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", - "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, -}: - fail( - "Kustomize base Deployment/logging-admin-service must derive " - "FIREMUD_GRPC_WORKLOAD_NAMESPACE from metadata.namespace, " - f"found {base_logging_admin_namespace!r}" - ) -base_logging_admin_grpc_volume = named_entry( - base_logging_admin_pod.get("volumes"), - "grpc-tls", - "Kustomize base Deployment/logging-admin-service volumes", -) -if base_logging_admin_grpc_volume.get("secret", {}).get("secretName") != "firemud-grpc-tls": - fail( - "Kustomize base Deployment/logging-admin-service shared grpc-tls must use " - "firemud-grpc-tls" - ) PY -for certificate_identity_mode in standalone hosted-controller; do - for logging_spring_profile in true false; do - python3 - "$resolved_values" "$namespace_gate_values" "$certificate_identity_mode" "$logging_spring_profile" <<'PY' +python3 - "$resolved_values" "$namespace_gate_values" <<'PY' import sys from pathlib import Path import yaml values = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) -certificate_identity_mode = sys.argv[3] -logging_spring_profile = sys.argv[4] == "true" -values["previewStack"]["certificateIdentity"]["mode"] = certificate_identity_mode services = values["previewStack"]["services"] by_name = {service["name"]: service for service in services} -by_name["logging-admin-service"]["springProfile"] = logging_spring_profile -by_name["logging-admin-service"]["mountGrpcTls"] = True by_name["game-design-service"]["springProfile"] = False by_name["game-design-service"]["mountGrpcTls"] = True by_name["world-management-service"]["mountGrpcTls"] = False Path(sys.argv[2]).write_text(yaml.safe_dump(values, sort_keys=False), encoding="utf-8") PY - if ! helm template "ns-gate-${certificate_identity_mode}-${logging_spring_profile}" "$ROOT_DIR/k8s/helm/firemud" \ - -f "$namespace_gate_values" \ - >"$namespace_gate_rendered"; then - fail "Helm chart render failed for gRPC namespace gate fixture (${certificate_identity_mode}, springProfile=${logging_spring_profile})" - fi - python3 - "$namespace_gate_rendered" "$certificate_identity_mode" "$logging_spring_profile" <<'PY' +if ! helm template hosted-identity-namespace-gates "$ROOT_DIR/k8s/helm/firemud" \ + -f "$namespace_gate_values" \ + >"$namespace_gate_rendered"; then + fail "Helm chart render failed for gRPC namespace gate fixture" +fi +python3 - "$namespace_gate_rendered" <<'PY' import sys from pathlib import Path @@ -5050,8 +4874,6 @@ deployments = { for document in yaml.safe_load_all(Path(sys.argv[1]).read_text(encoding="utf-8")) if isinstance(document, dict) and document.get("kind") == "Deployment" } -certificate_identity_mode = sys.argv[2] -logging_spring_profile = sys.argv[3] == "true" def env_map(service): @@ -5062,80 +4884,8 @@ def env_map(service): container = next((item for item in containers if item.get("name") == service), None) if container is None: fail(f"container/{service} is missing") - entries = container.get("env") - if not isinstance(entries, list): - fail(f"container/{service} has no env list") - result = {} - for entry in entries: - if not isinstance(entry, dict) or not entry.get("name"): - continue - name = entry["name"] - if name in result: - fail(f"Deployment/{service} has duplicate env name {name}") - result[name] = entry - return result - - -logging_env = env_map("logging-admin-service") -logging_deployment = deployments["logging-admin-service"] -logging_container = next( - item - for item in logging_deployment["spec"]["template"]["spec"]["containers"] - if item.get("name") == "logging-admin-service" -) -namespace_entries = [ - entry - for entry in logging_container["env"] - if isinstance(entry, dict) - and entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" -] -if len(namespace_entries) != 1: - fail( - "logging-admin-service must render exactly one " - "FIREMUD_GRPC_WORKLOAD_NAMESPACE, found " - f"{len(namespace_entries)}" - ) -namespace = logging_env.get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") -if namespace != { - "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", - "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, -}: - fail(f"logging-admin-service must derive namespace from metadata.namespace, found {namespace!r}") -if logging_spring_profile: - if logging_env.get("SPRING_PROFILES_ACTIVE") != { - "name": "SPRING_PROFILES_ACTIVE", - "value": "prod", - }: - fail("springProfile=true logging-admin-service must enable the prod profile") -elif "SPRING_PROFILES_ACTIVE" in logging_env: - fail("springProfile=false logging-admin-service unexpectedly enables the Spring profile") - -expected_paths = { - "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/client.crt", - "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/client.key", - "FIREMUD_GRPC_CA_CERT_PATH": "/tls/ca.crt", -} -for name, value in expected_paths.items(): - if logging_env.get(name, {}).get("value") != value: - fail( - f"{certificate_identity_mode} logging-admin-service must retain shared " - f"{name}={value!r}, found {logging_env.get(name)!r}" - ) -pod_spec = logging_deployment["spec"]["template"]["spec"] -grpc_mounts = [ - mount - for mount in logging_container.get("volumeMounts", []) - if isinstance(mount, dict) and mount.get("name") == "grpc-tls" -] -if len(grpc_mounts) != 1 or grpc_mounts[0].get("mountPath") != "/tls" or grpc_mounts[0].get("readOnly") is not True: - fail(f"{certificate_identity_mode} logging-admin-service must retain its read-only shared /tls mount") -grpc_volumes = [ - volume - for volume in pod_spec.get("volumes", []) - if isinstance(volume, dict) and volume.get("name") == "grpc-tls" -] -if len(grpc_volumes) != 1 or grpc_volumes[0].get("secret", {}).get("secretName") != "firemud-grpc-tls": - fail(f"{certificate_identity_mode} logging-admin-service must retain the shared firemud-grpc-tls Secret") + return {entry.get("name"): entry for entry in container.get("env", []) if entry.get("name")} + mounted_without_spring = env_map("game-design-service") namespace = mounted_without_spring.get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") @@ -5151,7 +4901,5 @@ without_mount = env_map("world-management-service") if "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in without_mount: fail("publication workload without a gRPC TLS mount unexpectedly declares namespace") PY - done -done echo "hosted identity controller manifest contract passed" diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index b91667497c..e72fd7db91 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -180,6 +180,54 @@ for workload in account-service game-session-service social-groups-service; do assert_mode 644 "$runtime_dir/$workload/workloads/$workload.key" done +# A hard-linked managed projection destination must be rejected before any +# other profile's projection is copied or chmodded. +hardlink_case="$CERT_DIR/hardlink-projection-case" +copy_generic_bundle "$CERT_DIR" "$hardlink_case" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$hardlink_case" +hardlink_runtime="$hardlink_case/local-runtime" +hardlink_target="$hardlink_runtime/social-groups-service/workloads/social-groups-service.key" +hardlink_sentinel="$hardlink_case/runtime-projection-alias-sentinel.txt" +hardlink_output="$CERT_DIR/hardlink-projection-output" +hardlink_before="$CERT_DIR/hardlink-projection-before.sha256" +hardlink_after="$CERT_DIR/hardlink-projection-after.sha256" + +snapshot_runtime_projection() { + local root="$1" + local file + while IFS= read -r -d '' file; do + printf '%s ' "$(stat -c '%a' "$file")" + sha256sum -- "$file" + done < <(find "$root" -type f -print0 | sort -z) +} + +printf 'external hard-link sentinel\n' >"$hardlink_sentinel" +chmod 640 "$hardlink_sentinel" +rm -- "$hardlink_target" +ln -- "$hardlink_sentinel" "$hardlink_target" +snapshot_runtime_projection "$hardlink_runtime" >"$hardlink_before" + +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$hardlink_case" >"$hardlink_output" 2>&1; then + echo "ensure-dev-certs accepted a hard-linked local runtime projection file" >&2 + exit 1 +fi +rg -Fq "refusing hard-linked file in local Compose runtime projection: $hardlink_target" \ + "$hardlink_output" || { + echo "ensure-dev-certs did not identify the hard-linked projection path" >&2 + cat "$hardlink_output" >&2 + exit 1 +} +snapshot_runtime_projection "$hardlink_runtime" >"$hardlink_after" +cmp -s "$hardlink_before" "$hardlink_after" || { + echo "ensure-dev-certs partially changed the local runtime projection before refusal" >&2 + exit 1 +} +[[ "$(<"$hardlink_sentinel")" == 'external hard-link sentinel' ]] || { + echo "ensure-dev-certs changed an external hard-link sentinel" >&2 + exit 1 +} +assert_mode 640 "$hardlink_sentinel" + # Unmanaged regular files under workloads/ retain their own bytes and modes; # only the three named local Compose identities are normalized by ensure. mode_case="$CERT_DIR/unmanaged-workload-modes" diff --git a/docker/README.md b/docker/README.md index 8688c4597e..02334f3694 100644 --- a/docker/README.md +++ b/docker/README.md @@ -36,7 +36,7 @@ docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.ym For ordinary local development, prefer `./gradlew devUp` and `./gradlew devDown`. The Gradle task builds the base image, application images, and `pg-dump-cron` image, ensures development certificates and workload identities, synchronizes the local Compose environment, and waits for the requested services to become ready. The raw source-built commands above are useful when iterating directly on the Compose build path. -Both local Compose lanes use internal gRPC mTLS. `ensure-dev-certs.sh` creates local-only Account, Game Session, and Social Groups workload leaves signed by the local development CA, and prepares the ignored `dev-tools/certs/local-runtime/` bind-mount projection. That projection contains runtime certificates and keys but not the CA private key; it is not a hosted certificate source. The local overrides point the protected callers at their own leaf, set the `local` workload namespace for Account and Logging & Admin peer checks, and keep Gateway/TCP Proxy HTTP and WebSocket routing unchanged. Do not copy these local settings or certificates into preview, dev-demo, or production deployments. +Both local Compose lanes use internal gRPC mTLS. `ensure-dev-certs.sh` creates local-only Account, Game Session, and Social Groups workload leaves signed by the local development CA, and prepares the ignored `dev-tools/certs/local-runtime/` bind-mount projection. That projection contains runtime certificates and keys but not the CA private key; it is not a hosted certificate source. The local overrides point the protected callers at their own leaf, set the `local` workload namespace for Account peer checks, and keep Gateway/TCP Proxy HTTP and WebSocket routing unchanged. Do not copy these local settings or certificates into preview, dev-demo, or production deployments. Canonical smoke/bootstrap proof: diff --git a/k8s/base/logging-admin-service.yaml b/k8s/base/logging-admin-service.yaml index 324c6fb73a..1bd8c367a1 100644 --- a/k8s/base/logging-admin-service.yaml +++ b/k8s/base/logging-admin-service.yaml @@ -24,10 +24,6 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" - - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH value: /tls/client.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index 7809ab70f8..cbefb5c198 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -200,12 +200,6 @@ spec: - name: FIREMUD_GRPC_CA_CERT_PATH value: /grpc-trust/ca.crt {{- else }} -{{- if eq $service.name "logging-admin-service" }} - - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace -{{- end }} {{ include "firemud.grpcTlsEnv" $ | nindent 12 }} {{- end }} {{- end }} diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index bb9c6e2c3a..00a6e74e3f 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -60,6 +60,7 @@ message CreateLogEventResponse { string payload_digest = 8; AccountAuditReceiptStatus status = 9; AccountAuditReceiptOutcome outcome = 10; + int32 audit_projection_version = 11; } message ReadLogEventReceiptRequest { @@ -86,6 +87,7 @@ message ReadLogEventReceiptResponse { string payload_digest = 8; AccountAuditReceiptStatus status = 9; AccountAuditReceiptOutcome outcome = 10; + int32 audit_projection_version = 11; } enum AccountAuditScope { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java index da1fb6e9eb..adf9fe3d60 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java @@ -84,6 +84,10 @@ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { } CreateLogEventResponse response = stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(builder.build()); + if (response.getAuditProjectionVersion() != 1) { + throw new IllegalStateException( + "Account audit receiver did not prove a supported audit projection version"); + } if (!response.getAuditEventId().equals(envelope.auditEventId().toString()) || !response.getPayloadDigest().equals(envelope.payloadDigest()) || response.getSchemaVersion() != envelope.schemaVersion() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index 655c6199b3..44ac20809e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -7,6 +7,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; @@ -60,8 +61,7 @@ public List pending(int limit) { } /** Locks one exact Account JOIN transition envelope for transaction-local reconciliation. */ - public Optional findJoinEnvelopeForUpdate( - UUID auditEventId, long tenantId) { + public Optional findJoinEnvelopeForUpdate(UUID auditEventId, long tenantId) { if (auditEventId == null || tenantId <= 0) { throw new IllegalArgumentException("JOIN audit identity and tenant are required"); } @@ -75,15 +75,30 @@ public Optional findJoinEnvelopeForUpdate( .and(ACCOUNT_AUDIT_OUTBOX.PRODUCER_SERVICE.eq("account-service")) .and(ACCOUNT_AUDIT_OUTBOX.EVENT_TYPE.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"))) .forUpdate() - .fetchOptional(this::toEnvelope); + .fetchOptional( + row -> + new JoinAuditEvidence( + toEnvelope(row), + row.getDeliveryStatus(), + row.getReceiverAuditProjectionVersion(), + row.getReceiverReceiptId(), + row.getReceiverLogEventId())); } public void markDelivered( UUID auditEventId, String receiptId, String logEventId, boolean minimized) { + if (auditEventId == null + || receiptId == null + || receiptId.isBlank() + || logEventId == null + || logEventId.isBlank()) { + throw new IllegalArgumentException("Verified audit delivery requires nonblank identity"); + } var update = dsl.update(ACCOUNT_AUDIT_OUTBOX) .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_RECEIPT_ID, receiptId) .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_LOG_EVENT_ID, logEventId) + .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_AUDIT_PROJECTION_VERSION, 1) .set(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS, minimized ? "MINIMIZED" : "COMMITTED") .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())); if (minimized) { @@ -122,4 +137,15 @@ private AccountAuditEnvelope toEnvelope(AccountAuditOutboxRecord row) { row.getPayloadDigest(), row.getPayload()); } + + public record JoinAuditEvidence( + AccountAuditEnvelope envelope, + String deliveryStatus, + Integer auditProjectionVersion, + String receiptId, + String projectionId) { + public JoinAuditEvidence { + Objects.requireNonNull(envelope, "envelope"); + } + } } 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 d689a03d60..f18c38ff5e 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 @@ -15,6 +15,7 @@ import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.JoinAuditEvidence; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; @@ -171,7 +172,7 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no } JoinMembershipProof membership = null; - AccountAuditEnvelope envelope = null; + JoinAuditEvidence auditEvidence = null; if (unresolvedReason == null) { membership = membershipRepository @@ -185,15 +186,17 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no } if (unresolvedReason == null) { - envelope = + auditEvidence = auditOutboxRepository .findJoinEnvelopeForUpdate( joinAuditEventId(operation.requestId()), operation.tenantId()) .orElse(null); - if (envelope == null) { + if (auditEvidence == null) { unresolvedReason = "JOIN_AUDIT_ENVELOPE_ABSENT"; - } else if (!auditEnvelopeMatches(operation, membership, envelope)) { + } else if (!auditEnvelopeMatches(operation, membership, auditEvidence.envelope())) { unresolvedReason = "JOIN_AUDIT_ENVELOPE_UNCLEAR"; + } else if (!verifiedJoinAuditDelivery(auditEvidence)) { + unresolvedReason = "JOIN_AUDIT_RECEIPT_UNVERIFIED"; } } @@ -328,6 +331,13 @@ private static boolean auditEnvelopeMatches( && Objects.equals(payload.requestId(), operation.requestId()); } + private static boolean verifiedJoinAuditDelivery(JoinAuditEvidence evidence) { + return "COMMITTED".equals(evidence.deliveryStatus()) + && Integer.valueOf(1).equals(evidence.auditProjectionVersion()) + && hasText(evidence.receiptId()) + && hasText(evidence.projectionId()); + } + private static JoinAuditPayload parseJoinAuditPayload(String json) { try { JsonNode root = AUDIT_JSON.readTree(json); diff --git a/services/account-service/src/main/resources/db/migration/V37__verified_audit_projection_evidence.sql b/services/account-service/src/main/resources/db/migration/V37__verified_audit_projection_evidence.sql new file mode 100644 index 0000000000..df24ae30b7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V37__verified_audit_projection_evidence.sql @@ -0,0 +1,6 @@ +ALTER TABLE account_audit_outbox + ADD COLUMN receiver_audit_projection_version INTEGER; + +ALTER TABLE account_audit_outbox + ADD CONSTRAINT account_audit_outbox_projection_version_check + CHECK (receiver_audit_projection_version IS NULL OR receiver_audit_projection_version = 1); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index 301b65d3e8..b90b031dbe 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -173,6 +173,40 @@ void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplica assertMembershipAndAuditOnce(fixture, membershipId); } + @Test + void retainedLegacyReceiptIdsWithoutProjectionVersionStayPending() { + JoinFixture fixture = committedEvidencePendingFixture(); + UUID auditEventId = joinAuditEventId(fixture.requestId()); + int updated = + dsl.execute( + "UPDATE account_audit_outbox SET receiver_audit_projection_version = NULL WHERE audit_event_id = ? AND delivery_status = 'COMMITTED'", + auditEventId); + assertThat(updated).isEqualTo(1); + assertThat( + dsl.resultQuery( + "SELECT receiver_receipt_id FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId) + .fetchOne(0, String.class)) + .isNotBlank(); + assertThat( + dsl.resultQuery( + "SELECT receiver_log_event_id FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId) + .fetchOne(0, String.class)) + .isNotBlank(); + assertThat( + dsl.resultQuery( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId) + .fetchOne(0, Integer.class)) + .isNull(); + + assertUnresolvedAtThreshold(fixture, "JOIN_AUDIT_RECEIPT_UNVERIFIED"); + assertOperation(fixture, "PENDING", null, 2, "JOIN_AUDIT_RECEIPT_UNVERIFIED"); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + } + @Test void absentScopeAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostics() { JoinFixture absentScope = committedEvidencePendingFixture(); @@ -391,6 +425,12 @@ private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture, int a attempts, fixture.requestId()); assertThat(updated).isEqualTo(1); + int auditUpdated = + dsl.execute( + "UPDATE account_audit_outbox SET delivery_status = 'COMMITTED', receiver_audit_projection_version = 1, receiver_receipt_id = 'verified-receipt', receiver_log_event_id = 'verified-projection' WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + joinAuditEventId(fixture.requestId()), + fixture.tenantId()); + assertThat(auditUpdated).isEqualTo(1); assertThat(countMemberships(fixture)).isEqualTo(1L); assertThat(countJoinOutbox(fixture)).isEqualTo(1L); } 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 691527c0e3..42dbdb9eb1 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 @@ -195,6 +195,12 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { Long.class, auditEventId)) .isEqualTo(1L); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + auditEventId)) + .isNull(); } @Test @@ -261,6 +267,12 @@ void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { String.class, minimizedEventId)) .isEqualTo("MINIMIZED"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + minimizedEventId)) + .isEqualTo(1); assertThat( jdbc.queryForObject( "SELECT payload FROM account_audit_outbox WHERE audit_event_id = ?", @@ -273,11 +285,48 @@ void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { String.class, committedEventId)) .isEqualTo("COMMITTED"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + committedEventId)) + .isEqualTo(1); + assertThatThrownBy( + () -> + jdbc.update( + "UPDATE account_audit_outbox SET receiver_audit_projection_version = 2 WHERE audit_event_id = ?", + committedEventId)) + .isInstanceOf(org.springframework.dao.DataAccessException.class); assertThat(outbox.pending(10)) .noneMatch(envelope -> envelope.auditEventId().equals(minimizedEventId)) .noneMatch(envelope -> envelope.auditEventId().equals(committedEventId)); } + @Test + void markDeliveredRejectsBlankReceiverIdentityWithoutChangingPendingRow() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(dsl); + UUID eventId = UUID.randomUUID(); + outbox.append(eventId, "platform", null, "ACCOUNT_REGISTERED", "{\"accountId\":44}"); + + assertThatThrownBy(() -> outbox.markDelivered(eventId, " ", "projection-id", false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Verified audit delivery requires nonblank identity"); + + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + eventId)) + .isEqualTo("PENDING"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + eventId)) + .isNull(); + } + @Test void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java new file mode 100644 index 0000000000..d9add2a482 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +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.loggingadmin.v1.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; +import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class LoggingAdminClientTest { + private static final UUID AUDIT_EVENT_ID = + UUID.fromString("f2b6e93a-d948-40b2-9b31-7291a5116237"); + private static final long TENANT_ID = 37L; + + @Test + void acceptsOnlyExactCommittedReceiptWithCurrentProjectionVersion() throws Exception { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = mockStub(); + when(stub.createLogEvent(any())).thenReturn(response(1)); + LoggingAdminClient client = newClient(stub); + + LoggingAdminClient.AuditDeliveryResult result = client.deliver(envelope()); + + assertThat(result.receiptId()).isEqualTo("receipt-1"); + assertThat(result.logEventId()).isEqualTo("projection-1"); + assertThat(result.minimized()).isFalse(); + } + + @ParameterizedTest + @ValueSource(ints = {0, 2, -1}) + void rejectsMissingOrUnsupportedProjectionVersion(int version) throws Exception { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = mockStub(); + when(stub.createLogEvent(any())).thenReturn(response(version)); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(envelope())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account audit receiver did not prove a supported audit projection version"); + } + + private static AccountAuditEnvelope envelope() { + String payload = "{\"accountId\":19,\"tenantId\":37}"; + return new AccountAuditEnvelope( + AUDIT_EVENT_ID, + "tenant", + TENANT_ID, + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + Instant.parse("2026-09-25T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } + + private static CreateLogEventResponse response(int projectionVersion) { + AccountAuditEnvelope envelope = envelope(); + return CreateLogEventResponse.newBuilder() + .setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantId(Long.toString(TENANT_ID)) + .setAuditEventId(envelope.auditEventId().toString()) + .setReceiptId("receipt-1") + .setLogEventId("projection-1") + .setSchemaVersion(envelope.schemaVersion()) + .setPayloadDigestVersion(envelope.payloadDigestVersion()) + .setPayloadDigest(envelope.payloadDigest()) + .setStatus(AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED) + .setOutcome(AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED) + .setAuditProjectionVersion(projectionVersion) + .build(); + } + + private static LoggingAdminClient newClient( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub) throws Exception { + LoggingAdminClient client = + new LoggingAdminClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } + + private static LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub mockStub() { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = + mock(LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } +} 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 6dd71e97a6..c4b429974e 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 @@ -23,6 +23,7 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.JoinAuditEvidence; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.ConnectScopeEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; @@ -30,6 +31,9 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.InOrder; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -62,7 +66,10 @@ void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) .thenReturn(Optional.of(activeJoinMembership())); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) - .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()))); + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest())))); fixture.service.reconcileDueOperations(NOW); @@ -83,6 +90,62 @@ void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { assertThat(reconciliationCounter(fixture, "committed")).isEqualTo(1); } + @ParameterizedTest + @MethodSource("unverifiedAuditDeliveryEvidence") + void incompleteOrLegacyAuditDeliveryEvidenceStaysPending( + String status, Integer version, String receiptId, String projectionId) { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + 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())); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + new JoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()), + status, + version, + receiptId, + projectionId))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_RECEIPT_UNVERIFIED", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_AUDIT_RECEIPT_UNVERIFIED", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); + } + + private static List unverifiedAuditDeliveryEvidence() { + return List.of( + Arguments.of("PENDING", null, null, null), + Arguments.of("COMMITTED", null, "legacy-receipt", "legacy-log-event-id"), + Arguments.of("COMMITTED", 2, "receipt-v2", "projection-v2"), + Arguments.of("COMMITTED", 1, " ", "projection-v1"), + Arguments.of("MINIMIZED", 1, "receipt-v1", "projection-v1")); + } + @Test void missingMembershipAfterScopeExpiryStaysPendingAndReschedulesAtTheAttemptThreshold() { Fixture fixture = fixture(3); @@ -228,7 +291,10 @@ void wrongPayloadDigestStaysPending() { when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) .thenReturn(Optional.of(activeJoinMembership())); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) - .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, sha256("wrong")))); + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, sha256("wrong"))))); when(fixture.joinOperations.recordReconciliationAttempt( REQUEST_ID, 0, @@ -268,8 +334,11 @@ void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn( Optional.of( - joinAuditEnvelope( - "other-world", TENANT_ID, AccountAuditDigest.ofPayload(mismatchedPayload)))); + verifiedJoinAuditEvidence( + joinAuditEnvelope( + "other-world", + TENANT_ID, + AccountAuditDigest.ofPayload(mismatchedPayload))))); when(fixture.joinOperations.recordReconciliationAttempt( REQUEST_ID, 0, @@ -341,7 +410,10 @@ void repeatedRunDoesNotFinishSameJoinTwice() { when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) .thenReturn(Optional.of(activeJoinMembership())); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) - .thenReturn(Optional.of(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest()))); + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest())))); fixture.service.reconcileDueOperations(NOW); fixture.service.reconcileDueOperations(NOW); @@ -580,6 +652,10 @@ private static AccountAuditEnvelope joinAuditEnvelope( payload); } + private static JoinAuditEvidence verifiedJoinAuditEvidence(AccountAuditEnvelope envelope) { + return new JoinAuditEvidence(envelope, "COMMITTED", 1, "verified-receipt", "verified-log"); + } + private static UUID joinAuditEventId() { return UUID.nameUUIDFromBytes( ("account-join-audit/v1:" + REQUEST_ID).getBytes(StandardCharsets.UTF_8)); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java deleted file mode 100644 index 5301aae34d..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.firedevops.firemud.loggingadmin.config; - -import java.util.HashSet; -import java.util.Set; -import net.firedevops.firemud.common.security.AuthTokenInterceptor; -import net.firedevops.firemud.common.security.GrpcAuthProperties; -import net.firedevops.firemud.common.security.JwtUtil; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.grpc.server.GlobalServerInterceptor; - -/** Allows mTLS-guarded Account audit methods to run without a JWT token. */ -@Configuration(proxyBeanMethods = false) -public class AccountAuditGrpcAuthConfiguration { - private static final Set ACCOUNT_AUDIT_METHODS = - Set.of( - "logging_admin.v1.LoggingAdminService/CreateLogEvent", - "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt"); - - @Bean - @GlobalServerInterceptor - @ConditionalOnProperty( - prefix = "firemud.auth.grpc", - name = "interceptor-enabled", - havingValue = "true", - matchIfMissing = true) - @ConditionalOnMissingBean(AuthTokenInterceptor.class) - public AuthTokenInterceptor accountAuditAuthTokenInterceptor( - @Qualifier("jwtUtil") JwtUtil jwtUtil, GrpcAuthProperties properties) { - Set unauthenticatedMethods = new HashSet<>(properties.getPublicMethods()); - unauthenticatedMethods.addAll(ACCOUNT_AUDIT_METHODS); - return new AuthTokenInterceptor(jwtUtil, unauthenticatedMethods); - } -} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java deleted file mode 100644 index b80457862e..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.firedevops.firemud.loggingadmin.dto; - -public record AccountAuditReceiptDto( - AccountAuditScope scope, - Long tenantId, - String auditEventId, - String receiptId, - long logEventId, - int schemaVersion, - int payloadDigestVersion, - String payloadDigest, - AccountAuditReceiptStatus status, - AccountAuditReceiptOutcome outcome) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java deleted file mode 100644 index 35bdf8d33a..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java +++ /dev/null @@ -1,8 +0,0 @@ -package net.firedevops.firemud.loggingadmin.dto; - -public enum AccountAuditReceiptOutcome { - ACCEPTED, - DUPLICATE, - NON_REPLAYABLE, - IDEMPOTENCY_CONFLICT -} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java deleted file mode 100644 index 9c9a8f5047..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.firedevops.firemud.loggingadmin.dto; - -public enum AccountAuditReceiptStatus { - COMMITTED, - MINIMIZED, - CONFLICT -} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java deleted file mode 100644 index e3f9b85a3d..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.firedevops.firemud.loggingadmin.dto; - -public enum AccountAuditScope { - PLATFORM("platform"), - TENANT("tenant"); - - private final String databaseValue; - - AccountAuditScope(String databaseValue) { - this.databaseValue = databaseValue; - } - - public String databaseValue() { - return databaseValue; - } -} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java index 0e187d9160..bbded3dd0b 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java @@ -1,22 +1,10 @@ package net.firedevops.firemud.loggingadmin.dto; -import com.google.protobuf.ByteString; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.time.Instant; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; -/** The immutable Account audit envelope accepted by the existing CreateLogEvent RPC. */ -@SuppressFBWarnings( - value = "EI_EXPOSE_REP", - justification = - "Protobuf ByteString is immutable, so retaining and exposing the payload is safe.") public record CreateLogEventRequest( - AccountAuditScope scope, - Long tenantId, - String auditEventId, - String producerService, - String eventType, - Instant occurredAt, - int schemaVersion, - ByteString payload, - int payloadDigestVersion, - String payloadDigest) {} + @NotNull Long tenantId, + Long accountId, + @NotNull @Size(max = 50) String type, + @NotNull @Size(max = 255) String message) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java deleted file mode 100644 index 2d3eeeb6c7..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.firedevops.firemud.loggingadmin.entity; - -import java.util.UUID; - -/** A durable receiver-side audit envelope and its readback receipt. */ -public record AccountAuditReceipt( - long id, - long logEventId, - UUID receiptId, - String scope, - Long tenantId, - String auditEventId, - String producerService, - String eventType, - long occurredAtSeconds, - int occurredAtNanos, - int schemaVersion, - int payloadDigestVersion, - String payloadDigest, - byte[] payload, - String status, - String outcome) { - public AccountAuditReceipt { - payload = payload == null ? null : payload.clone(); - } - - @Override - public byte[] payload() { - return payload == null ? null : payload.clone(); - } -} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java deleted file mode 100644 index 226e9d4046..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java +++ /dev/null @@ -1,3 +0,0 @@ -package net.firedevops.firemud.loggingadmin.entity; - -public record AccountAuditReceiptInsertResult(AccountAuditReceipt receipt, boolean inserted) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java deleted file mode 100644 index ef646e3987..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java +++ /dev/null @@ -1,131 +0,0 @@ -package net.firedevops.firemud.loggingadmin.repository; - -import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; -import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; -import static net.firedevops.firemud.loggingadmin.jooq.tables.LogEvents.LOG_EVENTS; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; -import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; -import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; -import org.jooq.DSLContext; -import org.jooq.Record; -import org.springframework.stereotype.Repository; - -@Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") -public class AccountAuditReceiptRepository { - private static final String ACCOUNT_AUDIT_PROJECTION_TYPE = "ACCOUNT_AUDIT"; - private static final String ACCOUNT_AUDIT_PROJECTION_MESSAGE_PREFIX = "Account audit event "; - - private final DSLContext dsl; - - public AccountAuditReceiptRepository(DSLContext dsl) { - this.dsl = dsl; - } - - public AccountAuditReceiptInsertResult insertIfAbsent( - CreateLogEventRequest request, UUID receiptId) { - long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); - long logEventId = insertOrFindProjection(request); - int inserted = - dsl.insertInto(ACCOUNT_AUDIT_RECEIPTS) - .set(ACCOUNT_AUDIT_RECEIPTS.LOG_EVENT_ID, logEventId) - .set(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID, receiptId) - .set(ACCOUNT_AUDIT_RECEIPTS.SCOPE, request.scope().databaseValue()) - .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_ID, request.tenantId()) - .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY, tenantKey) - .set(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID, request.auditEventId()) - .set(ACCOUNT_AUDIT_RECEIPTS.PRODUCER_SERVICE, request.producerService()) - .set(ACCOUNT_AUDIT_RECEIPTS.EVENT_TYPE, request.eventType()) - .set(ACCOUNT_AUDIT_RECEIPTS.OCCURRED_AT_SECONDS, request.occurredAt().getEpochSecond()) - .set(ACCOUNT_AUDIT_RECEIPTS.OCCURRED_AT_NANOS, request.occurredAt().getNano()) - .set(ACCOUNT_AUDIT_RECEIPTS.SCHEMA_VERSION, request.schemaVersion()) - .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD_DIGEST_VERSION, request.payloadDigestVersion()) - .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD_DIGEST, request.payloadDigest()) - .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD, request.payload().toByteArray()) - .set(ACCOUNT_AUDIT_RECEIPTS.STATUS, "COMMITTED") - .set(ACCOUNT_AUDIT_RECEIPTS.OUTCOME, "ACCEPTED") - .onConflictDoNothing() - .execute(); - AccountAuditReceipt receipt = - findByIdentity(request, tenantKey) - .orElseThrow( - () -> - new IllegalStateException( - "Account audit receipt identity conflict did not resolve to a receipt")); - return new AccountAuditReceiptInsertResult(receipt, inserted == 1); - } - - private long insertOrFindProjection(CreateLogEventRequest request) { - Long tenantKey = request.tenantId() == null ? Long.valueOf(0L) : request.tenantId(); - dsl.insertInto(LOG_EVENTS) - .set(LOG_EVENTS.SCOPE, request.scope().databaseValue()) - .set(LOG_EVENTS.TENANT_ID, request.tenantId()) - .set(LOG_EVENTS.TENANT_KEY, tenantKey) - .set(LOG_EVENTS.AUDIT_EVENT_ID, request.auditEventId()) - .set(LOG_EVENTS.TYPE, ACCOUNT_AUDIT_PROJECTION_TYPE) - .set(LOG_EVENTS.MESSAGE, ACCOUNT_AUDIT_PROJECTION_MESSAGE_PREFIX + request.auditEventId()) - .set(LOG_EVENTS.TIMESTAMP, toLocalDateTime(request.occurredAt())) - .set(LOG_EVENTS.ACCOUNT_ID, (Long) null) - .onConflictDoNothing() - .execute(); - - var tenantCondition = - request.tenantId() == null - ? LOG_EVENTS.TENANT_ID.isNull() - : LOG_EVENTS.TENANT_ID.eq(request.tenantId()); - Long logEventId = - dsl.select(LOG_EVENTS.ID) - .from(LOG_EVENTS) - .where( - LOG_EVENTS - .SCOPE - .eq(request.scope().databaseValue()) - .and(tenantCondition) - .and(LOG_EVENTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) - .fetchOne(LOG_EVENTS.ID); - if (logEventId == null) { - throw new IllegalStateException("Account audit projection identity did not resolve"); - } - return logEventId; - } - - public Optional findByIdentity( - CreateLogEventRequest request, long tenantKey) { - return dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) - .where( - ACCOUNT_AUDIT_RECEIPTS - .SCOPE - .eq(request.scope().databaseValue()) - .and(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY.eq(tenantKey)) - .and(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) - .fetchOptional(this::toEntity); - } - - private AccountAuditReceipt toEntity(Record record) { - AccountAuditReceiptsRecord receiptRecord = (AccountAuditReceiptsRecord) record; - return new AccountAuditReceipt( - receiptRecord.getId(), - receiptRecord.getLogEventId(), - receiptRecord.getReceiptId(), - receiptRecord.getScope(), - receiptRecord.getTenantId(), - receiptRecord.getAuditEventId(), - receiptRecord.getProducerService(), - receiptRecord.getEventType(), - receiptRecord.getOccurredAtSeconds(), - receiptRecord.getOccurredAtNanos(), - receiptRecord.getSchemaVersion(), - receiptRecord.getPayloadDigestVersion(), - receiptRecord.getPayloadDigest(), - receiptRecord.getPayload(), - receiptRecord.getStatus(), - receiptRecord.getOutcome()); - } -} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java index 3554945a10..0abd0a35c2 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java @@ -7,7 +7,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import java.util.Optional; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; import net.firedevops.firemud.loggingadmin.entity.LogEvent; import net.firedevops.firemud.loggingadmin.jooq.tables.records.LogEventsRecord; import org.jooq.DSLContext; @@ -33,12 +32,7 @@ public List findByTenantIdAndMessageContainingIgnoreCase( Long tenantId, String message) { String filter = message == null ? "" : message; return dsl.selectFrom(LOG_EVENTS) - .where( - LOG_EVENTS - .SCOPE - .eq(AccountAuditScope.TENANT.databaseValue()) - .and(LOG_EVENTS.TENANT_ID.eq(tenantId)) - .and(LOG_EVENTS.MESSAGE.containsIgnoreCase(filter))) + .where(LOG_EVENTS.TENANT_ID.eq(tenantId).and(LOG_EVENTS.MESSAGE.containsIgnoreCase(filter))) .fetch(this::toEntity); } @@ -49,7 +43,6 @@ public Optional findFirstByTenantIdAndTypeAndMessage( LOG_EVENTS .TENANT_ID .eq(tenantId) - .and(LOG_EVENTS.SCOPE.eq(AccountAuditScope.TENANT.databaseValue())) .and(LOG_EVENTS.TYPE.eq(type)) .and(LOG_EVENTS.MESSAGE.eq(message))) .orderBy(LOG_EVENTS.ID.asc()) @@ -68,13 +61,11 @@ public LogEvent save(LogEvent entity) { int updated = dsl.update(LOG_EVENTS) .set(LOG_EVENTS.TENANT_ID, entity.getTenantId()) - .set(LOG_EVENTS.TENANT_KEY, entity.getTenantId()) - .set(LOG_EVENTS.SCOPE, AccountAuditScope.TENANT.databaseValue()) .set(LOG_EVENTS.TYPE, entity.getType()) .set(LOG_EVENTS.MESSAGE, entity.getMessage()) .set(LOG_EVENTS.TIMESTAMP, toLocalDateTime(entity.getTimestamp())) .set(LOG_EVENTS.ACCOUNT_ID, entity.getAccountId()) - .where(LOG_EVENTS.ID.eq(entity.getId()).and(LOG_EVENTS.AUDIT_EVENT_ID.isNull())) + .where(LOG_EVENTS.ID.eq(entity.getId())) .execute(); if (updated != 1) { throw new IllegalStateException("Failed to update log_events id=" + entity.getId()); @@ -88,8 +79,6 @@ private Optional findById(Long id) { private void populate(LogEventsRecord record, LogEvent entity) { record.setTenantId(entity.getTenantId()); - record.setTenantKey(entity.getTenantId()); - record.setScope(AccountAuditScope.TENANT.databaseValue()); record.setType(entity.getType()); record.setMessage(entity.getMessage()); record.setTimestamp(toLocalDateTime(entity.getTimestamp())); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java deleted file mode 100644 index 52b49613b5..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.firedevops.firemud.loggingadmin.service; - -public class AuditReceiptNotFoundException extends RuntimeException { - public AuditReceiptNotFoundException() { - super("Account audit receipt not found"); - } -} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java deleted file mode 100644 index c8abf99170..0000000000 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.firedevops.firemud.loggingadmin.service; - -public class AuditStorageUnavailableException extends RuntimeException { - public AuditStorageUnavailableException(Throwable cause) { - super("Account audit receipt storage is unavailable", cause); - } -} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java index e86cc22dc0..0617b3ad2e 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java @@ -1,10 +1,8 @@ package net.firedevops.firemud.loggingadmin.service; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.dto.LogEventDto; public interface LogEventService { - AccountAuditReceiptDto createLogEvent(CreateLogEventRequest request); - - AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request); + LogEventDto createLogEvent(CreateLogEventRequest request); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java index 8baf9b73f1..fc3c54d6a0 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java @@ -1,28 +1,14 @@ package net.firedevops.firemud.loggingadmin.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import io.micrometer.core.annotation.Timed; import java.time.Instant; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.Objects; -import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; -import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; -import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; -import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; -import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; +import net.firedevops.firemud.loggingadmin.dto.LogEventDto; +import net.firedevops.firemud.loggingadmin.entity.LogEvent; +import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; import net.firedevops.firemud.loggingadmin.service.LogEventService; -import org.jooq.exception.DataAccessException; import org.slf4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -33,184 +19,31 @@ justification = "Spring injects the shared repository singleton for this service seam.") public class LogEventServiceImpl implements LogEventService { private static final Logger logger = LoggingUtil.getLogger(LogEventServiceImpl.class); - private static final String ACCOUNT_SERVICE = "account-service"; - private static final String SHA_256_PREFIX = "sha256:"; - private final AccountAuditReceiptRepository repository; + private final LogEventRepository repository; - public LogEventServiceImpl(AccountAuditReceiptRepository repository) { + public LogEventServiceImpl(LogEventRepository repository) { this.repository = repository; } @Override @Transactional - public AccountAuditReceiptDto createLogEvent(CreateLogEventRequest request) { - validateEnvelope(request); - try { - AccountAuditReceiptInsertResult result = - repository.insertIfAbsent(request, UUID.randomUUID()); - return receiptOutcome(result.receipt(), request, result.inserted()); - } catch (DataAccessException ex) { - logger.warn("Account audit receipt write is unavailable: {}", ex.getClass().getSimpleName()); - throw new AuditStorageUnavailableException(ex); - } - } - - @Override - @Transactional(readOnly = true) - public AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request) { - validateEnvelope(request); - try { - long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); - AccountAuditReceipt receipt = - repository - .findByIdentity(request, tenantKey) - .orElseThrow(AuditReceiptNotFoundException::new); - return receiptOutcome(receipt, request, false); - } catch (AuditReceiptNotFoundException ex) { - throw ex; - } catch (DataAccessException ex) { - logger.warn("Account audit receipt read is unavailable: {}", ex.getClass().getSimpleName()); - throw new AuditStorageUnavailableException(ex); - } - } - - private static AccountAuditReceiptDto receiptOutcome( - AccountAuditReceipt receipt, CreateLogEventRequest request, boolean inserted) { - if (inserted) { - return toDto( - receipt, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.ACCEPTED); - } - - boolean metadataMatches = metadataMatches(receipt, request); - if (!metadataMatches) { - return toDto( - receipt, - AccountAuditReceiptStatus.CONFLICT, - AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); - } - - byte[] retainedPayload = receipt.payload(); - if (retainedPayload == null) { - return toDto( - receipt, AccountAuditReceiptStatus.MINIMIZED, AccountAuditReceiptOutcome.NON_REPLAYABLE); - } - if (!Arrays.equals(retainedPayload, request.payload().toByteArray())) { - return toDto( - receipt, - AccountAuditReceiptStatus.CONFLICT, - AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); - } - - if ("MINIMIZED".equals(receipt.status()) || "NON_REPLAYABLE".equals(receipt.outcome())) { - return toDto( - receipt, AccountAuditReceiptStatus.MINIMIZED, AccountAuditReceiptOutcome.NON_REPLAYABLE); - } - if (!"COMMITTED".equals(receipt.status())) { - throw new IllegalStateException("Unknown persisted account audit receipt status"); - } - return toDto( - receipt, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.DUPLICATE); - } - - private static boolean metadataMatches( - AccountAuditReceipt receipt, CreateLogEventRequest request) { - Instant occurredAt = request.occurredAt(); - return receipt.scope().equals(request.scope().databaseValue()) - && Objects.equals(receipt.tenantId(), request.tenantId()) - && receipt.auditEventId().equals(request.auditEventId()) - && receipt.producerService().equals(request.producerService()) - && receipt.eventType().equals(request.eventType()) - && receipt.occurredAtSeconds() == occurredAt.getEpochSecond() - && receipt.occurredAtNanos() == occurredAt.getNano() - && receipt.schemaVersion() == request.schemaVersion() - && receipt.payloadDigestVersion() == request.payloadDigestVersion() - && receipt.payloadDigest().equals(request.payloadDigest()); - } - - private static AccountAuditReceiptDto toDto( - AccountAuditReceipt receipt, - AccountAuditReceiptStatus status, - AccountAuditReceiptOutcome outcome) { - return new AccountAuditReceiptDto( - "platform".equals(receipt.scope()) - ? net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM - : net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.TENANT, - receipt.tenantId(), - receipt.auditEventId(), - receipt.receiptId().toString(), - receipt.logEventId(), - receipt.schemaVersion(), - receipt.payloadDigestVersion(), - receipt.payloadDigest(), - status, - outcome); - } - - private static void validateEnvelope(CreateLogEventRequest request) { - if (request == null - || request.scope() == null - || request.auditEventId() == null - || request.auditEventId().isBlank() - || request.producerService() == null - || !ACCOUNT_SERVICE.equals(request.producerService()) - || request.eventType() == null - || request.eventType().isBlank() - || request.occurredAt() == null - || request.schemaVersion() <= 0 - || request.payload() == null - || request.payloadDigest() == null) { - throw new IllegalArgumentException("Account audit envelope is incomplete"); - } - if (!isCanonicalUuid(request.auditEventId())) { - throw new IllegalArgumentException("auditEventId must be a canonical UUID"); - } - if (request.scope() == net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM) { - if (request.tenantId() != null) { - throw new IllegalArgumentException("tenantId must be absent for platform scope"); - } - } else if (request.tenantId() == null || request.tenantId() <= 0) { - throw new IllegalArgumentException("tenantId must be positive for tenant scope"); - } - if (request.payloadDigestVersion() != 1) { - throw new IllegalArgumentException("payloadDigestVersion must be 1"); - } - if (!request.payloadDigest().matches("sha256:[0-9a-f]{64}")) { - throw new IllegalArgumentException("payloadDigest must be lowercase sha256 hex"); - } - byte[] payloadBytes = request.payload().toByteArray(); - validateUtf8(payloadBytes); - String computedDigest = SHA_256_PREFIX + sha256Hex(payloadBytes); - if (!computedDigest.equals(request.payloadDigest())) { - throw new IllegalArgumentException("payloadDigest does not match the exact payload bytes"); - } - } - - private static boolean isCanonicalUuid(String value) { - try { - return value.equals(UUID.fromString(value).toString()); - } catch (IllegalArgumentException ex) { - return false; - } - } - - private static void validateUtf8(byte[] payload) { - try { - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(java.nio.ByteBuffer.wrap(payload)); - } catch (CharacterCodingException ex) { - throw new IllegalArgumentException("payload must contain exact UTF-8 bytes", ex); - } - } - - private static String sha256Hex(byte[] payload) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 is unavailable", ex); - } + @Timed(value = "logging.createLogEvent") + public LogEventDto createLogEvent(CreateLogEventRequest request) { + logger.info("Creating log event {} for tenant {}", request.type(), request.tenantId()); + LogEvent entity = new LogEvent(); + entity.setTenantId(request.tenantId()); + entity.setAccountId(request.accountId()); + entity.setType(request.type()); + entity.setMessage(request.message()); + entity.setTimestamp(Instant.now()); + entity = repository.save(entity); + return new LogEventDto( + entity.getId(), + entity.getTenantId(), + entity.getAccountId(), + entity.getType(), + entity.getMessage(), + entity.getTimestamp()); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index 5f138cff0e..68bf6ab3bf 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -1,39 +1,24 @@ package net.firedevops.firemud.loggingadmin.service.impl; -import com.google.protobuf.ByteString; -import com.google.protobuf.Timestamp; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; -import java.time.Instant; import java.util.List; -import java.util.Map; import java.util.Set; import net.firedevops.firemud.common.grpc.GrpcAppErrors; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; -import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; -import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.loggingadmin.service.ModerationService; import net.firedevops.firemud.loggingadmin.v1.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; -import org.springframework.transaction.TransactionException; @GrpcService public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdminServiceImplBase { @@ -44,16 +29,10 @@ public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdmi "Feature-flag toggles are unavailable until the shared mutation gate is implemented"; private static final Set MODERATION_POLICY_CALLERS = Set.of("game-session-service", "social-groups-service"); - private static final String ACCOUNT_SERVICE = "account-service"; - private static final Map> ACCOUNT_AUDIT_CALLER_ALLOWLIST = - Map.of( - "CreateLogEvent", Set.of(ACCOUNT_SERVICE), - "ReadLogEventReceipt", Set.of(ACCOUNT_SERVICE)); private final LogQueryService logQueryService; private final LogEventService logEventService; private final ModerationService moderationService; - private final String workloadNamespace; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -65,21 +44,10 @@ public LoggingAdminGrpcService( LogEventService logEventService, ModerationService moderationService, MeterRegistry meterRegistry) { - this(logQueryService, logEventService, moderationService, meterRegistry, null); - } - - @Autowired - public LoggingAdminGrpcService( - LogQueryService logQueryService, - LogEventService logEventService, - ModerationService moderationService, - MeterRegistry meterRegistry, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.logQueryService = logQueryService; this.logEventService = logEventService; this.moderationService = moderationService; this.meterRegistry = meterRegistry; - this.workloadNamespace = workloadNamespace; } @Override @@ -206,226 +174,11 @@ public void queryLogs( @Timed(value = "loggingadminGrpc.createLogEvent") public void createLogEvent( CreateLogEventRequest request, StreamObserver responseObserver) { - try { - requireAccountAuditCaller("CreateLogEvent"); - AccountAuditReceiptDto receipt = logEventService.createLogEvent(toAuditRequest(request)); - CreateLogEventResponse response = toCreateLogEventResponse(receipt); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AdminAuthorizationException ex) { - responseObserver.onError( - Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); - } catch (IllegalArgumentException ex) { - responseObserver.onError( - Status.INVALID_ARGUMENT.withDescription(ex.getMessage()).asRuntimeException()); - } catch (AuditStorageUnavailableException ex) { - responseObserver.onError( - Status.UNAVAILABLE.withDescription(ex.getMessage()).asRuntimeException()); - } catch (DataAccessException | TransactionException ex) { - logger.warn("CreateLogEvent transaction is unavailable: {}", ex.getClass().getSimpleName()); - responseObserver.onError( - Status.UNAVAILABLE - .withDescription("Account audit ingress storage is unavailable") - .asRuntimeException()); - } catch (Exception ex) { - logger.error("CreateLogEvent failed before producing an audit receipt", ex); - responseObserver.onError( - Status.INTERNAL.withDescription("Account audit ingress failed").asRuntimeException()); - } - } - - @Override - @Timed(value = "loggingadminGrpc.readLogEventReceipt") - public void readLogEventReceipt( - ReadLogEventReceiptRequest request, - StreamObserver responseObserver) { - try { - requireAccountAuditCaller("ReadLogEventReceipt"); - AccountAuditReceiptDto receipt = logEventService.readLogEventReceipt(toAuditRequest(request)); - responseObserver.onNext(toReadLogEventReceiptResponse(receipt)); - responseObserver.onCompleted(); - } catch (AdminAuthorizationException ex) { - responseObserver.onError( - Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); - } catch (IllegalArgumentException ex) { - responseObserver.onError( - Status.INVALID_ARGUMENT.withDescription(ex.getMessage()).asRuntimeException()); - } catch (AuditReceiptNotFoundException ex) { - responseObserver.onError( - Status.NOT_FOUND.withDescription(ex.getMessage()).asRuntimeException()); - } catch (AuditStorageUnavailableException ex) { - responseObserver.onError( - Status.UNAVAILABLE.withDescription(ex.getMessage()).asRuntimeException()); - } catch (DataAccessException | TransactionException ex) { - logger.warn( - "ReadLogEventReceipt transaction is unavailable: {}", ex.getClass().getSimpleName()); - responseObserver.onError( - Status.UNAVAILABLE - .withDescription("Account audit receipt storage is unavailable") - .asRuntimeException()); - } catch (Exception ex) { - logger.error("ReadLogEventReceipt failed before producing a receipt", ex); - responseObserver.onError( - Status.INTERNAL - .withDescription("Account audit receipt read failed") - .asRuntimeException()); - } - } - - private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( - CreateLogEventRequest request) { - return toAuditRequest( - request.getScope(), - request.getTenantId(), - request.getAuditEventId(), - request.getProducerService(), - request.getEventType(), - request.hasOccurredAt() ? request.getOccurredAt() : null, - request.getSchemaVersion(), - request.getPayload(), - request.getPayloadDigestVersion(), - request.getPayloadDigest()); - } - - private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( - ReadLogEventReceiptRequest request) { - return toAuditRequest( - request.getScope(), - request.getTenantId(), - request.getAuditEventId(), - request.getProducerService(), - request.getEventType(), - request.hasOccurredAt() ? request.getOccurredAt() : null, - request.getSchemaVersion(), - request.getPayload(), - request.getPayloadDigestVersion(), - request.getPayloadDigest()); - } - - private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( - net.firedevops.firemud.loggingadmin.v1.AccountAuditScope requestScope, - String tenantIdText, - String auditEventId, - String producerService, - String eventType, - Timestamp occurredAt, - int schemaVersion, - ByteString payload, - int payloadDigestVersion, - String payloadDigest) { - AccountAuditScope scope = - switch (requestScope) { - case ACCOUNT_AUDIT_SCOPE_PLATFORM -> AccountAuditScope.PLATFORM; - case ACCOUNT_AUDIT_SCOPE_TENANT -> AccountAuditScope.TENANT; - default -> throw new IllegalArgumentException("scope must be platform or tenant"); - }; - Long tenantId; - if (scope == AccountAuditScope.TENANT) { - tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); - } else { - if (!tenantIdText.isEmpty()) { - throw new IllegalArgumentException("tenantId must be absent for platform scope"); - } - tenantId = null; - } - if (!ACCOUNT_SERVICE.equals(producerService)) { - throw new IllegalArgumentException( - "producerService must match the authenticated account-service workload"); - } - if (occurredAt == null) { - throw new IllegalArgumentException("occurredAt is required"); - } - if (occurredAt.getSeconds() < -62135596800L - || occurredAt.getSeconds() > 253402300799L - || occurredAt.getNanos() < 0 - || occurredAt.getNanos() > 999999999) { - throw new IllegalArgumentException("occurredAt must be a valid protobuf timestamp"); - } - return new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( - scope, - tenantId, - auditEventId, - ACCOUNT_SERVICE, - eventType, - Instant.ofEpochSecond(occurredAt.getSeconds(), occurredAt.getNanos()), - schemaVersion, - payload, - payloadDigestVersion, - payloadDigest); - } - - private static CreateLogEventResponse toCreateLogEventResponse(AccountAuditReceiptDto receipt) { - return CreateLogEventResponse.newBuilder() - .setScope(toProtoScope(receipt.scope())) - .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) - .setAuditEventId(receipt.auditEventId()) - .setReceiptId(receipt.receiptId()) - .setLogEventId(Long.toString(receipt.logEventId())) - .setSchemaVersion(receipt.schemaVersion()) - .setPayloadDigestVersion(receipt.payloadDigestVersion()) - .setPayloadDigest(receipt.payloadDigest()) - .setStatus(toProtoStatus(receipt.status())) - .setOutcome(toProtoOutcome(receipt.outcome())) - .build(); - } - - private static ReadLogEventReceiptResponse toReadLogEventReceiptResponse( - AccountAuditReceiptDto receipt) { - return ReadLogEventReceiptResponse.newBuilder() - .setScope(toProtoScope(receipt.scope())) - .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) - .setAuditEventId(receipt.auditEventId()) - .setReceiptId(receipt.receiptId()) - .setLogEventId(Long.toString(receipt.logEventId())) - .setSchemaVersion(receipt.schemaVersion()) - .setPayloadDigestVersion(receipt.payloadDigestVersion()) - .setPayloadDigest(receipt.payloadDigest()) - .setStatus(toProtoStatus(receipt.status())) - .setOutcome(toProtoOutcome(receipt.outcome())) - .build(); - } - - private static net.firedevops.firemud.loggingadmin.v1.AccountAuditScope toProtoScope( - AccountAuditScope scope) { - return switch (scope) { - case PLATFORM -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; - case TENANT -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; - }; - } - - private static net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus toProtoStatus( - AccountAuditReceiptStatus status) { - return switch (status) { - case COMMITTED -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus - .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED; - case MINIMIZED -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus - .ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED; - case CONFLICT -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus - .ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT; - }; - } - - private static net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome toProtoOutcome( - AccountAuditReceiptOutcome outcome) { - return switch (outcome) { - case ACCEPTED -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome - .ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED; - case DUPLICATE -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome - .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE; - case NON_REPLAYABLE -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome - .ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; - case IDEMPOTENCY_CONFLICT -> - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome - .ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT; - }; + responseObserver.onError( + Status.UNIMPLEMENTED + .withDescription( + "Typed account audit receipt receiver is unavailable in this service revision") + .asRuntimeException()); } @Override @@ -562,19 +315,4 @@ private static void requireAllowlistedInternalService( methodName + " requires an allowlisted internal service caller"); } } - - private void requireAccountAuditCaller(String methodName) { - Set allowedServices = ACCOUNT_AUDIT_CALLER_ALLOWLIST.get(methodName); - GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); - if (allowedServices == null - || peerIdentity == null - || !allowedServices.contains(peerIdentity.service()) - || workloadNamespace == null - || workloadNamespace.isBlank() - || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/" + ACCOUNT_SERVICE) - .equals(peerIdentity.uri())) { - throw new AdminAuthorizationException( - methodName + " requires an allowlisted account-service mTLS peer"); - } - } } diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql deleted file mode 100644 index 4e1a61f25a..0000000000 --- a/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql +++ /dev/null @@ -1,47 +0,0 @@ -CREATE TABLE account_audit_receipts ( - id BIGSERIAL PRIMARY KEY, - receipt_id UUID NOT NULL UNIQUE, - scope VARCHAR(16) NOT NULL, - tenant_id BIGINT, - tenant_key BIGINT NOT NULL, - audit_event_id VARCHAR(36) NOT NULL, - producer_service TEXT NOT NULL, - event_type TEXT NOT NULL, - occurred_at_seconds BIGINT NOT NULL, - occurred_at_nanos INTEGER NOT NULL, - schema_version INTEGER NOT NULL, - payload_digest_version INTEGER NOT NULL, - payload_digest TEXT NOT NULL, - payload BYTEA, - status VARCHAR(16) NOT NULL, - outcome VARCHAR(32) NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT chk_account_audit_receipt_scope - CHECK ( - (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) - OR ( - scope = 'tenant' - AND tenant_id IS NOT NULL - AND tenant_id > 0 - AND tenant_key = tenant_id - ) - ), - CONSTRAINT chk_account_audit_receipt_occurred_at_nanos - CHECK (occurred_at_nanos BETWEEN 0 AND 999999999), - CONSTRAINT chk_account_audit_receipt_versions - CHECK (schema_version > 0 AND payload_digest_version = 1), - CONSTRAINT chk_account_audit_receipt_digest - CHECK (payload_digest LIKE 'sha256:%' AND length(payload_digest) = 71), - CONSTRAINT chk_account_audit_receipt_terminal_state - CHECK ( - (status = 'COMMITTED' AND outcome IN ('ACCEPTED', 'DUPLICATE') AND payload IS NOT NULL) - OR (status = 'MINIMIZED' AND outcome = 'NON_REPLAYABLE' AND payload IS NULL) - ) -); - -CREATE UNIQUE INDEX uq_account_audit_receipt_identity - ON account_audit_receipts (scope, tenant_key, audit_event_id); - -CREATE INDEX idx_account_audit_receipts_tenant_event - ON account_audit_receipts (tenant_id, audit_event_id) - WHERE scope = 'tenant'; diff --git a/services/logging-admin-service/src/main/resources/db/migration/V3__account_audit_receipt_projection.sql b/services/logging-admin-service/src/main/resources/db/migration/V3__account_audit_receipt_projection.sql deleted file mode 100644 index c0d9144b4e..0000000000 --- a/services/logging-admin-service/src/main/resources/db/migration/V3__account_audit_receipt_projection.sql +++ /dev/null @@ -1,68 +0,0 @@ -ALTER TABLE log_events - ALTER COLUMN tenant_id DROP NOT NULL; - -ALTER TABLE log_events - ADD COLUMN scope VARCHAR(16) NOT NULL DEFAULT 'tenant', - ADD COLUMN audit_event_id VARCHAR(36), - ADD COLUMN tenant_key BIGINT NOT NULL DEFAULT 0; - -ALTER TABLE log_events - ADD CONSTRAINT chk_log_events_scope_tenant - CHECK ( - (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) - OR ( - scope = 'tenant' - AND tenant_id IS NOT NULL - AND ( - (audit_event_id IS NOT NULL AND tenant_key = tenant_id) - OR (audit_event_id IS NULL AND tenant_key IN (0, tenant_id)) - ) - ) - ); - -CREATE UNIQUE INDEX uq_log_events_account_audit_identity - ON log_events (scope, tenant_key, audit_event_id); - -ALTER TABLE account_audit_receipts - ADD COLUMN log_event_id BIGINT; - -INSERT INTO log_events ( - scope, - tenant_id, - tenant_key, - audit_event_id, - type, - message, - timestamp, - account_id -) -SELECT receipt.scope, - receipt.tenant_id, - receipt.tenant_key, - receipt.audit_event_id, - 'ACCOUNT_AUDIT', - 'Account audit event ' || receipt.audit_event_id, - TIMESTAMP '1970-01-01 00:00:00' - + receipt.occurred_at_seconds * INTERVAL '1' SECOND - + (receipt.occurred_at_nanos / 1000) * INTERVAL '0.000001' SECOND, - NULL -FROM account_audit_receipts AS receipt; - -UPDATE account_audit_receipts AS receipt -SET log_event_id = ( - SELECT event.id - FROM log_events AS event - WHERE event.scope = receipt.scope - AND event.tenant_key = receipt.tenant_key - AND event.audit_event_id = receipt.audit_event_id -); - -ALTER TABLE account_audit_receipts - ALTER COLUMN log_event_id SET NOT NULL; - -ALTER TABLE account_audit_receipts - ADD CONSTRAINT uq_account_audit_receipts_log_event_id UNIQUE (log_event_id); - -ALTER TABLE account_audit_receipts - ADD CONSTRAINT fk_account_audit_receipts_log_event_id - FOREIGN KEY (log_event_id) REFERENCES log_events (id); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 7c263e4659..e9cfceb262 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -1,56 +1,24 @@ package net.firedevops.firemud.loggingadmin; -import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; -import static net.firedevops.firemud.loggingadmin.jooq.tables.LogEvents.LOG_EVENTS; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import com.google.protobuf.ByteString; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Duration; -import java.time.Instant; -import java.time.LocalDateTime; -import java.util.HexFormat; import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import javax.sql.DataSource; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.loggingadmin.client.AccountClient; import net.firedevops.firemud.loggingadmin.client.GameSessionClient; import net.firedevops.firemud.loggingadmin.client.GameSessionControlPlaneClient; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; -import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.dto.QueryLogsRequest; -import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; -import net.firedevops.firemud.loggingadmin.jooq.tables.records.LogEventsRecord; -import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; -import net.firedevops.firemud.loggingadmin.service.LogEventService; -import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; -import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpHeaders; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; @@ -103,463 +71,6 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private GameSessionControlPlaneClient gameSessionControlPlaneClient; - @Autowired private DSLContext dsl; - @Autowired private DataSource dataSource; - @Autowired private LogEventService logEventService; - @Autowired private LogQueryService logQueryService; - - @Test - void accountAuditReceiptAndProjectionShareStableIdentityAcrossRetryAndConflict() { - String eventId = "82a6f475-0baa-4fd0-a86b-580f286a9940"; - String payload = "{\"accountId\":91,\"auditMarker\":\"tenant-retry-proof\"}"; - CreateLogEventRequest request = tenantAuditRequest(eventId, payload); - - var accepted = logEventService.createLogEvent(request); - var duplicate = logEventService.createLogEvent(request); - var conflict = - logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"changed\":true}")); - - assertThat(accepted.status()).isEqualTo(AccountAuditReceiptStatus.COMMITTED); - assertThat(accepted.outcome()).isEqualTo(AccountAuditReceiptOutcome.ACCEPTED); - assertThat(duplicate.outcome()).isEqualTo(AccountAuditReceiptOutcome.DUPLICATE); - assertThat(duplicate.receiptId()).isEqualTo(accepted.receiptId()); - assertThat(duplicate.logEventId()).isEqualTo(accepted.logEventId()); - assertThat(conflict.status()).isEqualTo(AccountAuditReceiptStatus.CONFLICT); - assertThat(conflict.outcome()).isEqualTo(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); - assertThat(conflict.logEventId()).isEqualTo(accepted.logEventId()); - - LogEventsRecord projection = - dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(accepted.logEventId())).fetchOne(); - AccountAuditReceiptsRecord receipt = - dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) - .where(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId)) - .fetchOne(); - assertThat(projection).isNotNull(); - assertThat(projection.getScope()).isEqualTo("tenant"); - assertThat(projection.getTenantId()).isEqualTo(42L); - assertThat(projection.getAuditEventId()).isEqualTo(eventId); - assertThat(projection.getType()).isEqualTo("ACCOUNT_AUDIT"); - assertThat(projection.getMessage()).isEqualTo("Account audit event " + eventId); - assertThat(projection.getMessage()).doesNotContain("accountId", "tenant-retry-proof"); - assertThat(receipt).isNotNull(); - assertThat(receipt.getLogEventId()).isEqualTo(projection.getId()); - assertThat(receipt.getPayload()).isEqualTo(payload.getBytes(StandardCharsets.UTF_8)); - assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isOne(); - assertThat( - dsl.fetchCount( - ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) - .isOne(); - assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))) - .containsExactly("Account audit event " + eventId); - } - - @Test - void platformAuditProjectionHasNoTenantAndIsExcludedFromTenantQuery() { - String eventId = "41613d4b-3e66-4c9a-9f1c-7e02f54d0c34"; - String marker = "platform-only-marker"; - String payload = "{\"accountId\":92,\"auditMarker\":\"" + marker + "\"}"; - CreateLogEventRequest request = platformAuditRequest(eventId, payload); - - var accepted = logEventService.createLogEvent(request); - - LogEventsRecord projection = - dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(accepted.logEventId())).fetchOne(); - assertThat(projection).isNotNull(); - assertThat(projection.getScope()).isEqualTo("platform"); - assertThat(projection.getTenantId()).isNull(); - assertThat(projection.getAuditEventId()).isEqualTo(eventId); - assertThat(projection.getMessage()).isEqualTo("Account audit event " + eventId); - assertThat(projection.getMessage()).doesNotContain(marker); - assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))).isEmpty(); - } - - @Test - void receiptFailureRollsBackTheAlreadyInsertedAuditProjection() { - String eventId = "f15e1f7a-f2ee-4f90-b83d-77695bcac86c"; - dsl.execute( - "CREATE OR REPLACE FUNCTION fail_test_account_audit_receipt() RETURNS trigger " - + "LANGUAGE plpgsql AS $$ BEGIN IF NEW.audit_event_id = '" - + eventId - + "' THEN RAISE EXCEPTION 'injected receipt insert failure'; END IF; RETURN NEW; END $$"); - dsl.execute( - "CREATE TRIGGER fail_test_account_audit_receipt BEFORE INSERT ON account_audit_receipts " - + "FOR EACH ROW EXECUTE FUNCTION fail_test_account_audit_receipt()"); - try { - assertThatThrownBy( - () -> - logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"accountId\":93}"))) - .isInstanceOf(AuditStorageUnavailableException.class); - assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isZero(); - assertThat( - dsl.fetchCount( - ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) - .isZero(); - } finally { - dsl.execute( - "DROP TRIGGER IF EXISTS fail_test_account_audit_receipt ON account_audit_receipts"); - dsl.execute("DROP FUNCTION IF EXISTS fail_test_account_audit_receipt()"); - } - } - - @Test - void concurrentExactRetriesCreateOneProjectionAndReturnTheSameIdentifiers() throws Exception { - String eventId = "4b7d9ee5-62f5-44dd-8b35-dcf6490d7404"; - CreateLogEventRequest request = tenantAuditRequest(eventId, "{\"accountId\":94}"); - CountDownLatch start = new CountDownLatch(1); - ExecutorService executor = Executors.newFixedThreadPool(2); - try { - Future first = executor.submit(() -> createAfter(start, request)); - Future second = executor.submit(() -> createAfter(start, request)); - start.countDown(); - var firstResult = first.get(20, TimeUnit.SECONDS); - var secondResult = second.get(20, TimeUnit.SECONDS); - - assertThat(firstResult.logEventId()).isEqualTo(secondResult.logEventId()); - assertThat(firstResult.receiptId()).isEqualTo(secondResult.receiptId()); - assertThat(java.util.List.of(firstResult.outcome(), secondResult.outcome())) - .containsExactlyInAnyOrder( - AccountAuditReceiptOutcome.ACCEPTED, AccountAuditReceiptOutcome.DUPLICATE); - assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isOne(); - assertThat( - dsl.fetchCount( - ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) - .isOne(); - } finally { - executor.shutdownNow(); - } - } - - @Test - void v3BackfillsRetainedV2ReceiptsAndKeepsLegacyTenantLogWritesValid() { - String schema = "logging_admin_migration_" + UUID.randomUUID().toString().replace("-", ""); - dsl.execute("CREATE SCHEMA " + schema); - try { - Flyway.configure() - .dataSource(dataSource) - .locations("classpath:db/migration") - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .target(MigrationVersion.fromVersion("2")) - .load() - .migrate(); - - dsl.execute( - "INSERT INTO " - + schema - + ".log_events (tenant_id, type, message, timestamp, account_id) " - + "VALUES (?, ?, ?, ?, ?)", - 73L, - "PAYMENT", - "legacy payment log", - LocalDateTime.of(2025, 3, 1, 12, 0), - 12L); - seedV2Receipt( - schema, - UUID.fromString("30000000-0000-4000-8000-000000000001"), - "tenant", - 73L, - "10000000-0000-4000-8000-000000000001", - Instant.parse("2025-03-01T12:00:01.123456Z"), - false); - seedV2Receipt( - schema, - UUID.fromString("30000000-0000-4000-8000-000000000002"), - "tenant", - 73L, - "10000000-0000-4000-8000-000000000002", - Instant.parse("2025-03-01T12:00:02.987654Z"), - true); - seedV2Receipt( - schema, - UUID.fromString("40000000-0000-4000-8000-000000000001"), - "platform", - null, - "20000000-0000-4000-8000-000000000001", - Instant.parse("2025-03-01T12:00:03.123456Z"), - false); - seedV2Receipt( - schema, - UUID.fromString("40000000-0000-4000-8000-000000000002"), - "platform", - null, - "20000000-0000-4000-8000-000000000002", - Instant.parse("2025-03-01T12:00:04.987654Z"), - true); - - Flyway.configure() - .dataSource(dataSource) - .locations("classpath:db/migration") - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .load() - .migrate(); - - assertThat( - dsl.fetchSingle( - "SELECT COUNT(*) FROM " + schema + ".log_events WHERE message = ?", - "legacy payment log") - .get(0, Integer.class)) - .isEqualTo(1); - assertThat( - dsl.fetchSingle( - "SELECT tenant_key FROM " + schema + ".log_events WHERE message = ?", - "legacy payment log") - .get(0, Long.class)) - .isEqualTo(0L); - assertThat( - dsl.fetchSingle("SELECT COUNT(*) FROM " + schema + ".account_audit_receipts") - .get(0, Integer.class)) - .isEqualTo(4); - assertThat( - dsl.fetchSingle( - "SELECT COUNT(*) FROM " - + schema - + ".account_audit_receipts AS receipt LEFT JOIN " - + schema - + ".log_events AS event ON event.id = receipt.log_event_id " - + "WHERE event.id IS NULL") - .get(0, Integer.class)) - .isEqualTo(0); - assertBackfilledReceipt( - schema, - "30000000-0000-4000-8000-000000000001", - "tenant", - 73L, - "10000000-0000-4000-8000-000000000001", - "COMMITTED", - "ACCEPTED", - "2025-03-01T12:00:01.123456"); - assertBackfilledReceipt( - schema, - "30000000-0000-4000-8000-000000000002", - "tenant", - 73L, - "10000000-0000-4000-8000-000000000002", - "MINIMIZED", - "NON_REPLAYABLE", - "2025-03-01T12:00:02.987654"); - assertBackfilledReceipt( - schema, - "40000000-0000-4000-8000-000000000001", - "platform", - null, - "20000000-0000-4000-8000-000000000001", - "COMMITTED", - "ACCEPTED", - "2025-03-01T12:00:03.123456"); - assertBackfilledReceipt( - schema, - "40000000-0000-4000-8000-000000000002", - "platform", - null, - "20000000-0000-4000-8000-000000000002", - "MINIMIZED", - "NON_REPLAYABLE", - "2025-03-01T12:00:04.987654"); - - dsl.execute( - "INSERT INTO " - + schema - + ".log_events (tenant_id, type, message, timestamp) VALUES (?, ?, ?, ?)", - 84L, - "PAYMENT", - "legacy insert", - LocalDateTime.of(2025, 3, 1, 13, 0)); - Long legacyLogId = - dsl.fetchSingle( - "SELECT id FROM " + schema + ".log_events WHERE message = ?", "legacy insert") - .get("id", Long.class); - assertThat( - dsl.fetchSingle( - "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", legacyLogId) - .get(0, Long.class)) - .isEqualTo(0L); - - dsl.execute( - "UPDATE " + schema + ".log_events SET tenant_id = ? WHERE id = ?", 85L, legacyLogId); - assertThat( - dsl.fetchSingle( - "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", legacyLogId) - .get(0, Long.class)) - .isEqualTo(0L); - - dsl.execute( - "INSERT INTO " - + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES (?, ?, ?, ?, ?, ?)", - "tenant", - 86L, - 86L, - "60000000-0000-4000-8000-000000000001", - "ACCOUNT_AUDIT", - "Account audit event 60000000-0000-4000-8000-000000000001"); - assertThat( - dsl.fetchSingle( - "SELECT tenant_key FROM " + schema + ".log_events WHERE audit_event_id = ?", - "60000000-0000-4000-8000-000000000001") - .get(0, Long.class)) - .isEqualTo(86L); - - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO " - + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES ('tenant', 73, 74, '50000000-0000-4000-8000-000000000001', " - + "'ACCOUNT_AUDIT', 'mismatched key')")) - .isInstanceOf(DataIntegrityViolationException.class) - .hasMessageContaining("chk_log_events_scope_tenant"); - } finally { - dsl.execute("DROP SCHEMA " + schema + " CASCADE"); - } - } - - private void seedV2Receipt( - String schema, - UUID receiptId, - String scope, - Long tenantId, - String eventId, - Instant occurredAt, - boolean minimized) { - byte[] originalPayload = "{\"retained\":true}".getBytes(StandardCharsets.UTF_8); - long tenantKey = tenantId == null ? 0L : tenantId.longValue(); - dsl.execute( - "INSERT INTO " - + schema - + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id, " - + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, schema_version, " - + "payload_digest_version, payload_digest, payload, status, outcome) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - receiptId, - scope, - tenantId, - tenantKey, - eventId, - "account-service", - "ACCOUNT_REGISTRATION", - occurredAt.getEpochSecond(), - occurredAt.getNano(), - 1, - 1, - digest(originalPayload), - minimized ? null : originalPayload, - minimized ? "MINIMIZED" : "COMMITTED", - minimized ? "NON_REPLAYABLE" : "ACCEPTED"); - } - - private void assertBackfilledReceipt( - String schema, - String receiptId, - String scope, - Long tenantId, - String eventId, - String status, - String outcome, - String timestamp) { - var receipt = - dsl.fetchOne( - "SELECT receipt.scope, receipt.tenant_id, receipt.tenant_key, receipt.audit_event_id, " - + "receipt.receipt_id, receipt.producer_service, receipt.event_type, " - + "receipt.occurred_at_seconds, receipt.occurred_at_nanos, receipt.schema_version, " - + "receipt.payload_digest_version, receipt.payload, receipt.payload_digest, " - + "receipt.status, receipt.outcome, receipt.log_event_id, event.id AS projection_id, " - + "event.type, event.message, event.timestamp, event.account_id FROM " - + schema - + ".account_audit_receipts AS receipt JOIN " - + schema - + ".log_events AS event ON event.id = receipt.log_event_id " - + "WHERE receipt.audit_event_id = ?", - eventId); - assertThat(receipt).isNotNull(); - assertThat(receipt.get("scope", String.class)).isEqualTo(scope); - assertThat(receipt.get("tenant_id", Long.class)).isEqualTo(tenantId); - assertThat(receipt.get("tenant_key", Long.class)).isEqualTo(tenantId == null ? 0L : tenantId); - assertThat(receipt.get("audit_event_id", String.class)).isEqualTo(eventId); - assertThat(receipt.get("receipt_id", UUID.class)).isEqualTo(UUID.fromString(receiptId)); - assertThat(receipt.get("producer_service", String.class)).isEqualTo("account-service"); - assertThat(receipt.get("event_type", String.class)).isEqualTo("ACCOUNT_REGISTRATION"); - Instant occurredAt = Instant.parse(timestamp + "Z"); - assertThat(receipt.get("occurred_at_seconds", Long.class)) - .isEqualTo(occurredAt.getEpochSecond()); - assertThat(receipt.get("occurred_at_nanos", Integer.class)).isEqualTo(occurredAt.getNano()); - assertThat(receipt.get("schema_version", Integer.class)).isEqualTo(1); - assertThat(receipt.get("payload_digest_version", Integer.class)).isEqualTo(1); - assertThat(receipt.get("payload_digest", String.class)) - .isEqualTo(digest("{\"retained\":true}".getBytes(StandardCharsets.UTF_8))); - assertThat(receipt.get("status", String.class)).isEqualTo(status); - assertThat(receipt.get("outcome", String.class)).isEqualTo(outcome); - assertThat(receipt.get("log_event_id", Long.class)) - .isEqualTo(receipt.get("projection_id", Long.class)); - assertThat(receipt.get("type", String.class)).isEqualTo("ACCOUNT_AUDIT"); - assertThat(receipt.get("message", String.class)).isEqualTo("Account audit event " + eventId); - assertThat(receipt.get("message", String.class)).doesNotContain("retained"); - assertThat(receipt.get("timestamp", LocalDateTime.class)) - .isEqualTo(LocalDateTime.parse(timestamp)); - assertThat(receipt.get("account_id", Long.class)).isNull(); - assertThat( - dsl.fetchSingle( - "SELECT COUNT(*) FROM " + schema + ".log_events WHERE audit_event_id = ?", - eventId) - .get(0, Integer.class)) - .isEqualTo(1); - if ("MINIMIZED".equals(status)) { - assertThat(receipt.get("payload", byte[].class)).isNull(); - } else { - assertThat(receipt.get("payload", byte[].class)) - .isEqualTo("{\"retained\":true}".getBytes(StandardCharsets.UTF_8)); - } - } - - private AccountAuditReceiptDto createAfter(CountDownLatch start, CreateLogEventRequest request) { - try { - if (!start.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Concurrent audit test did not start"); - } - return logEventService.createLogEvent(request); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Concurrent audit test was interrupted", ex); - } - } - - private static CreateLogEventRequest tenantAuditRequest(String eventId, String payload) { - return auditRequest(AccountAuditScope.TENANT, 42L, eventId, payload); - } - - private static CreateLogEventRequest platformAuditRequest(String eventId, String payload) { - return auditRequest(AccountAuditScope.PLATFORM, null, eventId, payload); - } - - private static CreateLogEventRequest auditRequest( - AccountAuditScope scope, Long tenantId, String eventId, String payload) { - ByteString payloadBytes = ByteString.copyFrom(payload, StandardCharsets.UTF_8); - return new CreateLogEventRequest( - scope, - tenantId, - eventId, - "account-service", - "ACCOUNT_AUDIT_INTEGRATION_TEST", - Instant.parse("2026-09-24T00:00:00Z"), - 1, - payloadBytes, - 1, - digest(payloadBytes.toByteArray())); - } - - private static String digest(byte[] payload) { - try { - return "sha256:" - + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 is unavailable", ex); - } - } - @Test void pingEndpointReturnsPong() throws Exception { String token = diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java deleted file mode 100644 index fe7e669f6b..0000000000 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java +++ /dev/null @@ -1,234 +0,0 @@ -package net.firedevops.firemud.loggingadmin.service.impl; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import com.google.protobuf.ByteString; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Instant; -import java.util.HexFormat; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; -import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; -import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; -import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; -import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -class LogEventServiceImplTest { - private static final String AUDIT_EVENT_ID = "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3"; - private static final UUID RECEIPT_ID = UUID.fromString("c0c1f03b-31b7-4281-aaf8-2d66f29e8770"); - private static final long LOG_EVENT_ID = 192L; - - private final AccountAuditReceiptRepository repository = - Mockito.mock(AccountAuditReceiptRepository.class); - private final LogEventServiceImpl service = new LogEventServiceImpl(repository); - - @Test - void firstWriteReturnsCommittedAcceptedReceipt() { - CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); - AccountAuditReceipt receipt = - receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); - when(repository.insertIfAbsent(eq(request), any(UUID.class))) - .thenReturn(new AccountAuditReceiptInsertResult(receipt, true)); - - var result = service.createLogEvent(request); - - assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); - assertEquals(AccountAuditReceiptOutcome.ACCEPTED, result.outcome()); - assertEquals(LOG_EVENT_ID, result.logEventId()); - verify(repository).insertIfAbsent(eq(request), any(UUID.class)); - } - - @Test - void exactRetryReturnsOriginalReceiptAsDuplicate() { - CreateLogEventRequest request = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); - AccountAuditReceipt receipt = - receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); - when(repository.insertIfAbsent(eq(request), any(UUID.class))) - .thenReturn(new AccountAuditReceiptInsertResult(receipt, false)); - - var result = service.createLogEvent(request); - - assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); - assertEquals(AccountAuditReceiptOutcome.DUPLICATE, result.outcome()); - assertEquals(42L, result.tenantId()); - assertEquals(LOG_EVENT_ID, result.logEventId()); - assertEquals(RECEIPT_ID.toString(), result.receiptId()); - } - - @Test - void changedPayloadReturnsIdempotencyConflict() { - CreateLogEventRequest original = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); - CreateLogEventRequest changed = - request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{\"changed\":true}"); - when(repository.insertIfAbsent(eq(changed), any(UUID.class))) - .thenReturn( - new AccountAuditReceiptInsertResult( - receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), - false)); - - var result = service.createLogEvent(changed); - - assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); - assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); - assertEquals(LOG_EVENT_ID, result.logEventId()); - } - - @Test - void changedImmutableMetadataReturnsIdempotencyConflict() { - CreateLogEventRequest original = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); - CreateLogEventRequest changed = - request(AccountAuditScope.PLATFORM, null, Instant.EPOCH.plusSeconds(1), "{}"); - when(repository.insertIfAbsent(eq(changed), any(UUID.class))) - .thenReturn( - new AccountAuditReceiptInsertResult( - receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), - false)); - - var result = service.createLogEvent(changed); - - assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); - assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); - } - - @Test - void minimizedRetryIsSuccessfulButNonReplayable() { - CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); - when(repository.insertIfAbsent(eq(request), any(UUID.class))) - .thenReturn( - new AccountAuditReceiptInsertResult( - receipt(request, null, "MINIMIZED", "NON_REPLAYABLE"), false)); - - var result = service.createLogEvent(request); - - assertEquals(AccountAuditReceiptStatus.MINIMIZED, result.status()); - assertEquals(AccountAuditReceiptOutcome.NON_REPLAYABLE, result.outcome()); - } - - @Test - void missingReadbackThrowsForCanonicalNotFoundMapping() { - CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); - when(repository.findByIdentity(request, 0L)).thenReturn(Optional.empty()); - - assertThrows(AuditReceiptNotFoundException.class, () -> service.readLogEventReceipt(request)); - } - - @Test - void unsupportedDigestVersionFailsBeforeRepositoryAccess() { - CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); - CreateLogEventRequest unsupported = - new CreateLogEventRequest( - valid.scope(), - valid.tenantId(), - valid.auditEventId(), - valid.producerService(), - valid.eventType(), - valid.occurredAt(), - valid.schemaVersion(), - valid.payload(), - 2, - valid.payloadDigest()); - - assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(unsupported)); - verifyNoInteractions(repository); - } - - @Test - void payloadDigestMismatchFailsBeforeRepositoryAccess() { - CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); - CreateLogEventRequest mismatched = - new CreateLogEventRequest( - valid.scope(), - valid.tenantId(), - valid.auditEventId(), - valid.producerService(), - valid.eventType(), - valid.occurredAt(), - valid.schemaVersion(), - valid.payload(), - valid.payloadDigestVersion(), - "sha256:" + "0".repeat(64)); - - assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(mismatched)); - verifyNoInteractions(repository); - } - - @Test - void invalidUtf8PayloadFailsBeforeRepositoryAccess() { - ByteString payload = ByteString.copyFrom(new byte[] {(byte) 0xff}); - CreateLogEventRequest request = - new CreateLogEventRequest( - AccountAuditScope.PLATFORM, - null, - AUDIT_EVENT_ID, - "account-service", - "ACCOUNT_REGISTERED", - Instant.EPOCH, - 1, - payload, - 1, - digest(payload.toByteArray())); - - assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(request)); - verifyNoInteractions(repository); - } - - private static CreateLogEventRequest request( - AccountAuditScope scope, Long tenantId, Instant occurredAt, String payloadText) { - ByteString payload = ByteString.copyFrom(payloadText, StandardCharsets.UTF_8); - return new CreateLogEventRequest( - scope, - tenantId, - AUDIT_EVENT_ID, - "account-service", - "ACCOUNT_REGISTERED", - occurredAt, - 1, - payload, - 1, - digest(payload.toByteArray())); - } - - private static AccountAuditReceipt receipt( - CreateLogEventRequest request, byte[] payload, String status, String outcome) { - return new AccountAuditReceipt( - 91L, - LOG_EVENT_ID, - RECEIPT_ID, - request.scope().databaseValue(), - request.tenantId(), - request.auditEventId(), - request.producerService(), - request.eventType(), - request.occurredAt().getEpochSecond(), - request.occurredAt().getNano(), - request.schemaVersion(), - request.payloadDigestVersion(), - request.payloadDigest(), - payload, - status, - outcome); - } - - private static String digest(byte[] payload) { - try { - return "sha256:" - + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException(ex); - } - } -} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 2a5c7658ee..068c2e974c 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -1,49 +1,23 @@ package net.firedevops.firemud.loggingadmin.service.impl; -import static org.assertj.core.api.Assertions.assertThat; 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.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; import com.google.protobuf.Timestamp; -import io.grpc.Context; -import io.grpc.Metadata; -import io.grpc.MethodDescriptor; -import io.grpc.ServerCall; -import io.grpc.ServerCallHandler; import io.grpc.Status; -import io.grpc.protobuf.ProtoUtils; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.AuthTokenInterceptor; -import net.firedevops.firemud.common.security.GrpcAuthProperties; import net.firedevops.firemud.common.security.SessionContext; -import net.firedevops.firemud.loggingadmin.config.AccountAuditGrpcAuthConfiguration; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; -import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; -import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; -import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.loggingadmin.service.ModerationService; @@ -55,16 +29,11 @@ import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse; import net.firedevops.firemud.loggingadmin.v1.QueryLogsRequest; import net.firedevops.firemud.loggingadmin.v1.QueryLogsResponse; -import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; -import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; import net.firedevops.firemud.loggingadmin.v1.ToggleFeatureFlagRequest; import net.firedevops.firemud.loggingadmin.v1.ToggleFeatureFlagResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; class LoggingAdminGrpcServiceAuthTest { @AfterEach @@ -72,38 +41,6 @@ void tearDown() { SessionContext.clear(); } - @Test - void auditMethodsBypassJwtRequirementButOtherMethodsRemainProtected() { - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - ConfigurationPropertiesAutoConfiguration.class, - CommonSecurityAutoConfiguration.class)) - .withUserConfiguration(AccountAuditGrpcAuthConfiguration.class) - .withPropertyValues( - "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", - "firemud.auth.grpc.public-methods[0]=logging_admin.v1.LoggingAdminService/Ping") - .run( - context -> { - assertThat(context).hasSingleBean(AuthTokenInterceptor.class); - GrpcAuthProperties properties = context.getBean(GrpcAuthProperties.class); - assertThat(properties.getPublicMethods()) - .containsExactly("logging_admin.v1.LoggingAdminService/Ping"); - AuthTokenInterceptor interceptor = context.getBean(AuthTokenInterceptor.class); - assertTrue( - passesWithoutBearer( - interceptor, "logging_admin.v1.LoggingAdminService/CreateLogEvent")); - assertTrue( - passesWithoutBearer( - interceptor, "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt")); - assertTrue( - passesWithoutBearer(interceptor, "logging_admin.v1.LoggingAdminService/Ping")); - assertFalse( - passesWithoutBearer( - interceptor, "logging_admin.v1.LoggingAdminService/QueryLogs")); - }); - } - @Test void adminMethodsReturnPermissionDeniedErrorDetail() { SessionContext.setContext("1", List.of("player"), Map.of()); @@ -136,165 +73,18 @@ public void onCompleted() {} } @Test - void accountMtlSPeerCreatesReceiptWithoutJwtOrAdminRole() { - LogEventService logEventService = Mockito.mock(LogEventService.class); - ModerationService moderationService = Mockito.mock(ModerationService.class); - String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); - when(logEventService.createLogEvent(any())) - .thenReturn( - new AccountAuditReceiptDto( - AccountAuditScope.PLATFORM, - null, - "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", - "receipt-1", - 77L, - 1, - 1, - digest, - AccountAuditReceiptStatus.COMMITTED, - AccountAuditReceiptOutcome.ACCEPTED)); - LoggingAdminGrpcService service = - new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), - logEventService, - moderationService, - new SimpleMeterRegistry(), - "firemud"); - - AtomicReference ref = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - invokeWithPeer( - "account-service", - () -> service.createLogEvent(validCreateRequest(), responseObserver(ref, error))); - - assertNotNull(ref.get()); - assertEquals("77", ref.get().getLogEventId()); - assertEquals( - net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM, - ref.get().getScope()); - assertEquals( - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus - .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED, - ref.get().getStatus()); - assertEquals( - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome - .ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED, - ref.get().getOutcome()); - assertNull(error.get()); - verify(logEventService).createLogEvent(any()); - verify(moderationService, never()).applyAction(any()); - } - - @Test - void adminJwtClaimsDoNotAuthorizeAuditIngressWithoutAccountPeer() { - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); - LogEventService logEventService = Mockito.mock(LogEventService.class); - LoggingAdminGrpcService service = newService(logEventService); - AtomicReference response = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - - service.createLogEvent(validCreateRequest(), responseObserver(response, error)); - - assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); - verifyNoInteractions(logEventService); - } - - @Test - void jwtClaimNamingAccountServiceCannotOverrideWrongMtlsPeer() { - SessionContext.setContext(null, List.of(), Map.of(), true, "account-service", "instance-1"); - LogEventService logEventService = Mockito.mock(LogEventService.class); - LoggingAdminGrpcService service = newService(logEventService); - AtomicReference response = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - - invokeWithPeer( - "game-session-service", - () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); - - assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); - verifyNoInteractions(logEventService); - } - - @Test - void accountAuditRejectsAccountServicePeerFromOtherNamespace() { - LogEventService logEventService = Mockito.mock(LogEventService.class); - LoggingAdminGrpcService service = newService(logEventService); - AtomicReference response = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - - invokeWithPeer( - "other", - "account-service", - () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); - - assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); - verifyNoInteractions(logEventService); - } - - @Test - void receiptReadReturnsCanonicalNotFoundStatus() { - LogEventService logEventService = Mockito.mock(LogEventService.class); - when(logEventService.readLogEventReceipt(any())).thenThrow(new AuditReceiptNotFoundException()); - LoggingAdminGrpcService service = newService(logEventService); - AtomicReference response = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - - invokeWithPeer( - "account-service", - () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); - - assertEquals(Status.Code.NOT_FOUND, Status.fromThrowable(error.get()).getCode()); - assertNull(response.get()); - } - - @Test - void accountMtlSPeerCanReadTypedReceiptWithoutJwt() { + void createLogEventFailsClosedWithoutInvokingLegacyWriter() { LogEventService logEventService = Mockito.mock(LogEventService.class); - String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); - when(logEventService.readLogEventReceipt(any())) - .thenReturn( - new AccountAuditReceiptDto( - AccountAuditScope.PLATFORM, - null, - "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", - "receipt-1", - 77L, - 1, - 1, - digest, - AccountAuditReceiptStatus.COMMITTED, - AccountAuditReceiptOutcome.DUPLICATE)); - LoggingAdminGrpcService service = newService(logEventService); - AtomicReference response = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - - invokeWithPeer( - "account-service", - () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); - - assertEquals( - net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome - .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE, - response.get().getOutcome()); - assertNull(error.get()); - verify(logEventService).readLogEventReceipt(any()); + assertCreateLogEventUnavailable(validCreateLogEventRequest(), logEventService); } @Test - void auditStorageFailureReturnsCanonicalUnavailableStatus() { + void createLogEventFailsClosedBeforeTypedRequestValidation() { LogEventService logEventService = Mockito.mock(LogEventService.class); - when(logEventService.createLogEvent(any())) - .thenThrow(new AuditStorageUnavailableException(new IllegalStateException("database"))); - LoggingAdminGrpcService service = newService(logEventService); - AtomicReference response = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); + CreateLogEventRequest unsupportedDigestVersion = + validCreateLogEventRequest().toBuilder().setPayloadDigestVersion(2).build(); - invokeWithPeer( - "account-service", - () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); - - assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); - assertNull(response.get()); + assertCreateLogEventUnavailable(unsupportedDigestVersion, logEventService); } @Test @@ -435,25 +225,6 @@ public void onCompleted() {} verifyNoInteractions(logQueryService); } - @Test - void createLogEventMapsUnsupportedDigestVersionRejectionToInvalidArgument() { - LogEventService logEventService = Mockito.mock(LogEventService.class); - when(logEventService.createLogEvent(any())) - .thenThrow(new IllegalArgumentException("payloadDigestVersion must be 1")); - LoggingAdminGrpcService service = newService(logEventService); - - AtomicReference ref = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - CreateLogEventRequest request = - validCreateRequest().toBuilder().setPayloadDigestVersion(2).build(); - invokeWithPeer( - "account-service", () -> service.createLogEvent(request, responseObserver(ref, error))); - - assertEquals(Status.Code.INVALID_ARGUMENT, Status.fromThrowable(error.get()).getCode()); - assertNull(ref.get()); - verify(logEventService).createLogEvent(argThat(dto -> dto.payloadDigestVersion() == 2)); - } - @Test void applyModerationActionRejectsZeroSessionIdBeforeDispatch() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -799,113 +570,55 @@ public void onCompleted() {} verifyNoInteractions(moderationService); } - private static LoggingAdminGrpcService newService(LogEventService logEventService) { - return new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), - logEventService, - Mockito.mock(ModerationService.class), - new SimpleMeterRegistry(), - "firemud"); - } + private static void assertCreateLogEventUnavailable( + CreateLogEventRequest request, LogEventService logEventService) { + ModerationService moderationService = Mockito.mock(ModerationService.class); + LoggingAdminGrpcService service = + new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + logEventService, + moderationService, + new SimpleMeterRegistry()); - private static boolean passesWithoutBearer( - AuthTokenInterceptor interceptor, String fullMethodName) { - MethodDescriptor descriptor = - MethodDescriptor.newBuilder() - .setType(MethodDescriptor.MethodType.UNARY) - .setFullMethodName(fullMethodName) - .setRequestMarshaller(ProtoUtils.marshaller(CreateLogEventRequest.getDefaultInstance())) - .setResponseMarshaller( - ProtoUtils.marshaller(CreateLogEventResponse.getDefaultInstance())) - .build(); - @SuppressWarnings("unchecked") - ServerCall serverCall = - (ServerCall) Mockito.mock(ServerCall.class); - when(serverCall.getMethodDescriptor()).thenReturn(descriptor); - AtomicReference callStarted = new AtomicReference<>(false); - ServerCallHandler next = - (call, headers) -> { - callStarted.set(true); - return new ServerCall.Listener<>() {}; - }; - - interceptor.interceptCall(serverCall, new Metadata(), next); - return callStarted.get(); - } + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + service.createLogEvent( + request, + new StreamObserver<>() { + @Override + public void onNext(CreateLogEventResponse value) { + response.set(value); + } - private static StreamObserver responseObserver( - AtomicReference response, AtomicReference error) { - return new StreamObserver<>() { - @Override - public void onNext(T value) { - response.set(value); - } - - @Override - public void onError(Throwable value) { - error.set(value); - } - - @Override - public void onCompleted() {} - }; - } + @Override + public void onError(Throwable throwable) { + error.set(throwable); + } - private static void invokeWithPeer(String serviceName, Runnable invocation) { - invokeWithPeer("firemud", serviceName, invocation); - } + @Override + public void onCompleted() {} + }); - private static void invokeWithPeer(String namespace, String serviceName, Runnable invocation) { - String uri = "spiffe://firemud/ns/" + namespace + "/sa/" + serviceName; - Context context = - Context.current() - .withValue( - GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, serviceName)); - Context previous = context.attach(); - try { - invocation.run(); - } finally { - context.detach(previous); - } + assertNull(response.get()); + assertNotNull(error.get()); + assertEquals(Status.Code.UNIMPLEMENTED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService, moderationService); } - private static CreateLogEventRequest validCreateRequest() { - ByteString payload = ByteString.copyFrom("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); + private static CreateLogEventRequest validCreateLogEventRequest() { + ByteString payload = ByteString.copyFromUtf8("{}"); return CreateLogEventRequest.newBuilder() .setScope( - net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM) + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantId("1") .setAuditEventId("d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3") .setProducerService("account-service") .setEventType("ACCOUNT_REGISTERED") - .setOccurredAt(Timestamp.newBuilder().setSeconds(1).setNanos(234567890)) + .setOccurredAt(Timestamp.newBuilder().setSeconds(1).build()) .setSchemaVersion(1) .setPayload(payload) .setPayloadDigestVersion(1) - .setPayloadDigest(digest(payload.toByteArray())) + .setPayloadDigest("sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a") .build(); } - - private static ReadLogEventReceiptRequest validReadRequest() { - CreateLogEventRequest create = validCreateRequest(); - return ReadLogEventReceiptRequest.newBuilder() - .setScope(create.getScope()) - .setAuditEventId(create.getAuditEventId()) - .setProducerService(create.getProducerService()) - .setEventType(create.getEventType()) - .setOccurredAt(create.getOccurredAt()) - .setSchemaVersion(create.getSchemaVersion()) - .setPayload(create.getPayload()) - .setPayloadDigestVersion(create.getPayloadDigestVersion()) - .setPayloadDigest(create.getPayloadDigest()) - .build(); - } - - private static String digest(byte[] payload) { - try { - return "sha256:" - + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException(ex); - } - } } From 4340ebaa1c8e9a153339edf09638bb6ceefcb54f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 20:57:49 +1300 Subject: [PATCH 40/55] Align smoke workload identities and document JOIN reconciliation controls --- .../environment-and-secrets-catalog.md | 20 ++- .../account-service/configuration.md | 15 +- dev-tools/certs/ensure-dev-certs.sh | 8 +- dev-tools/tests/compose-grpc-mtls-contract.sh | 128 +++++++++++++----- docker/docker-compose.grpc-mtls.override.yml | 8 +- 5 files changed, 136 insertions(+), 43 deletions(-) diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index 23cd54ce1d..3a80f15a5a 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -18,6 +18,7 @@ JWT implementation drift: the current runtime loads and immediately replaces one - [TLS & Certificates](#tls--certificates) - [Authentication & JWT](#authentication--jwt) - [Service Discovery](#service-discovery) +- [Account JOIN Reconciliation](#account-join-reconciliation) - [Observability](#observability) - [Asset Storage](#asset-storage) - [Backup & Restore Variables](#backup--restore-variables) @@ -214,6 +215,19 @@ Player-facing environments (`hobby-self-hosted`, staging, production) must treat --- +## Account JOIN Reconciliation + +These Account-specific environment variables configure the current scheduled, readback-only reconciliation of uncertain `PENDING` public-production JOIN operations. The defaults below are shared by the normal and production Spring profiles. + +| Variable | Purpose and bounds | Default | +| -------- | ------------------ | ------- | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BATCH_SIZE` | Maximum due operations read back in one job pass; valid range `1..100` | `50` | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_MAX_ATTEMPTS` | Positive diagnostic threshold for unresolved attempts; reaching it does not terminalize an operation | `12` | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_INTERVAL_MS` | Positive fixed delay between scheduled job invocations, in milliseconds | `30000` | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BACKOFF_MS` | Positive delay, in milliseconds, before retrying an unresolved operation | `30000` | + +The attempt threshold only raises diagnostics; it never converts an uncertain `PENDING` operation to a terminal state. Exact readback recovery continues with backoff while the operation remains pending. See [Account Service Configuration: JOIN Reconciliation](../microservices/account-service/configuration.md#join-reconciliation) for the Account-local mapping and consequences. + ## Observability Services are instrumented to create OpenTelemetry spans, but an environment may advertise only a capability level proved end to end under ADR 0017. The collector endpoint can be overridden with the `OTEL_ENDPOINT` environment variable (mapped to the Spring property `otel.endpoint`): @@ -298,12 +312,12 @@ See `../system-architecture-backup-recovery.md` for schedules and retention poli ## Additional Notes -Service-specific settings such as SMTP credentials for the Account Service or `GAME_TICK_DURATION_MS` for the Game Session Service are documented in each service's design README. See the "Environment Variables" sections in: +Service-specific settings remain documented in their service design documents; this catalog also indexes Account's JOIN reconciliation controls above because their diagnostic-only retry threshold needs an explicit operator note. See: -- `../microservices/account-service/README.md#environment-variables` +- [Account Service Configuration: JOIN Reconciliation](../microservices/account-service/configuration.md#join-reconciliation) - `../microservices/game-session-service/README.md#environment-variables` -This catalog covers only shared configuration keys. +This catalog primarily covers shared configuration keys and explicitly indexed service-specific controls. Operational scripts like `dev-tools/restores/restore-cluster.sh` use an optional `FIREMUD_K8S_NAMESPACE` override to target non-default namespaces during restore drills. In normal shared-environment operations, namespace selection should stay aligned with the standard overlay namespace (`firemud`). diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index cfeb4f6035..892a793ebe 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -28,7 +28,7 @@ The current runtime still uses the shared-HMAC compatibility profile for issuanc ## Service-Specific Variables -Additional variables configure outbound email delivery and payment behavior: +Additional variables configure outbound email delivery, payment behavior, and Account's JOIN reconciliation. The reconciliation environment-variable names, defaults, and bounds are maintained in the central [Environment Variables & Secrets Catalog: Account JOIN Reconciliation](../../infrastructure/environment-and-secrets-catalog.md#account-join-reconciliation); the local properties and runtime consequences are summarized below. | Variable | Purpose | Default | | -------- | ------- | ------- | @@ -53,6 +53,19 @@ Additional variables configure outbound email delivery and payment behavior: Changing any of the three JWT lifetime variables—`FIREMUD_AUTH_JWT_EXPIRATION_MS`, `FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS`, or `FIREMUD_ACCOUNT_TOKENS_CONNECT_TOKEN_EXPIRATION_MS`—changes the `exp` claim only for newly issued JWTs; already issued JWTs retain their existing `exp`. `FIREMUD_ACCOUNT_TOKENS_SESSION_EXPIRATION_MS` is only the current default TTL for legacy session records whose writer omits an explicit lifetime; it does not change JWT `exp`, issued-token-registry retention, or gameplay continuity. The current control-ui, player-bootstrap, and connect-token writers pass their corresponding JWT lifetimes directly, which is implementation drift if target convergence requires one per-token retention rule. `FIREMUD_ACCOUNT_TOKENS_CONNECT_SCOPE_EXPIRATION_MS` separately controls the discovery selector's `connectScopeExpiresAt`; it is not a JWT lifetime, session-record TTL, registry-retention setting, or gameplay-continuity cap. The cleanup margin is applied when new registry records are admitted; it does not change the expiration of existing JWTs or the immutable anchor of an existing gameplay binding. A larger cleanup margin therefore cannot raise the independent gameplay-continuity cap. The separate Account overrides are current runtime controls with target ceilings and startup/preflight proof obligations recorded above; they do not establish target convergence by themselves. +## JOIN Reconciliation + +`AccountJoinReconciliationJob` invokes the bounded, readback-only reconciler on the configured fixed delay. The environment variables in the central catalog map to these Account-local Spring properties: + +| Spring property | Account-local effect | +| --------------- | -------------------- | +| `firemud.account.join-reconciliation.batch-size` | Caps each due-operation readback page. | +| `firemud.account.join-reconciliation.max-attempts` | Raises a diagnostic threshold for unresolved attempts only. | +| `firemud.account.join-reconciliation.interval-ms` | Sets the fixed delay between job invocations. | +| `firemud.account.join-reconciliation.backoff-ms` | Sets the next readback time after an unresolved attempt. | + +Reaching `max-attempts` never terminalizes an uncertain `PENDING` operation: exact readback continues with backoff, and attempt count alone is not evidence of commit or absence. Expiry or unavailable readback likewise does not authorize a membership mutation or an invented terminal outcome. + ## Proto Files The gRPC schemas for this service live in [`protos/account/v1`](../../../../protos/account/v1). Use `./gradlew generateProto` to regenerate Java stubs when the definitions change. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 517de72401..f32032f2a0 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -111,7 +111,10 @@ ensure_compose_mtls_certs() { for service in "${services[@]}"; do local service_dir="$COMPOSE_MTLS_STAGE_DIR/$service" mkdir -m 755 -- "$service_dir" - if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service ]]; then + if [[ "$service" == account-service \ + || "$service" == game-session-service \ + || "$service" == entity-management-service \ + || "$service" == social-groups-service ]]; then "$GENERATOR" --workload \ "$authority_dir/ca.crt" "$authority_dir/ca.key" \ "$service_dir/client.crt" "$service_dir/client.key" dev "$service" @@ -171,7 +174,8 @@ ensure_compose_mtls_certs() { echo "Compose mTLS workload fixture contains an unexpected service directory." >&2 return 1 fi - for service in account-service game-session-service entity-management-service; do + for service in \ + account-service game-session-service entity-management-service social-groups-service; do local san_output uri_sans san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" uri_sans="$(printf '%s\n' "$san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index e622a208cc..2188467178 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -18,18 +18,32 @@ FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ FIREMUD_SMOKE_RUN_ID="$run_id" \ COMPOSE_PROJECT_NAME="$project_name" \ bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" -FIREMUD_SMOKE_TEST_MODE=1 \ -FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ -FIREMUD_SMOKE_RUN_ID="$run_id" \ -COMPOSE_PROJECT_NAME="$project_name" \ - bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" - services=( account-service gateway automation-scripting-service entity-management-service game-design-service game-logic-service game-session-service logging-admin-service social-groups-service tcp-proxy-service world-management-service ) workloads_dir="$fixture_root/workloads" + +snapshot_workloads() { + find "$workloads_dir" -type f -print0 | sort -z \ + | while IFS= read -r -d '' file; do + printf '%s ' "$(stat -c '%a' "$file")" + sha256sum -- "$file" + done +} + +workloads_before_idempotent_readback="$(snapshot_workloads)" +FIREMUD_SMOKE_TEST_MODE=1 \ +FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ +FIREMUD_SMOKE_RUN_ID="$run_id" \ +COMPOSE_PROJECT_NAME="$project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" +[[ "$workloads_before_idempotent_readback" == "$(snapshot_workloads)" ]] || { + echo "Compose mTLS certificate verification changed an existing valid fixture." >&2 + exit 1 +} + [[ "$(stat -c '%a' "$fixture_root")" == 700 ]] [[ "$(stat -c '%a' "$fixture_root/authority")" == 700 ]] [[ "$(stat -c '%a' "$fixture_root/authority/ca.key")" == 600 ]] @@ -79,16 +93,26 @@ for service in "${services[@]}"; do [[ "$cert_public_key" == "$leaf_public_key" ]] done +identity_services=(account-service game-session-service entity-management-service social-groups-service) declare -A identity_fingerprints=() -for service in account-service game-session-service entity-management-service; do +for service in "${identity_services[@]}"; do echo "Checking exact workload identity: $service" san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" - [[ "$san_output" == *"URI:spiffe://firemud/ns/dev/sa/$service"* ]] + uri_sans="$(printf '%s\n' "$san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" + [[ "$uri_sans" == "URI:spiffe://firemud/ns/dev/sa/$service" \ + && "$san_output" == *"DNS:$service"* ]] identity_fingerprints["$service"]="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -fingerprint -sha256)" done -[[ "${identity_fingerprints[account-service]}" != "${identity_fingerprints[game-session-service]}" ]] -[[ "${identity_fingerprints[account-service]}" != "${identity_fingerprints[entity-management-service]}" ]] -[[ "${identity_fingerprints[game-session-service]}" != "${identity_fingerprints[entity-management-service]}" ]] +for ((i = 0; i < ${#identity_services[@]}; i++)); do + for ((j = i + 1; j < ${#identity_services[@]}; j++)); do + left="${identity_services[$i]}" + right="${identity_services[$j]}" + [[ "${identity_fingerprints[$left]}" != "${identity_fingerprints[$right]}" ]] || { + echo "Compose mTLS workloads share a private identity: $left and $right" >&2 + exit 1 + } + done +done echo "Checking canonical Compose entrypoints." mtls_compose="$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml" rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "false"' "$mtls_compose" @@ -131,48 +155,84 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; cp "$ROOT_DIR/.env.sample" "$compose_fixture/docker/compose.env" cp "$ROOT_DIR/.env.sample" "$compose_fixture/.env" - rendered_config="$TEST_ROOT/compose-config.json" + rendered_source_config="$TEST_ROOT/compose-source-config.json" + FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" \ + docker compose --env-file "$compose_fixture/.env" \ + -f "$compose_fixture/docker/docker-compose.yml" \ + -f "$compose_fixture/docker/docker-compose.override.yml" \ + -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ + config --format json >"$rendered_source_config" + rendered_image_config="$TEST_ROOT/compose-image-config.json" FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" SMOKE_IMAGE_TAG=contract \ docker compose --env-file "$compose_fixture/.env" \ -f "$compose_fixture/docker/docker-compose.yml" \ -f "$compose_fixture/docker/docker-compose.override.yml" \ -f "$compose_fixture/docker/docker-compose.smoke-images.override.yml" \ -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ - config --format json >"$rendered_config" - python3 - "$rendered_config" "$fixture_root" <<'PY' + config --format json >"$rendered_image_config" + python3 - "$rendered_source_config" "$rendered_image_config" "$fixture_root" <<'PY' import json import pathlib import sys -config_path, cert_root = sys.argv[1:] -config = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8")) -services = config["services"] +source_config_path, image_config_path, cert_root = sys.argv[1:] app_names = { "account-service", "gateway", "automation-scripting-service", "entity-management-service", "game-design-service", "game-logic-service", "game-session-service", "logging-admin-service", "social-groups-service", "tcp-proxy-service", "world-management-service", } -for name in app_names: - service = services[name] - environment = service.get("environment", {}) - assert environment.get("FIREMUD_GRPC_PLAINTEXT") == "false", name - assert environment.get("GRPC_SERVER_TLS_ENABLED") == "true", name - assert environment.get("FIREMUD_GRPC_CERT_CHAIN_PATH") == "/app/certs/client.crt", name - assert environment.get("FIREMUD_GRPC_PRIVATE_KEY_PATH") == "/app/certs/client.key", name - assert environment.get("FIREMUD_GRPC_CA_CERT_PATH") == "/app/certs/ca.crt", name - mounts = [mount for mount in service.get("volumes", []) if mount.get("target") == "/app/certs"] - assert len(mounts) == 1, name - assert mounts[0]["source"] == f"{cert_root}/workloads/{name}", (name, mounts[0]) - assert mounts[0].get("read_only") is True, name - assert service.get("build") is None, f"image-only proof must not build {name}" -entity_namespace = services["entity-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") -assert entity_namespace == "dev", entity_namespace -assert services["account-service"]["image"].endswith(":contract") -print("Verified Compose mTLS wiring and image-only service configuration.") +for profile, config_path, image_only in ( + ("source", source_config_path, False), + ("images", image_config_path, True), +): + services = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8"))["services"] + for name in app_names: + service = services[name] + environment = service.get("environment", {}) + assert environment.get("FIREMUD_GRPC_PLAINTEXT") == "false", (profile, name) + assert environment.get("GRPC_SERVER_TLS_ENABLED") == "true", (profile, name) + assert environment.get("FIREMUD_GRPC_CERT_CHAIN_PATH") == "/app/certs/client.crt", (profile, name) + assert environment.get("FIREMUD_GRPC_PRIVATE_KEY_PATH") == "/app/certs/client.key", (profile, name) + assert environment.get("FIREMUD_GRPC_CA_CERT_PATH") == "/app/certs/ca.crt", (profile, name) + mounts = [mount for mount in service.get("volumes", []) if mount.get("target") == "/app/certs"] + assert len(mounts) == 1, (profile, name) + assert mounts[0]["source"] == f"{cert_root}/workloads/{name}", (profile, name, mounts[0]) + assert mounts[0].get("read_only") is True, (profile, name) + assert "/authority" not in mounts[0]["source"], (profile, name, mounts[0]) + if image_only: + assert service.get("build") is None, f"image-only proof must not build {name}" + + for name in ("account-service", "entity-management-service", "social-groups-service"): + namespace = services[name]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") + assert namespace == "dev", (profile, name, namespace) + if image_only: + assert services["account-service"]["image"].endswith(":contract") +print("Verified source and image Compose mTLS wiring and workload identities.") PY else echo "Docker Compose unavailable; skipped rendered-configuration assertion." fi +social_groups_leaf="$workloads_dir/social-groups-service/client.crt" +chmod 644 "$social_groups_leaf" +cp -- "$workloads_dir/account-service/client.crt" "$social_groups_leaf" +chmod 444 "$social_groups_leaf" +wrong_leaf_snapshot="$(snapshot_workloads)" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$run_id" \ + COMPOSE_PROJECT_NAME="$project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" \ + >"$TEST_ROOT/wrong-leaf-output" 2>&1; then + echo "Compose mTLS certificate verification accepted the Account leaf for Social Groups." >&2 + exit 1 +fi +rg -Fq 'Compose mTLS workload has the wrong SPIFFE identity: social-groups-service' \ + "$TEST_ROOT/wrong-leaf-output" +[[ "$wrong_leaf_snapshot" == "$(snapshot_workloads)" ]] || { + echo "Compose mTLS certificate verification changed an existing wrong-identity fixture." >&2 + exit 1 +} + echo "Compose gRPC mTLS certificate and wiring contract passed." diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 8e964e51a9..1beda5c42c 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -1,7 +1,7 @@ # Canonical fresh/image/restart smoke profile. This deliberately overrides the -# ordinary local plaintext profile. Account, Game Session, and Entity -# Management receive distinct dev-namespace SPIFFE leaves; the other eight -# local apps share the local client leaf. Each app gets only its scoped +# ordinary local Compose profile. Account, Game Session, Entity Management, and +# Social Groups receive distinct dev-namespace SPIFFE leaves; the other seven +# local apps share the generic client leaf. Each app gets only its scoped # read-only leaf mount and the public CA certificate under /app/certs. The CA # private key stays host-only and is never mounted into an app. x-grpc-mtls-environment: &grpc-mtls-environment @@ -16,6 +16,7 @@ services: account-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/account-service:/app/certs:ro @@ -65,6 +66,7 @@ services: social-groups-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/social-groups-service:/app/certs:ro From 2a9be0b7684b04c44e523d5788d7343566dece0e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:58:22 +1300 Subject: [PATCH 41/55] Reject aliased certificate material and mismatched Compose keys --- dev-tools/certs/clean-dev-certs.sh | 23 ++- dev-tools/certs/ensure-dev-certs.sh | 102 +++++++--- dev-tools/certs/generate-dev-certs.sh | 58 +++++- dev-tools/tests/compose-grpc-mtls-contract.sh | 85 +++++++- ...ocal-compose-workload-identity-contract.sh | 181 ++++++++++++++++++ 5 files changed, 408 insertions(+), 41 deletions(-) diff --git a/dev-tools/certs/clean-dev-certs.sh b/dev-tools/certs/clean-dev-certs.sh index 987d041e27..d4ec9cf709 100644 --- a/dev-tools/certs/clean-dev-certs.sh +++ b/dev-tools/certs/clean-dev-certs.sh @@ -12,10 +12,25 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi -if [[ -L "$CERT_DIR" ]]; then - echo "Refusing symlink certificate directory; preserving it: $CERT_DIR" >&2 - exit 1 -fi +refuse_symlink_path() { + local path="$1" + local description="$2" + local current_path="$path" + + while [[ "$current_path" == */ && "$current_path" != "/" ]]; do + current_path="${current_path%/}" + done + + while [[ "$current_path" != "." && "$current_path" != "/" ]]; do + [[ ! -L "$current_path" ]] || { + echo "Refusing symlinked $description; preserving it: $path" >&2 + exit 1 + } + current_path="$(dirname -- "$current_path")" + done +} + +refuse_symlink_path "$CERT_DIR" "certificate directory" if [ ! -d "$CERT_DIR" ]; then echo "No certificate directory at $CERT_DIR" exit 0 diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index f1a4ee9c05..82fe6e25ab 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -13,6 +13,10 @@ refuse_symlink_path() { local description="$2" local current_path="$path" + while [[ "$current_path" == */ && "$current_path" != "/" ]]; do + current_path="${current_path%/}" + done + while [[ "$current_path" != "." && "$current_path" != "/" ]]; do [[ ! -L "$current_path" ]] || { echo "refusing symlinked $description: $path" >&2 @@ -21,6 +25,48 @@ refuse_symlink_path() { current_path="$(dirname -- "$current_path")" done } + +preflight_managed_file() { + local path="$1" + local description="$2" + local link_count + + refuse_symlink_path "$path" "$description" + [[ -e "$path" ]] || return 0 + [[ -f "$path" ]] || { + echo "refusing non-regular $description: $path" >&2 + exit 1 + } + link_count="$(stat -c '%h' -- "$path")" + if ((link_count > 1)); then + echo "refusing hard-linked $description: $path" >&2 + exit 1 + fi +} + +preflight_managed_directory() { + local path="$1" + local description="$2" + + refuse_symlink_path "$path" "$description" + if [[ -e "$path" && ! -d "$path" ]]; then + echo "refusing non-directory $description: $path" >&2 + exit 1 + fi +} + +certificate_matches_private_key() { + local certificate="$1" + local private_key="$2" + local certificate_public_key private_key_public_key + + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ + | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null)" || return 1 + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null)" || return 1 + [[ -n "$certificate_public_key" && "$certificate_public_key" == "$private_key_public_key" ]] +} + COMPOSE_MTLS_STAGE_ROOT="" COMPOSE_MTLS_STAGE_DIR="" @@ -68,21 +114,28 @@ ensure_compose_mtls_certs() { echo "Compose mTLS authority path must be a real directory." >&2 return 1 fi + preflight_managed_directory "$authority_dir" "Compose mTLS authority directory" + local authority_file + for authority_file in ca.crt ca.key client.crt client.key; do + preflight_managed_file "$authority_dir/$authority_file" "Compose mTLS authority material" + done + if [[ ! -f "$authority_dir/ca.crt" || ! -f "$authority_dir/ca.key" || ! -f "$authority_dir/client.crt" || ! -f "$authority_dir/client.key" ]]; then + if [[ -n "$(find "$authority_dir" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then + echo "Compose mTLS authority fixture is incomplete; refusing to replace existing material." >&2 + return 1 + fi + fi chmod 700 "$authority_dir" if [[ "$(stat -Lc '%u %a %F' "$authority_dir")" != "$owner_id 700 directory" ]]; then echo "Compose mTLS authority fixture must be an owner-only (0700) directory." >&2 return 1 fi if [[ ! -f "$authority_dir/ca.crt" || ! -f "$authority_dir/ca.key" || ! -f "$authority_dir/client.crt" || ! -f "$authority_dir/client.key" ]]; then - if [[ -n "$(find "$authority_dir" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then - echo "Compose mTLS authority fixture is incomplete; refusing to replace existing material." >&2 - return 1 - fi (umask 077; "$GENERATOR" "$authority_dir") fi - local authority_file for authority_file in ca.crt ca.key client.crt client.key; do - if [[ -L "$authority_dir/$authority_file" || ! -f "$authority_dir/$authority_file" ]]; then + preflight_managed_file "$authority_dir/$authority_file" "Compose mTLS authority material" + if [[ ! -f "$authority_dir/$authority_file" ]]; then echo "Compose mTLS authority fixture is missing a regular $authority_file file." >&2 return 1 fi @@ -161,6 +214,10 @@ ensure_compose_mtls_certs() { return 1 fi openssl verify -CAfile "$service_dir/ca.crt" "$service_dir/client.crt" >/dev/null + if ! certificate_matches_private_key "$service_dir/client.crt" "$service_dir/client.key"; then + echo "Compose mTLS workload certificate and private key do not match: $service" >&2 + return 1 + fi done local found_service_count=0 entry for entry in "$workloads_dir"/*; do @@ -201,27 +258,20 @@ if [[ "${1:-}" == "--compose-mtls" ]]; then exit $? fi -required_files=( - "$CERT_DIR/ca.crt" - "$CERT_DIR/ca.key" - "$CERT_DIR/client.crt" - "$CERT_DIR/client.key" - "$CERT_DIR/dev-ca.pem" - "$CERT_DIR/dev-cert.pem" - "$CERT_DIR/dev-key.pem" - "$CERT_DIR/server.crt" - "$CERT_DIR/server.key" +managed_source_files=( + ca.crt ca.key ca.srl client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem + server.crt server.key server.csr dev-cert.cnf ) -refuse_symlink_path "$CERT_DIR" "certificate directory" -for file in "${required_files[@]}"; do - refuse_symlink_path "$file" "certificate material" +preflight_managed_directory "$CERT_DIR" "certificate directory" +for filename in "${managed_source_files[@]}"; do + preflight_managed_file "$CERT_DIR/$filename" "certificate material" done -refuse_symlink_path "$WORKLOAD_DIR" "workload certificate directory" +preflight_managed_directory "$WORKLOAD_DIR" "workload certificate directory" for workload in account-service game-session-service social-groups-service; do - refuse_symlink_path "$WORKLOAD_DIR/$workload.crt" "workload certificate output" - refuse_symlink_path "$WORKLOAD_DIR/$workload.key" "workload private-key output" + preflight_managed_file "$WORKLOAD_DIR/$workload.crt" "workload certificate output" + preflight_managed_file "$WORKLOAD_DIR/$workload.key" "workload private-key output" done refuse_symlink_path "$RUNTIME_DIR" "local Compose runtime projection" @@ -252,7 +302,7 @@ workload_certificate_is_valid() { local certificate="$WORKLOAD_DIR/$workload.crt" local private_key="$WORKLOAD_DIR/$workload.key" local expected_uri="spiffe://firemud/ns/$WORKLOAD_NAMESPACE/sa/$workload" - local subject_alt_names uri_sans certificate_public_key private_key_public_key + local subject_alt_names uri_sans [[ -f "$certificate" && -f "$private_key" ]] || return 1 openssl verify -purpose sslclient -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || return 1 @@ -260,11 +310,7 @@ workload_certificate_is_valid() { subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName 2>/dev/null)" || return 1 uri_sans="$(printf '%s\n' "$subject_alt_names" | grep -oE 'URI:[^,[:space:]]+' || true)" [[ "$uri_sans" == "URI:$expected_uri" && "$subject_alt_names" == *"DNS:$workload"* ]] || return 1 - certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout \ - | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null)" || return 1 - private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER 2>/dev/null \ - | openssl dgst -sha256 2>/dev/null)" || return 1 - [[ -n "$certificate_public_key" && "$certificate_public_key" == "$private_key_public_key" ]] + certificate_matches_private_key "$certificate" "$private_key" } for workload in "${workloads[@]}"; do diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 359d940bb2..abf1b0ed89 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -8,6 +8,10 @@ refuse_symlink_path() { local description="$2" local current_path="$path" + while [[ "$current_path" == */ && "$current_path" != "/" ]]; do + current_path="${current_path%/}" + done + while [[ "$current_path" != "." && "$current_path" != "/" ]]; do [[ ! -L "$current_path" ]] || { echo "refusing symlinked $description: $path" >&2 @@ -17,6 +21,39 @@ refuse_symlink_path() { done } +preflight_managed_file() { + local path="$1" + local description="$2" + local link_count + + refuse_symlink_path "$path" "$description" + [[ -e "$path" ]] || return 0 + [[ -f "$path" ]] || { + echo "refusing non-regular $description: $path" >&2 + exit 1 + } + link_count="$(stat -c '%h' -- "$path")" + if ((link_count > 1)); then + echo "refusing hard-linked $description: $path" >&2 + exit 1 + fi +} + +preflight_managed_directory() { + local path="$1" + local description="$2" + + refuse_symlink_path "$path" "$description" + if [[ -e "$path" && ! -d "$path" ]]; then + echo "refusing non-directory $description: $path" >&2 + exit 1 + fi +} + +paths_are_same_file() { + [[ "$1" == "$2" ]] || { [[ -e "$1" && -e "$2" ]] && [[ "$1" -ef "$2" ]]; } +} + if [[ "${1:-}" == "--workload" ]]; then umask 077 if [[ $# -ne 7 ]]; then @@ -30,10 +67,19 @@ if [[ "${1:-}" == "--workload" ]]; then output_key="$5" runtime_namespace="$6" workload="$7" - refuse_symlink_path "$ca_cert" "certificate authority source" - refuse_symlink_path "$ca_key" "certificate authority source" - refuse_symlink_path "$output_cert" "workload certificate output" - refuse_symlink_path "$output_key" "workload private-key output" + preflight_managed_file "$ca_cert" "certificate authority source" + preflight_managed_file "$ca_key" "certificate authority source" + preflight_managed_file "$output_cert" "workload certificate output" + preflight_managed_file "$output_key" "workload private-key output" + if paths_are_same_file "$ca_cert" "$ca_key" \ + || paths_are_same_file "$output_cert" "$output_key" \ + || paths_are_same_file "$output_cert" "$ca_cert" \ + || paths_are_same_file "$output_cert" "$ca_key" \ + || paths_are_same_file "$output_key" "$ca_cert" \ + || paths_are_same_file "$output_key" "$ca_key"; then + echo "certificate authority sources and workload outputs must be distinct paths." >&2 + exit 1 + fi for required_file in "$ca_cert" "$ca_key"; do [[ -f "$required_file" ]] || { echo "missing certificate authority file: $required_file" >&2 @@ -105,13 +151,13 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi -refuse_symlink_path "$CERT_DIR" "certificate directory" generated_files=( ca.crt ca.key ca.srl client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem server.crt server.key server.csr dev-cert.cnf ) +preflight_managed_directory "$CERT_DIR" "certificate directory" for filename in "${generated_files[@]}"; do - refuse_symlink_path "$CERT_DIR/$filename" "certificate material" + preflight_managed_file "$CERT_DIR/$filename" "certificate material" done if [[ -d "$CERT_DIR" ]]; then while IFS= read -r -d '' symlink_path; do diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 13ac1885f4..86ee858134 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -28,7 +28,7 @@ workloads_dir="$fixture_root/workloads" snapshot_workloads() { find "$workloads_dir" -type f -print0 | sort -z \ | while IFS= read -r -d '' file; do - printf '%s ' "$(stat -c '%a' "$file")" + printf '%s ' "$(stat -c '%a %h' "$file")" sha256sum -- "$file" done } @@ -69,6 +69,58 @@ if FIREMUD_SMOKE_TEST_MODE=1 \ fi rg -Fq 'Compose mTLS workloads path must be a real directory.' "$TEST_ROOT/symlink-output" +authority_hardlink_run_id="${run_id}-authority-hardlink" +authority_hardlink_project_name="firemud-smoke-$authority_hardlink_run_id" +authority_hardlink_project_key="$(printf '%s' "$authority_hardlink_project_name" | sha256sum | awk '{print $1}')" +authority_hardlink_fixture="$ownership_dir/$authority_hardlink_project_key.grpc-mtls" +authority_hardlink_dir="$authority_hardlink_fixture/authority" +authority_hardlink_key="$authority_hardlink_dir/ca.key" +authority_hardlink_sentinel="$authority_hardlink_dir/ca-key-alias-sentinel" +mkdir -m 700 -- "$authority_hardlink_fixture" +mkdir -m 711 -- "$authority_hardlink_dir" +for file in ca.crt ca.key client.crt client.key; do + cp -- "$fixture_root/authority/$file" "$authority_hardlink_dir/$file" +done +cp -- "$authority_hardlink_key" "$authority_hardlink_sentinel" +chmod 640 "$authority_hardlink_sentinel" +rm -- "$authority_hardlink_key" +ln -- "$authority_hardlink_sentinel" "$authority_hardlink_key" + +snapshot_authority_sources() { + find "$authority_hardlink_dir" -maxdepth 1 -type f -print0 | sort -z \ + | while IFS= read -r -d '' file; do + printf '%s ' "$(stat -c '%a %h' "$file")" + sha256sum -- "$file" + done +} + +authority_before_hardlink_refusal="$(snapshot_authority_sources)" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$authority_hardlink_run_id" \ + COMPOSE_PROJECT_NAME="$authority_hardlink_project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$authority_hardlink_fixture" \ + >"$TEST_ROOT/authority-hardlink-output" 2>&1; then + echo "Compose mTLS certificate setup accepted a hard-linked authority key." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked Compose mTLS authority material: $authority_hardlink_key" \ + "$TEST_ROOT/authority-hardlink-output" +[[ "$authority_before_hardlink_refusal" == "$(snapshot_authority_sources)" \ + && "$(stat -c '%a' "$authority_hardlink_dir")" == 711 \ + && ! -e "$authority_hardlink_fixture/workloads" ]] || { + echo "Compose mTLS authority preflight partially changed hard-linked source material." >&2 + exit 1 +} +[[ "$(<"$authority_hardlink_sentinel")" == "$(<"$fixture_root/authority/ca.key")" ]] || { + echo "Compose mTLS authority preflight changed the hard-link sentinel contents." >&2 + exit 1 +} +[[ "$(stat -c '%a' "$authority_hardlink_sentinel")" == 640 ]] || { + echo "Compose mTLS authority preflight changed the hard-link sentinel mode." >&2 + exit 1 +} + public_key_digest() { local cert_or_key="$1" kind="$2" if [[ "$kind" == certificate ]]; then @@ -222,10 +274,37 @@ else echo "Docker Compose unavailable; skipped rendered-configuration assertion." fi +social_groups_key="$workloads_dir/social-groups-service/client.key" +social_groups_key_backup="$TEST_ROOT/social-groups-client-key.backup" +cp -- "$social_groups_key" "$social_groups_key_backup" +chmod 644 "$social_groups_key" +cp -- "$workloads_dir/account-service/client.key" "$social_groups_key" +chmod 444 "$social_groups_key" +mismatched_key_snapshot="$(snapshot_workloads)" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$run_id" \ + COMPOSE_PROJECT_NAME="$project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" \ + >"$TEST_ROOT/mismatched-key-output" 2>&1; then + echo "Compose mTLS certificate verification accepted a mismatched certificate/key pair." >&2 + exit 1 +fi +rg -Fq 'Compose mTLS workload certificate and private key do not match: social-groups-service' \ + "$TEST_ROOT/mismatched-key-output" +[[ "$mismatched_key_snapshot" == "$(snapshot_workloads)" ]] || { + echo "Compose mTLS verification changed an existing mismatched fixture." >&2 + exit 1 +} +chmod 644 "$social_groups_key" +cp -- "$social_groups_key_backup" "$social_groups_key" +chmod 444 "$social_groups_key" + social_groups_leaf="$workloads_dir/social-groups-service/client.crt" -chmod 644 "$social_groups_leaf" +chmod 644 "$social_groups_leaf" "$social_groups_key" cp -- "$workloads_dir/account-service/client.crt" "$social_groups_leaf" -chmod 444 "$social_groups_leaf" +cp -- "$workloads_dir/account-service/client.key" "$social_groups_key" +chmod 444 "$social_groups_leaf" "$social_groups_key" wrong_leaf_snapshot="$(snapshot_workloads)" if FIREMUD_SMOKE_TEST_MODE=1 \ FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index e72fd7db91..dde8e8611d 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -193,6 +193,15 @@ hardlink_before="$CERT_DIR/hardlink-projection-before.sha256" hardlink_after="$CERT_DIR/hardlink-projection-after.sha256" snapshot_runtime_projection() { + local root="$1" + local file + while IFS= read -r -d '' file; do + printf '%s ' "$(stat -c '%a %h' "$file")" + sha256sum -- "$file" + done < <(find "$root" -type f -print0 | sort -z) +} + +snapshot_certificate_tree() { local root="$1" local file while IFS= read -r -d '' file; do @@ -228,6 +237,137 @@ cmp -s "$hardlink_before" "$hardlink_after" || { } assert_mode 640 "$hardlink_sentinel" +# Ensure preflights every managed source before the generic CA-key chmod or a +# missing workload-pair regeneration can alter either side of a hard link. +source_hardlink_case="$CERT_DIR/hardlink-source-case" +copy_generic_bundle "$CERT_DIR" "$source_hardlink_case" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$source_hardlink_case" +source_hardlink_key="$source_hardlink_case/workloads/game-session-service.key" +source_hardlink_certificate="$source_hardlink_case/workloads/game-session-service.crt" +source_hardlink_sentinel="$source_hardlink_case/source-key-alias-sentinel" +source_hardlink_output="$CERT_DIR/hardlink-source-output" +printf 'external source-key sentinel\n' >"$source_hardlink_sentinel" +chmod 640 "$source_hardlink_sentinel" +rm -- "$source_hardlink_key" "$source_hardlink_certificate" +ln -- "$source_hardlink_sentinel" "$source_hardlink_key" +chmod 644 "$source_hardlink_case/ca.key" +source_hardlink_before="$(snapshot_certificate_tree "$source_hardlink_case")" +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$source_hardlink_case" \ + >"$source_hardlink_output" 2>&1; then + echo "ensure-dev-certs accepted a hard-linked workload source key." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked workload private-key output: $source_hardlink_key" \ + "$source_hardlink_output" +[[ "$source_hardlink_before" == "$(snapshot_certificate_tree "$source_hardlink_case")" \ + && "$(<"$source_hardlink_sentinel")" == 'external source-key sentinel' ]] || { + echo "ensure-dev-certs partially changed a hard-linked workload source or another managed file." >&2 + exit 1 +} +assert_mode 640 "$source_hardlink_sentinel" +assert_mode 644 "$source_hardlink_case/ca.key" + +# The standalone generic generator must reject a hard-linked output before an +# incomplete bundle can rotate or overwrite any of its remaining material. +generator_hardlink_case="$CERT_DIR/generator-hardlink-case" +copy_generic_bundle "$CERT_DIR" "$generator_hardlink_case" +generator_hardlink_key="$generator_hardlink_case/server.key" +generator_hardlink_sentinel="$generator_hardlink_case/server-key-alias-sentinel" +generator_hardlink_output="$CERT_DIR/generator-hardlink-output" +cp -- "$generator_hardlink_key" "$generator_hardlink_sentinel" +chmod 640 "$generator_hardlink_sentinel" +rm -- "$generator_hardlink_key" "$generator_hardlink_case/dev-key.pem" +ln -- "$generator_hardlink_sentinel" "$generator_hardlink_key" +generator_hardlink_before="$(snapshot_certificate_tree "$generator_hardlink_case")" +if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" "$generator_hardlink_case" \ + >"$generator_hardlink_output" 2>&1; then + echo "generate-dev-certs accepted a hard-linked managed certificate output." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked certificate material: $generator_hardlink_key" \ + "$generator_hardlink_output" +[[ "$generator_hardlink_before" == "$(snapshot_certificate_tree "$generator_hardlink_case")" ]] || { + echo "generate-dev-certs partially changed an incomplete hard-linked bundle." >&2 + exit 1 +} +assert_mode 640 "$generator_hardlink_sentinel" + +# The standalone workload signer preflights both read-only CA inputs and its +# certificate/key outputs before it creates either output. +workload_source_case="$CERT_DIR/generator-workload-source-case" +mkdir -p "$workload_source_case/output" +cp -- "$CERT_DIR/ca.crt" "$workload_source_case/ca.crt" +cp -- "$CERT_DIR/ca.key" "$workload_source_case/ca-key-sentinel" +chmod 640 "$workload_source_case/ca-key-sentinel" +ln -- "$workload_source_case/ca-key-sentinel" "$workload_source_case/ca.key" +workload_source_before="$(snapshot_certificate_tree "$workload_source_case")" +workload_source_output="$CERT_DIR/generator-workload-source-output" +if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$workload_source_case/ca.crt" "$workload_source_case/ca.key" \ + "$workload_source_case/output/client.crt" "$workload_source_case/output/client.key" \ + local account-service >"$workload_source_output" 2>&1; then + echo "generate-dev-certs accepted a hard-linked workload CA source." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked certificate authority source: $workload_source_case/ca.key" \ + "$workload_source_output" +[[ "$workload_source_before" == "$(snapshot_certificate_tree "$workload_source_case")" \ + && ! -e "$workload_source_case/output/client.crt" \ + && ! -e "$workload_source_case/output/client.key" ]] || { + echo "generate-dev-certs partially changed output after rejecting a hard-linked CA source." >&2 + exit 1 +} +assert_mode 640 "$workload_source_case/ca-key-sentinel" + +workload_output_case="$CERT_DIR/generator-workload-output-case" +mkdir -p "$workload_output_case/ca" "$workload_output_case/output" +cp -- "$CERT_DIR/ca.crt" "$workload_output_case/ca/ca.crt" +cp -- "$CERT_DIR/ca.key" "$workload_output_case/ca/ca.key" +workload_output_sentinel="$workload_output_case/output/key-alias-sentinel" +workload_output_key="$workload_output_case/output/client.key" +printf 'external workload-output sentinel\n' >"$workload_output_sentinel" +chmod 640 "$workload_output_sentinel" +ln -- "$workload_output_sentinel" "$workload_output_key" +workload_output_before="$(snapshot_certificate_tree "$workload_output_case")" +workload_output_output="$CERT_DIR/generator-workload-output-output" +if bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$workload_output_case/ca/ca.crt" "$workload_output_case/ca/ca.key" \ + "$workload_output_case/output/client.crt" "$workload_output_key" \ + local account-service >"$workload_output_output" 2>&1; then + echo "generate-dev-certs accepted a hard-linked workload private-key output." >&2 + exit 1 +fi +rg -Fq "refusing hard-linked workload private-key output: $workload_output_key" \ + "$workload_output_output" +[[ "$workload_output_before" == "$(snapshot_certificate_tree "$workload_output_case")" \ + && ! -e "$workload_output_case/output/client.crt" \ + && "$(<"$workload_output_sentinel")" == 'external workload-output sentinel' ]] || { + echo "generate-dev-certs partially changed a hard-linked workload output." >&2 + exit 1 +} +assert_mode 640 "$workload_output_sentinel" + +# Present managed paths must be regular files, not directories or other +# special entries that a later generator would partially replace. +invalid_kind_case="$CERT_DIR/non-regular-source-case" +copy_generic_bundle "$CERT_DIR" "$invalid_kind_case" +rm -- "$invalid_kind_case/ca.crt" +mkdir -- "$invalid_kind_case/ca.crt" +invalid_kind_before="$(snapshot_certificate_tree "$invalid_kind_case")" +invalid_kind_output="$CERT_DIR/non-regular-source-output" +if bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$invalid_kind_case" \ + >"$invalid_kind_output" 2>&1; then + echo "ensure-dev-certs accepted a non-regular managed certificate path." >&2 + exit 1 +fi +rg -Fq "refusing non-regular certificate material: $invalid_kind_case/ca.crt" \ + "$invalid_kind_output" +[[ "$invalid_kind_before" == "$(snapshot_certificate_tree "$invalid_kind_case")" \ + && -d "$invalid_kind_case/ca.crt" ]] || { + echo "ensure-dev-certs partially changed an invalid managed source path." >&2 + exit 1 +} + # Unmanaged regular files under workloads/ retain their own bytes and modes; # only the three named local Compose identities are normalized by ensure. mode_case="$CERT_DIR/unmanaged-workload-modes" @@ -519,4 +659,45 @@ cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$symlink_ exit 1 } +ancestor_symlink_case="$CERT_DIR/ancestor-symlink-case" +ancestor_real_parent="$ancestor_symlink_case/real-parent" +ancestor_real_cert_dir="$ancestor_real_parent/cert-dir" +ancestor_alias="$ancestor_symlink_case/alias" +ancestor_alias_cert_dir="$ancestor_alias/cert-dir" +mkdir -p "$ancestor_real_cert_dir" +printf 'protected generated-name sentinel\n' >"$ancestor_real_cert_dir/ca.key" +chmod 640 "$ancestor_real_cert_dir/ca.key" +printf 'protected workload sentinel\n' >"$ancestor_real_cert_dir/workloads.key" +chmod 644 "$ancestor_real_cert_dir/workloads.key" +ln -s "$ancestor_real_parent" "$ancestor_alias" +if cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$ancestor_alias_cert_dir" 2>&1)"; then + echo "certificate cleanup accepted a certificate directory beneath a symlinked ancestor" >&2 + exit 1 +fi +[[ "$cleanup_output" == *"Refusing symlinked certificate directory; preserving it: $ancestor_alias_cert_dir"* \ + && "$(<"$ancestor_real_cert_dir/ca.key")" == 'protected generated-name sentinel' \ + && "$(<"$ancestor_real_cert_dir/workloads.key")" == 'protected workload sentinel' ]] || { + echo "certificate cleanup followed an ancestor symlink or changed protected entries" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} +assert_mode 640 "$ancestor_real_cert_dir/ca.key" +assert_mode 644 "$ancestor_real_cert_dir/workloads.key" + +direct_symlink_alias="$ancestor_symlink_case/direct-alias" +ln -s "$ancestor_real_cert_dir" "$direct_symlink_alias" +if cleanup_output="$(bash "$ROOT_DIR/dev-tools/certs/clean-dev-certs.sh" "$direct_symlink_alias/" 2>&1)"; then + echo "certificate cleanup accepted a symlink directory with a trailing slash" >&2 + exit 1 +fi +[[ "$cleanup_output" == *"Refusing symlinked certificate directory; preserving it: $direct_symlink_alias/"* \ + && "$(<"$ancestor_real_cert_dir/ca.key")" == 'protected generated-name sentinel' \ + && "$(<"$ancestor_real_cert_dir/workloads.key")" == 'protected workload sentinel' ]] || { + echo "certificate cleanup followed a trailing-slash symlink or changed protected entries" >&2 + printf '%s\n' "$cleanup_output" >&2 + exit 1 +} +assert_mode 640 "$ancestor_real_cert_dir/ca.key" +assert_mode 644 "$ancestor_real_cert_dir/workloads.key" + echo "Local Compose workload identity contract passed." From 1314d3cf1fcc5b970056b83d344d022911b99233 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:46:06 +1300 Subject: [PATCH 42/55] Fix Account migration namespace and front identity proof --- .../account-service/runtime-and-data.md | 6 +- .../logging-admin-service/api-contracts.md | 2 + design/grpc-docs/grpc-api.md | 4 +- design/project-management/ai-observations.md | 6 ++ .../player-access-and-session.md | 2 +- dev-tools/certs/ensure-dev-certs.sh | 45 +++++++++-- dev-tools/certs/generate-dev-certs.sh | 4 + dev-tools/tests/compose-grpc-mtls-contract.sh | 81 +++++++++++++++++++ ...ocal-compose-workload-identity-contract.sh | 21 +++++ .../v1/logging_admin_service.proto | 4 + ...l => V38__account_join_reconciliation.sql} | 0 .../AccountMigrationVersionTest.java | 44 ++++++++++ 12 files changed, 206 insertions(+), 13 deletions(-) rename services/account-service/src/main/resources/db/migration/{V28__account_join_reconciliation.sql => V38__account_join_reconciliation.sql} (100%) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 594bacb3bd..7e6a8b43a4 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -30,7 +30,7 @@ The live runtime membership response carries `accountId`, `tenantId`, `membershi Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist, but current connect-token issuance uses membership existence, admission, version, and evaluation-time evidence without enforcing the emitted lifecycle or authority-generation fields. It does not yet validate the full private/playtest target or perform the required membership-version/generation baseline reread at issuance; a replay-cache hit also returns before fresh authority reads. Character discovery applies its local membership/admission checks after entitlement and target checks. These paths do not create or restore membership. -Account owns the explicit `JoinPublicProductionMembership` writer and HTTP controller, and Game Session's direct text `JOIN` dispatcher is implemented locally; the Gateway guard blocks external exposure of the Account HTTP route and first-party `Join & Play` remains unavailable. A `PENDING` intent persists before entitlement work; unavailable or expired-scope attempts remain retryable `AUTH_UNAVAILABLE` with no fabricated policy evidence. The bounded Account worker is readback-only and terminalizes only exact positive operation, scope, membership, and audit evidence; absent or uncertain evidence remains nonterminal with capped diagnostics and backoff, never terminalized by expiry or attempt limit. Registration/JOIN audit outbox records retain one identity through receiver retries, and the integrated Logging & Admin receiver/readback is local code; no exact PostgreSQL lost-acknowledgement/concurrency or direct text-to-Logging end-to-end proof is claimed. The target membership-generation snapshot at connect-token issuance remains unproved. Runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md), with owner contracts in [Authentication](../../system-architecture-authentication.md) and [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). +Account owns the explicit `JoinPublicProductionMembership` writer and HTTP controller, and Game Session's direct text `JOIN` dispatcher is implemented locally; the Gateway guard blocks external exposure of the Account HTTP route and first-party `Join & Play` remains unavailable. A `PENDING` intent persists before entitlement work; unavailable or expired-scope attempts remain retryable `AUTH_UNAVAILABLE` with no fabricated policy evidence. The bounded Account worker is readback-only and terminalizes only exact positive operation, scope, membership, and audit evidence; absent or uncertain evidence remains nonterminal with capped diagnostics and backoff, never terminalized by expiry or attempt limit. Registration/JOIN audit outbox records retain one identity through receiver retries, and Account's producer-side receipt validation and verified-projection marker handling are local code; the separate Logging & Admin receiver/readback remains unavailable in this front; no exact PostgreSQL lost-acknowledgement/concurrency or direct text-to-Logging end-to-end proof is claimed. The target membership-generation snapshot at connect-token issuance remains unproved. Runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md), with owner contracts in [Authentication](../../system-architecture-authentication.md) and [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). `GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`; broader reconnect/cutover consumption and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` when the tenant has zero or multiple subscription rows; focused cardinality/retry proof does not establish the full entitlement snapshot/freshness contract, including explicit free/trial rows, authoritative current-row selection, `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and delivery. `CommitTenantCapacityAdmission` has a synchronized target request/replay contract including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. @@ -56,9 +56,9 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. - **Target state:** global Account registration creates only global account/security state and a platform-scoped audit outbox entry in the same transaction; successful JOIN records a separate tenant-scoped event using its exact committed `tenantId`. Account preserves one stable event identity and envelope across retries. Logging & Admin owns the typed receipt, exact-payload digest, readback, minimized-evidence, and retention contract; see [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Logging & Admin is not a second authority for Account state. -- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; unavailable, timeout, mismatched, and ambiguous responses leave that identity `PENDING` and never mint a replacement. The integrated receiver performs exact payload-byte digest validation and readback. After a matching terminal minimized receipt, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. +- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; unavailable, timeout, mismatched, and ambiguous responses leave that identity `PENDING` and never mint a replacement. The receiver's target exact payload-byte digest validation and durable readback remain unavailable in this front; the producer cannot treat its request/response validation as proof that those separate receiver capabilities exist. After a matching terminal minimized receipt, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. - JOIN first commits a policy-independent `PENDING` intent; only an available entitlement result binds the policy digest, `allowPublicJoin`, and entitlement version for the membership/outbox/outcome transaction. An expired scope on a retained `PENDING` request returns retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation. The bounded Account reconciler is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence, while absent or uncertain evidence remains pending with capped diagnostics and backoff. It never reissues an expired scope or terminalizes by expiry or attempt limit. PostgreSQL unknown-outcome/concurrency proof remains open. -- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. +- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN append to the durable outbox and validate matching receipt responses as described above; receipt delivery/readback remains fail-closed until the separate receiver capability is present and proved. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). - Provides a JWKS endpoint for other services to validate tokens. Account Service owns signing-key lifecycle authorization, token issuance/rotation, desired key-ring state, and JWKS publication. In target non-exportable-signer mode, Account delegates only explicitly authorized private-key operations to the approved signer boundary; signer custody does not transfer lifecycle or publication authority. In the interim Account-only mounted fallback, the materialization controller is the sole Kubernetes API reader, writer, and generator for the fixed `jwt-signing-keys` Secret and custodian of that interim private material, but it may act only on Account-authorized operations. Account consumes projected key files and has no signing-Secret API authority. Kubernetes Jobs or CronJobs only observe Account-owned rotation, convergence, and retained evidence; they do not request or own rotation, read or write private keys, or publish JWKS, as described in the [Security Architecture](../../system-architecture-security.md). diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index b1bf8487ed..b610ae43c5 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -10,6 +10,8 @@ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenant `CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. +Both typed receipt responses carry `auditProjectionVersion=1` only when the receiver has durably linked the exact scope-qualified receipt to a distinct `log_events` audit projection in the same transaction. `receiptId` names the durable receipt; `logEventId` names the linked projection, not the receipt row's surrogate. The projection retains bounded identity metadata rather than another payload copy, including after payload minimization. Missing (`0`) or unsupported versions are not evidence of this capability; Account rejects them before marking delivery verified. The version marker never substitutes for the complete envelope, receipt/projection identity, status, and outcome checks above. Enabling version 1 does not attest historical Account outbox IDs or rewrite their unknown projection provenance; recovery requires exact current readback and guarded Account-owned recording. See [Account Runtime and Data](../account-service/runtime-and-data.md#implementation-status). + At this stage, `CreateLogEvent` returns gRPC `UNIMPLEMENTED` before request validation or dispatch, and `ReadLogEventReceipt` has no handler. The target workload-only mTLS/method-allowlist receiver, durable receipt/readback, and runtime proof remain unavailable; the target contract is not an implementation claim. The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index f087137665..0c4cc76c57 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -9752,7 +9752,7 @@ plus scoped tick pause/resume used for rollback safety. | payload_digest | [string](#string) | | | | status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | | outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | -| audit_projection_version | [int32](#int32) | | | +| audit_projection_version | [int32](#int32) | | Version 1 attests an exact receipt linked atomically to a distinct audit log projection. Zero or unsupported versions cannot verify delivery or historical producer provenance. | @@ -9896,7 +9896,7 @@ plus scoped tick pause/resume used for rollback safety. | status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | | outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| audit_projection_version | [int32](#int32) | | | +| audit_projection_version | [int32](#int32) | | Same receipt/projection attestation as CreateLogEventResponse; never payload replay proof. Zero or unsupported versions cannot verify delivery or historical producer provenance. | diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5b7d83d043..95481ff91a 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -223,3 +223,9 @@ Entry format: - Context: a Game Session validation run failed a new fixture assertion, but a pipeline ending in `tee` returned exit0 because the shell did not enable `pipefail`. - Expected pattern: enable `set -o pipefail` before captured validation pipelines and verify the terminal build result and test reports; a log sink's success is not the validation process's success. - Outcome: the failed build was identified from its terminal report, not reported as passing. After the fixture correction, the guarded complete rerun passed; no production check or negative assertion was weakened. + +- `2026-10-03`: Assert fresh initialization before testing idempotence + - Context: the Compose mTLS certificate contract checked private authority-directory permissions only after running setup twice. + - Observation: the second call repaired the first call's incorrect permissions, so the passing contract masked a broken fresh-initialization postcondition. + - Expected pattern: assert the first-call postconditions before any verification or idempotence rerun, then separately prove the rerun preserves the valid fixture. + - Outcome: setup now restores owner-only authority permissions after generation, and the focused contract independently proves the first-call boundary and repeated-call preservation. 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 a157e12077..68ce6ab81d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca The Account JOIN worker's positive audit evidence now includes an explicit version-1 COMMITTED receipt/projection marker and nonblank receiver identities from the locked scoped outbox row. Retained legacy IDs without that marker remain unresolved; this front stays unavailable until the receiver child supplies the matching versioned capability and proof. -Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, the owner-local Account audit outbox and typed Logging & Admin receipt/readback, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct text `JOIN` dispatch exist locally, but the Gateway still blocks external route exposure and first-party `Join & Play` remains unavailable. Account's bounded JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`, and only exact positive prior-commit evidence can terminalize; absent or uncertain evidence remains pending with capped diagnostics/backoff, never because of expiry or attempt limit. PostgreSQL lost-acknowledgement/concurrency, direct text-client-to-Logging end-to-end, and connect-token membership-version/authority-generation baseline proof remain open. Current `PLAY` and connect-token issuance remain partial: local `PLAY` validates lifecycle/version/generation on supplied-authority branches, but live Account runtime readers fail closed before data access. Account membership and realm-grant authorities remain separately owned. Namespace-aware binding, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. +Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, the owner-local Account audit outbox and producer-side typed receipt validation (the separate Logging & Admin receiver/readback remains unavailable in this front), tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct text `JOIN` dispatch exist locally, but the Gateway still blocks external route exposure and first-party `Join & Play` remains unavailable. Account's bounded JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`, and only exact positive prior-commit evidence can terminalize; absent or uncertain evidence remains pending with capped diagnostics/backoff, never because of expiry or attempt limit. PostgreSQL lost-acknowledgement/concurrency, direct text-client-to-Logging end-to-end, and connect-token membership-version/authority-generation baseline proof remain open. Current `PLAY` and connect-token issuance remain partial: local `PLAY` validates lifecycle/version/generation on supplied-authority branches, but live Account runtime readers fail closed before data access. Account membership and realm-grant authorities remain separately owned. Namespace-aware binding, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. 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. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 82fe6e25ab..f8bf2ffff1 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -92,7 +92,7 @@ ensure_compose_mtls_certs() { return 1 fi - local owner_id authority_dir workloads_dir service + local owner_id authority_dir workloads_dir service authority_mode_restored=0 owner_id="$(id -u)" if [[ ! -d "$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED" || -L "$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED" ]]; then echo "run-owned smoke ownership directory is unavailable." >&2 @@ -125,13 +125,16 @@ ensure_compose_mtls_certs() { return 1 fi fi - chmod 700 "$authority_dir" - if [[ "$(stat -Lc '%u %a %F' "$authority_dir")" != "$owner_id 700 directory" ]]; then - echo "Compose mTLS authority fixture must be an owner-only (0700) directory." >&2 - return 1 - fi if [[ ! -f "$authority_dir/ca.crt" || ! -f "$authority_dir/ca.key" || ! -f "$authority_dir/client.crt" || ! -f "$authority_dir/client.key" ]]; then (umask 077; "$GENERATOR" "$authority_dir") + # The generic generator makes the bundle directory container-readable. + # Compose authority material must remain private on its first generation too. + chmod 700 "$authority_dir" + if [[ "$(stat -Lc '%u %a %F' "$authority_dir")" != "$owner_id 700 directory" ]]; then + echo "Compose mTLS authority fixture must be an owner-only (0700) directory." >&2 + return 1 + fi + authority_mode_restored=1 fi for authority_file in ca.crt ca.key client.crt client.key; do preflight_managed_file "$authority_dir/$authority_file" "Compose mTLS authority material" @@ -140,9 +143,27 @@ ensure_compose_mtls_certs() { return 1 fi done + openssl verify -CAfile "$authority_dir/ca.crt" "$authority_dir/client.crt" >/dev/null + if ! certificate_matches_private_key "$authority_dir/client.crt" "$authority_dir/client.key"; then + echo "Compose mTLS shared client certificate and private key do not match." >&2 + return 1 + fi + local authority_san_output authority_uri_sans + authority_san_output="$(openssl x509 -in "$authority_dir/client.crt" -noout -ext subjectAltName)" + authority_uri_sans="$(printf '%s\n' "$authority_san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" + if [[ -n "$authority_uri_sans" ]]; then + echo "Compose mTLS shared client certificate must not contain a workload URI SAN." >&2 + return 1 + fi + if ((authority_mode_restored == 0)); then + chmod 700 "$authority_dir" + if [[ "$(stat -Lc '%u %a %F' "$authority_dir")" != "$owner_id 700 directory" ]]; then + echo "Compose mTLS authority fixture must be an owner-only (0700) directory." >&2 + return 1 + fi + fi chmod 600 "$authority_dir/ca.key" "$authority_dir/client.key" chmod 644 "$authority_dir/ca.crt" "$authority_dir/client.crt" - openssl verify -CAfile "$authority_dir/ca.crt" "$authority_dir/client.crt" >/dev/null workloads_dir="$requested_root/workloads" local -a services=( @@ -243,6 +264,16 @@ ensure_compose_mtls_certs() { return 1 fi done + for service in \ + gateway automation-scripting-service game-design-service game-logic-service logging-admin-service tcp-proxy-service; do + local san_output uri_sans + san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" + uri_sans="$(printf '%s\n' "$san_output" | grep -oE 'URI:[^,[:space:]]+' || true)" + if [[ -n "$uri_sans" ]]; then + echo "Compose mTLS shared generic workload must not contain a URI SAN: $service" >&2 + return 1 + fi + done fi echo "Compose mTLS workload certificates are ready in $workloads_dir" diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index abf1b0ed89..f44715eb86 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -218,6 +218,10 @@ validate_existing_leaf() { echo "existing local $description certificate has no readable subject alternative names: $certificate" >&2 return 1 fi + if [[ "$subject_alt_names" == *"URI:"* ]]; then + echo "existing local generic $description certificate must not contain a workload URI SAN: $certificate" >&2 + return 1 + fi for dns_name in "${local_service_dns_names[@]}"; do san_pattern="DNS:${dns_name}([,[:space:]]|$)" if [[ ! "$subject_alt_names" =~ $san_pattern ]]; then diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 86ee858134..10fe47141b 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -18,6 +18,10 @@ FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ FIREMUD_SMOKE_RUN_ID="$run_id" \ COMPOSE_PROJECT_NAME="$project_name" \ bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" +[[ "$(stat -c '%a' "$fixture_root/authority")" == 700 ]] || { + echo "first Compose mTLS certificate setup did not retain owner-only authority permissions." >&2 + exit 1 +} services=( account-service gateway automation-scripting-service entity-management-service game-design-service game-logic-service game-session-service logging-admin-service @@ -50,6 +54,83 @@ COMPOSE_PROJECT_NAME="$project_name" \ [[ ! -e "$workloads_dir/ca.key" ]] [[ -z "$(find "$workloads_dir" -type f -name ca.key -print -quit)" ]] +snapshot_tree() { + local tree_root="$1" + find "$tree_root" -type f -print0 | sort -z \ + | while IFS= read -r -d '' file; do + printf '%s %s ' "$(stat -c '%a %h' "$file")" "${file#"$tree_root"/}" + sha256sum -- "$file" + done +} + +# A CA-valid dedicated workload leaf in the shared authority slot is an +# accidental misprojection. Reject it before chmod or workload projection. +misplaced_authority_run_id="${run_id}-misplaced-authority" +misplaced_authority_project_name="firemud-smoke-$misplaced_authority_run_id" +misplaced_authority_project_key="$(printf '%s' "$misplaced_authority_project_name" | sha256sum | awk '{print $1}')" +misplaced_authority_root="$ownership_dir/$misplaced_authority_project_key.grpc-mtls" +misplaced_authority_dir="$misplaced_authority_root/authority" +mkdir -m 700 -- "$misplaced_authority_root" +mkdir -m 755 -- "$misplaced_authority_dir" +cp -- "$fixture_root/authority/ca.crt" "$misplaced_authority_dir/ca.crt" +cp -- "$fixture_root/authority/ca.key" "$misplaced_authority_dir/ca.key" +cp -- "$workloads_dir/game-session-service/client.crt" "$misplaced_authority_dir/client.crt" +cp -- "$workloads_dir/game-session-service/client.key" "$misplaced_authority_dir/client.key" +chmod 644 "$misplaced_authority_dir/ca.crt" "$misplaced_authority_dir/client.crt" +chmod 600 "$misplaced_authority_dir/ca.key" +# Noncanonical client-key mode proves refusal precedes authority-file chmod. +chmod 444 "$misplaced_authority_dir/client.key" +misplaced_authority_before="$(snapshot_tree "$misplaced_authority_root")" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$misplaced_authority_run_id" \ + COMPOSE_PROJECT_NAME="$misplaced_authority_project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$misplaced_authority_root" \ + >"$TEST_ROOT/misplaced-authority-output" 2>&1; then + echo "Compose mTLS certificate setup accepted a dedicated leaf in the shared authority slot." >&2 + exit 1 +fi +rg -Fq 'shared client certificate must not contain a workload URI SAN' "$TEST_ROOT/misplaced-authority-output" +[[ "$misplaced_authority_before" == "$(snapshot_tree "$misplaced_authority_root")" \ + && "$(stat -c '%a' "$misplaced_authority_dir")" == 755 \ + && ! -e "$misplaced_authority_root/workloads" ]] || { + echo "Compose mTLS source-identity refusal changed authority material or created workload projections." >&2 + exit 1 +} + +# Existing generic projections receive the same no-URI-SAN check, with all +# files left untouched when a dedicated certificate was placed in one. +misplaced_projection_run_id="${run_id}-misplaced-projection" +misplaced_projection_project_name="firemud-smoke-$misplaced_projection_run_id" +misplaced_projection_project_key="$(printf '%s' "$misplaced_projection_project_name" | sha256sum | awk '{print $1}')" +misplaced_projection_root="$ownership_dir/$misplaced_projection_project_key.grpc-mtls" +mkdir -m 700 -- "$misplaced_projection_root" +cp -a -- "$fixture_root/authority" "$misplaced_projection_root/authority" +cp -a -- "$workloads_dir" "$misplaced_projection_root/workloads" +chmod 644 "$misplaced_projection_root/workloads/gateway/client.crt" \ + "$misplaced_projection_root/workloads/gateway/client.key" +cp -- "$workloads_dir/game-session-service/client.crt" \ + "$misplaced_projection_root/workloads/gateway/client.crt" +cp -- "$workloads_dir/game-session-service/client.key" \ + "$misplaced_projection_root/workloads/gateway/client.key" +chmod 444 "$misplaced_projection_root/workloads/gateway/client.crt" \ + "$misplaced_projection_root/workloads/gateway/client.key" +misplaced_projection_before="$(snapshot_tree "$misplaced_projection_root")" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$misplaced_projection_run_id" \ + COMPOSE_PROJECT_NAME="$misplaced_projection_project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$misplaced_projection_root" \ + >"$TEST_ROOT/misplaced-projection-output" 2>&1; then + echo "Compose mTLS certificate setup accepted a dedicated leaf in a generic workload projection." >&2 + exit 1 +fi +rg -Fq 'shared generic workload must not contain a URI SAN: gateway' "$TEST_ROOT/misplaced-projection-output" +[[ "$misplaced_projection_before" == "$(snapshot_tree "$misplaced_projection_root")" ]] || { + echo "Compose mTLS generic-identity refusal partially changed an existing workload projection." >&2 + exit 1 +} + symlink_run_id="${run_id}-symlink" symlink_project_name="firemud-smoke-$symlink_run_id" symlink_project_key="$(printf '%s' "$symlink_project_name" | sha256sum | awk '{print $1}')" diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index dde8e8611d..68f76549d2 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -112,6 +112,16 @@ assert_workload_certificate() { } } +assert_no_uri_san() { + local certificate="$1" + local subject_alt_names + subject_alt_names="$(openssl x509 -in "$certificate" -noout -ext subjectAltName)" + if [[ "$subject_alt_names" == *"URI:"* ]]; then + echo "generic local certificate unexpectedly contains a workload URI SAN: $certificate" >&2 + exit 1 + fi +} + assert_invalid_workload_uri_is_reissued() { local case_name="$1" local subject_alt_name="$2" @@ -159,6 +169,9 @@ assert_invalid_workload_uri_is_reissued() { bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" +assert_no_uri_san "$CERT_DIR/client.crt" +assert_no_uri_san "$CERT_DIR/server.crt" + runtime_dir="$CERT_DIR/local-runtime" [[ -z "$(find "$runtime_dir" -name ca.key -print -quit)" ]] || { echo "CA private key was copied into the Compose runtime projection" >&2 @@ -409,6 +422,14 @@ for file in server.crt server.key client.crt client.key dev-cert.pem dev-key.pem done assert_invalid_existing_bundle_is_preserved "$wrong_issuer_case" wrong-issuer +misplaced_workload_case="$CERT_DIR/invalid-generic-workload-identity-bundle" +copy_generic_bundle "$CERT_DIR" "$misplaced_workload_case" +cp "$CERT_DIR/workloads/game-session-service.crt" "$misplaced_workload_case/client.crt" +cp "$CERT_DIR/workloads/game-session-service.key" "$misplaced_workload_case/client.key" +cp "$misplaced_workload_case/client.crt" "$misplaced_workload_case/dev-cert.pem" +cp "$misplaced_workload_case/client.key" "$misplaced_workload_case/dev-key.pem" +assert_invalid_existing_bundle_is_preserved "$misplaced_workload_case" generic-workload-identity + expired_case="$CERT_DIR/invalid-expired-bundle" copy_generic_bundle "$CERT_DIR" "$expired_case" cat >"$expired_case/expired.cnf" <<'EOF' diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index aafa3a0f95..6871831122 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -64,6 +64,8 @@ message CreateLogEventResponse { string payload_digest = 9; AccountAuditReceiptStatus status = 10; AccountAuditReceiptOutcome outcome = 11; + // Version 1 attests an exact receipt linked atomically to a distinct audit log projection. + // Zero or unsupported versions cannot verify delivery or historical producer provenance. int32 audit_projection_version = 12; } @@ -92,6 +94,8 @@ message ReadLogEventReceiptResponse { AccountAuditReceiptStatus status = 9; AccountAuditReceiptOutcome outcome = 10; shared.v1.ErrorDetail error = 11; + // Same receipt/projection attestation as CreateLogEventResponse; never payload replay proof. + // Zero or unsupported versions cannot verify delivery or historical producer provenance. int32 audit_projection_version = 12; } diff --git a/services/account-service/src/main/resources/db/migration/V28__account_join_reconciliation.sql b/services/account-service/src/main/resources/db/migration/V38__account_join_reconciliation.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V28__account_join_reconciliation.sql rename to services/account-service/src/main/resources/db/migration/V38__account_join_reconciliation.sql 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 new file mode 100644 index 0000000000..211338bcfb --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java @@ -0,0 +1,44 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; + +class AccountMigrationVersionTest { + @Test + void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws IOException { + List migrations; + try (var files = Files.list(Path.of("src/main/resources/db/migration"))) { + migrations = + files + .map(path -> Objects.requireNonNull(path.getFileName()).toString()) + .filter(name -> name.startsWith("V") && name.endsWith(".sql")) + .sorted() + .toList(); + } + + assertThat(migrations) + .contains( + "V28__account_audit_delivery_backoff.sql", + "V37__verified_audit_projection_evidence.sql", + "V38__account_join_reconciliation.sql") + .doesNotContain("V28__account_join_reconciliation.sql"); + assertThat(migrations.stream().map(AccountMigrationVersionTest::version).toList()) + .as("Flyway rejects two different migration descriptions with the same version") + .doesNotHaveDuplicates(); + assertThat(version("V28__account_audit_delivery_backoff.sql")) + .isEqualTo(version("V28__account_join_reconciliation.sql")); + } + + private static MigrationVersion version(String name) { + int separator = name.indexOf("__"); + assertThat(separator).as("versioned migration naming: %s", name).isGreaterThan(1); + return MigrationVersion.fromVersion(name.substring(1, separator)); + } +} From 6eae364e9765a248da7422c49c0cc6a268b901c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:18:29 +1300 Subject: [PATCH 43/55] Protect local workload certificate projections --- dev-tools/certs/README.md | 2 +- dev-tools/certs/ensure-dev-certs.sh | 6 ++++-- .../local-compose-workload-identity-contract.sh | 14 +++++++++++++- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index d00011cd06..5d019e9f67 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -12,5 +12,5 @@ Generated certificate outputs in this directory are ignored by Git and should no - Standalone hosted runs keep the legacy shared bundle for other gRPC workloads and use eight cert-manager-issued `firemud-grpc-` runtime-facing leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. Runtime namespaces contain no CA private key; missing or invalid issuer-projected leaves fail closed. - Default `dev-tools/certs/ensure-dev-certs.sh` validates the local CA and shared material, then prepares the canonical local Compose entrypoints with distinct Account, Game Session, and Social Groups workload identities under the ignored `local-runtime/` projection. It contains runtime-facing material only, never `ca.key`; the host CA key remains mode `0600`. - `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the canonical smoke fixture beneath the active run-owned Compose state directory. The authority directory remains host-only with mode `0700`, and its CA private key remains mode `0600`; each of eleven Java application containers gets a read-only `/app/certs` mount with only its leaf key, certificate, and public CA. Account, Game Session, Entity Management, Social Groups, and World Management get distinct `dev`-namespace SPIFFE leaves; World Management's leaf supports its authenticated Game Session owner-read path for the initial admission bind. Other services use the shared local development leaf. Retain the fixture while its exact Compose project may restart, and remove it only after that project is torn down. -- The three canonical runtime-proof entrypoints layer `docker/docker-compose.grpc-mtls.override.yml` last; ordinary `docker/docker-compose.override.yml` remains the plaintext local debugging profile. Hosted certificate provisioning is separate and never mounts the local CA private key. +- The ordinary `docker/docker-compose.override.yml` and local-images profile use the default local mTLS projection; the three canonical runtime-proof entrypoints layer `docker/docker-compose.grpc-mtls.override.yml` last to use their separate run-owned smoke fixture. Hosted certificate provisioning is separate and never mounts the local CA private key. - `dev-tools/certs/clean-dev-certs.sh` removes only its listed top-level files and known workload-leaf/runtime-projection paths, removing directories only when empty; unexpected files and symlinks are preserved and reported. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index f8bf2ffff1..1787886471 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -455,8 +455,10 @@ done # The complete existing projection passed preflight, so directory setup and # copy/chmod operations can now proceed without changing unrelated hard links. -mkdir -p "$RUNTIME_DIR" -chmod 755 "$RUNTIME_DIR" +if [[ ! -d "$RUNTIME_DIR" ]]; then + mkdir -m 700 -- "$RUNTIME_DIR" +fi +chmod 700 -- "$RUNTIME_DIR" for workload in "${workloads[@]}"; do mkdir -p "$RUNTIME_DIR/$workload/workloads" done diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index 68f76549d2..b74ba14352 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -179,7 +179,7 @@ runtime_dir="$CERT_DIR/local-runtime" } assert_mode 600 "$CERT_DIR/ca.key" assert_mode 700 "$CERT_DIR/workloads" -assert_mode 755 "$runtime_dir" +assert_mode 700 "$runtime_dir" for profile in default account-service game-session-service social-groups-service; do assert_mode 755 "$runtime_dir/$profile" assert_mode 644 "$runtime_dir/$profile/client.key" @@ -214,6 +214,18 @@ snapshot_runtime_projection() { done < <(find "$root" -type f -print0 | sort -z) } +# A repeat ensure restores the private outer projection boundary without +# changing the directly mounted files or their container-readable modes. +runtime_projection_before="$(snapshot_runtime_projection "$runtime_dir")" +chmod 755 "$runtime_dir" +bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" "$CERT_DIR" +runtime_projection_after="$(snapshot_runtime_projection "$runtime_dir")" +[[ "$runtime_projection_before" == "$runtime_projection_after" ]] || { + echo "idempotent certificate setup changed runtime projection files or modes" >&2 + exit 1 +} +assert_mode 700 "$runtime_dir" + snapshot_certificate_tree() { local root="$1" local file From bae68b71306e1201608f1b5b6ac847cec5e6e0d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:18:01 +1300 Subject: [PATCH 44/55] Clarify locally supported direct-text JOIN selectors --- .../microservices/game-session-service/protocols.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 882d939553..ee960106cf 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -70,7 +70,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Implemented locally; end-to-end/runtime proof remains incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. PostgreSQL execution, pending-operation recovery, and direct text/first-party path proof remain open. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | +| `JOIN ` | **Implemented locally; end-to-end/runtime proof remains incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. PostgreSQL execution, pending-operation recovery, and direct text/first-party path proof remain open. Current local input requires the exact `WORLDS` response index or a uniquely resolving bare world slug, following `REALMS`; `tenantSlug/worldSlug` remains target-only and is not accepted by the current parser. | `JOIN demo` (when that world slug is unique) | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | | `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | From 07cdc7d854d1d7fbac0bfdd5f0bbdfdf52f85179 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 07:20:34 +1300 Subject: [PATCH 45/55] Recheck JOIN scope expiry before membership mutation --- .../service/impl/AccountServiceImpl.java | 5 + .../service/impl/AccountServiceImplTest.java | 99 +++++++++++++++++++ 2 files changed, 104 insertions(+) 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 5355ba61b1..2a688ab098 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 @@ -742,6 +742,11 @@ private JoinPublicProductionResult executePendingJoinAttempt( accountTenantMembershipRepository .findByAccountIdAndTenantId(accountId, scope.tenantId()) .orElse(null); + if (isConnectScopeExpired(scope)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, "NOT_EVALUATED", "AUTH_UNAVAILABLE"); + return pendingJoinFailure(scope, "AUTH_UNAVAILABLE"); + } boolean transitioned = false; if (membership == null) { membership = new AccountTenantMembership(); 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 8aa5101e06..46bbe07e1d 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 @@ -786,6 +786,105 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { org.mockito.Mockito.verifyNoMoreInteractions(gameSessionClient); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void scopeExpiringDuringFinalJoinEvaluationLeavesNewOrRetainedIntentPending( + boolean retainedPendingIntent) { + 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(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + tokenProperties.setConnectScopeExpirationMs(3_600_000L); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest( + connectScopeId, + retainedPendingIntent ? "join-expiring-retained-1" : "join-expiring-new-1"); + + if (retainedPendingIntent) { + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult initialAttempt = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(initialAttempt.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", initialAttempt.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + } + + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + active.setEntitlementVersion(1L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + VerifiedJoinScope scope = retainedScope.get(); + java.time.Instant scopeExpiry = java.time.Instant.parse(scope.connectScopeExpiresAt()); + java.time.Instant evaluatedAt = java.time.Instant.parse(scope.evaluatedAt()); + assertTrue(scopeExpiry.isAfter(evaluatedAt)); + AtomicReference now = new AtomicReference<>(evaluatedAt); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenAnswer( + invocation -> { + now.set(scopeExpiry); + return java.util.List.of(active); + }); + org.mockito.Mockito.clearInvocations( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository, + subscriptionRepository); + + JoinPublicProductionResult result; + try (org.mockito.MockedStatic instantMock = + org.mockito.Mockito.mockStatic( + java.time.Instant.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + instantMock.when(java.time.Instant::now).thenAnswer(invocation -> now.get()); + result = service.joinPublicProduction(bootstrap.bootstrapToken(), request); + } + + assertFalse(result.success()); + assertFalse(result.replayed()); + assertEquals("AUTH_UNAVAILABLE", result.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertNull(retainedOperation.get().outcome()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("NOT_EVALUATED", retainedOperation.get().lastAttemptAuthorityAvailability()); + assertNotNull(retainedOperation.get().requestDigest()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .recordAttemptFailure(request.requestId(), "NOT_EVALUATED", "AUTH_UNAVAILABLE"); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordCallerBoundAuthorityInvalidation(request.requestId()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + org.mockito.Mockito.verify(accountTenantMembershipRepository) + .findByAccountIdAndTenantId(11L, 7L); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + @Test void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { Account account = new Account(); From 5422b63a6515b4f77efe0974dca66aa37e4379ad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 12:46:10 +1300 Subject: [PATCH 46/55] Clarify Account reader containment and JOIN recovery proof --- .../architecture/microservices/account-service/api-contracts.md | 2 +- .../microservices/account-service/runtime-and-data.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index dafae4e97f..5b719c4f62 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -258,7 +258,7 @@ The canonical token refresh, replacement, generation, revocation, fencing, logou The canonical membership, entitlement response shape, freshness, and sequence contract is [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). This API document retains only the local surfaces and transport consequences: - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` and `GetTenantEntitlementsForRuntime(tenantId, requestId)` are internal-only workload APIs for gameplay/runtime callers; they are not caller-facing substitutes for the billing-safe membership and entitlement variants listed above. -- Current drift: both methods are listed under Account's gRPC `public-methods` in development and production configuration, bypassing shared bearer validation, and the handlers do not enforce the exact Game Session/World Management workload or typed tenant-bound caller context. The target internal-only boundary remains canonical; readiness requires removal of the bypass plus missing-token, wrong-workload, and cross-tenant negative proof. +- Current status: both methods have been removed from Account's gRPC `public-methods` in development and production configuration, and the handlers admit only the exact Game Session peer. A request from that peer receives an in-band `FAILED_PRECONDITION` (`ErrorDetail`) before Account data access because typed caller/target context is unavailable; wrong-peer requests are denied. Typed caller/target context, positive snapshot behavior, and consumer proof remain unavailable. The canonical target contract remains in [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetRealmAccessGrant` and `ListRealmAccessGrantsForAccount` remain Account-owned internal reads for non-public realm discovery and admission; both require `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` and reject an unscoped or tenant-global `realmSlug` lookup. Current implementation is limited to four-field grant persistence/internal lookup and limited text `PLAY` denial; it does not prove lifecycle-bound reads, expiry, revocation propagation, consumer reconciliation, or active-binding ejection. Tenant-admin grant management and user-facing account selection remain incomplete. - `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is consumed by Account through `GameSessionClient`. [Multi-Tenancy's realm-catalog-and-admission-pointer contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) owns the realm-catalog/admission-pointer identity and `OPEN`/`CLOSED` semantics; Game Session remains the runtime owner that persists, mutates, and serves the pointer read. Account applies a bounded deadline to its gameplay-routing RPCs and translates only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` failures to retryable HTTP `503` / `AUTH_UNAVAILABLE`; other transport statuses retain their transport classification. Reachable application outcomes are not availability failures. Account's local pointer validation requires `stateScope` to be exactly `SHARED` or `ISOLATED`: a complete `CLOSED` pointer becomes `REALM_UNAVAILABLE`, reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid pointer evidence becomes `ADMISSION_POINTER_UNAVAILABLE`, and a valid scope whose exact pair changed becomes `CONNECT_SCOPE_MISMATCH`. Account never treats a timeout as missing pointer evidence, coerces an unknown scope to shared state, or silently re-resolves a stale selector. The current response remains the implemented local pointer shape; target pointer fields and `CLOSED` handling are owned by that canonical runtime routing contract and remain implementation drift where noted there. - `GetTenantEntitlementsTenant` and `GetTenantEntitlementsCrossTenantSupportSafe` remain separate caller-bound and redacted support-safe API variants. They must not be multiplexed with the internal runtime surface. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 45c3ccc178..958930fab6 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -288,7 +288,7 @@ Account-first bootstrap authenticates before tenant selection and accepts config Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers still fail closed before reads because their requests cannot prove caller/target binding, so those local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). -The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes return retryable `AUTH_UNAVAILABLE`, and the bounded worker terminalizes only exact positive evidence; absent or uncertain evidence remains pending with capped diagnostics and backoff. PostgreSQL lost-acknowledgement/concurrency, direct text-client/Logging end-to-end, and target membership-generation reread proof remain open. Logging receipt behavior is locally implemented, but the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Broader reconnect/cutover consumption of admission-pointer truth and operator pointer tooling are incomplete. +The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Logging receipt behavior is locally implemented, but the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Broader reconnect/cutover consumption of admission-pointer truth and operator pointer tooling are incomplete. `GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows; focused cardinality/retry proof does not establish the full snapshot/freshness contract, including explicit free/trial rows, authoritative current-row selection, `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and delivery. `CommitTenantCapacityAdmission` has a synchronized target request/replay contract including `mutationDigest`, but its RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. From 4557d73dcbbe5e604936a6900109e1d5a9951616 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 19:34:47 +1300 Subject: [PATCH 47/55] fix(account): contain reset RPCs and harden JOIN reconciliation proof --- .github/workflows/ci.yml | 1 + ...025-explicit-open-enrollment-membership.md | 2 +- .../environment-and-secrets-catalog.md | 2 +- .../account-service/api-contracts.md | 3 +- .../account-service/configuration.md | 4 +- .../account-service/runtime-and-data.md | 2 +- .../system-architecture-authz-route-matrix.md | 4 +- .../system-architecture-multi-tenancy.md | 2 +- .../system-architecture-protocol-bridging.md | 8 +- .../player-access-and-session.md | 2 +- ...r-experience-commands-and-communication.md | 10 +-- .../realm-routing-and-playable-state.md | 4 +- ...hared-runtime-contracts-and-persistence.md | 2 +- dev-tools/README.md | 2 +- .../account-workload-namespace-contract.sh | 89 +++++++++++++++++++ .../account-service/templates/deployment.yaml | 7 ++ .../AccountJoinReconciliationService.java | 21 ++++- .../service/impl/AccountGrpcService.java | 57 +++++------- .../AccountJoinPostgresIntegrationTest.java | 2 +- ...ReconciliationPostgresIntegrationTest.java | 6 +- .../AccountJoinReconciliationServiceTest.java | 65 ++++++++++++-- .../service/impl/AccountGrpcServiceTest.java | 41 +++++++++ 22 files changed, 262 insertions(+), 74 deletions(-) create mode 100644 dev-tools/tests/account-workload-namespace-contract.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7031ff3417..9a9f2ecd4a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -374,6 +374,7 @@ jobs: bash ./dev-tools/tests/trust-bootstrap-live-proof-contract.sh bash ./dev-tools/tests/trust-bootstrap-provision-contract.sh bash ./dev-tools/tests/hosted-identity-controller-manifest-contract.sh + bash ./dev-tools/tests/account-workload-namespace-contract.sh bash ./dev-tools/tests/hosted-identity-controller-workflow-contract.sh bash ./dev-tools/tests/worktree-topology-contract.sh bash ./dev-tools/tests/dev-tools-readme-contract.sh diff --git a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md index 46d1f1a629..a47bd619b2 100644 --- a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md +++ b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md @@ -88,7 +88,7 @@ This avoids durable rows for casual visits but creates a second class of gamepla - Add explicit browser/mobile join and text `JOIN` flows before first character creation/connect/`PLAY`. - Carry the verified `connectScopeId` through `JoinPublicProductionMembership`, bind the exact `catalogRevision` and `pointerVersion` pair plus the authoritative `allowPublicJoin` result and `entitlementVersion` into the versioned request/policy digest and committed transition evidence, and prove the policy, digest, selector, catalog, and pointer are rechecked at the membership commit gate. Prove that `JOIN_REQUIRED` is emitted only after an authoritative `allowPublicJoin=true` result; `allowPublicJoin=false` returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and stale or last-known-good entitlement cannot authorize join or restore `INACTIVE` membership. -- Implement the canonical `JoinPublicProductionMembership` operation rather than restoring the removed writer or retaining a compatibility adapter. The obsolete operation has been removed from the current Account proto/service, client, configuration, allowlists, and focused tests; generated references must be regenerated from the canonical contract when explicit `JOIN` is implemented. In the target state, `POST /auth/connect-token` and `PLAY` must require membership and must not write it. +- Implement the canonical `JoinPublicProductionMembership` operation rather than restoring the removed writer or retaining a compatibility adapter. The obsolete operation has been removed from the current Account proto/service, client, configuration, allowlists, and focused tests; generated references must be regenerated from the canonical contract when public explicit-`JOIN` delivery becomes available. In the target state, `POST /auth/connect-token` and `PLAY` must require membership and must not write it. - Prove every `IssueConnectToken` call, including the first call after explicit join, rereads the exact current caller-bound runtime membership snapshot at its Account issuance commit gate, including `membershipLifecycleState`, independent `membershipVersion`, and opaque `membershipAuthorityGeneration`; cached or bootstrap evidence cannot substitute even when its generation appears current. - Commit membership, its `membershipAuthorityGeneration`/`membershipVersion` changes, operation outcome, and exactly one transition audit/outbox event for create or restore atomically; an `ACTIVE` retry must remain event-free, and SQL membership/operation state is authoritative for replay. - Gate every new membership commit on the immediately preceding fresh ADR 0028 entitlement evaluation. Prove that unavailable or unsafe entitlement authority returns `ENTITLEMENT_UNAVAILABLE`, billing denial or a billing grace state that blocks joining returns `TENANT_BILLING_BLOCKED`, and a nonbilling public-production policy denial returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`; no membership, audit, or outbox record is committed after a failed, stale, future-dated, mismatched, or otherwise invalid evaluation, including evaluation/commit races. Prove that public-production alone can return `JOIN_REQUIRED` or invoke public `JOIN`, while private/playtest/non-production admission requires active membership and its current grant/entitlement and never invokes public join. diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index 3a80f15a5a..583256daac 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -224,7 +224,7 @@ These Account-specific environment variables configure the current scheduled, re | `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BATCH_SIZE` | Maximum due operations read back in one job pass; valid range `1..100` | `50` | | `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_MAX_ATTEMPTS` | Positive diagnostic threshold for unresolved attempts; reaching it does not terminalize an operation | `12` | | `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_INTERVAL_MS` | Positive fixed delay between scheduled job invocations, in milliseconds | `30000` | -| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BACKOFF_MS` | Positive delay, in milliseconds, before retrying an unresolved operation | `30000` | +| `FIREMUD_ACCOUNT_JOIN_RECONCILIATION_BACKOFF_MS` | Positive initial delay, in milliseconds, before retrying an unresolved operation. The delay doubles for each persisted unresolved attempt and caps at `max(initial delay, 300000)` ms. | `30000` | The attempt threshold only raises diagnostics; it never converts an uncertain `PENDING` operation to a terminal state. Exact readback recovery continues with backoff while the operation remains pending. See [Account Service Configuration: JOIN Reconciliation](../microservices/account-service/configuration.md#join-reconciliation) for the Account-local mapping and consequences. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index da785e641a..a728d4e9cc 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,7 +54,7 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -The local `/auth/bootstrap/join` controller and operation are implemented, but the Gateway route guard blocks external exposure and the route is absent from `publicOpenAPI`; first-party `Join & Play` remains unavailable. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit, so the strict ADR 0025 commit gate remains incomplete. The bounded Account worker may terminalize only after the exact operation, scope, membership, immutable audit envelope, and version-1 COMMITTED receiver receipt/projection identity are positively proved from the same scoped outbox row. Missing, legacy-unversioned, unsupported-version, or minimized delivery evidence leaves the intent pending with retry diagnostics. Expiry and attempt limits do not authorize JOIN replay or terminalization. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). +The local `/auth/bootstrap/join` controller and operation are implemented, but the Gateway route guard blocks external exposure and the route is absent from `publicOpenAPI`; first-party `Join & Play` remains unavailable. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit, so the strict ADR 0025 commit gate remains incomplete. The bounded Account worker may terminalize only after the exact operation, scope, membership, immutable audit envelope, and version-1 COMMITTED receiver receipt/projection identity are positively proved from the same scoped outbox row. Missing, legacy-unversioned, unsupported-version, or minimized delivery evidence leaves the intent pending with retry diagnostics. Each persisted unresolved attempt doubles its retry delay from the configured initial delay up to `max(initial delay, 300000 ms)`; the diagnostic attempt threshold does not stop readback or authorize JOIN replay or terminalization. Expiry does not authorize a terminal outcome. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. @@ -105,6 +105,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `POST /auth/pending-deletion/recovery/challenge` and `POST /auth/pending-deletion/recovery` are dedicated target recovery routes classified `public`; they may issue only `pending-deletion-access`, never normal login, bootstrap, connect-token, tenant, purchase, or gameplay authority. These target routes are not currently routable. - `RequestPasswordReset` – initiate a password reset email. Public initiation returns the same neutral success for known and unknown normalized email addresses; an unknown address creates no token and schedules no delivery. - `CompletePasswordReset` – update the password using a token. The current service conditionally consumes the still-valid token in the same transaction as the account mutation so a concurrent reuse cannot apply a second update; PostgreSQL execution remains a proof gate. +- The `RequestPasswordReset` and `CompletePasswordReset` gRPC handlers currently fail with `FAILED_PRECONDITION` before calling AccountService because no authorized internal caller is configured. The supported public REST reset routes remain available; this gRPC containment does not change their Account-owned token-consumption behavior. - External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the account-ID gRPC `LinkExternalAccount` also fails closed before mutation. The persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. No provider route may become routable until the target globally bound flow is implemented and proved. - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index 892a793ebe..5eda41c146 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -62,9 +62,9 @@ Changing any of the three JWT lifetime variables—`FIREMUD_AUTH_JWT_EXPIRATION_ | `firemud.account.join-reconciliation.batch-size` | Caps each due-operation readback page. | | `firemud.account.join-reconciliation.max-attempts` | Raises a diagnostic threshold for unresolved attempts only. | | `firemud.account.join-reconciliation.interval-ms` | Sets the fixed delay between job invocations. | -| `firemud.account.join-reconciliation.backoff-ms` | Sets the next readback time after an unresolved attempt. | +| `firemud.account.join-reconciliation.backoff-ms` | Sets the initial retry delay; persisted attempts scale it according to the central catalog's capped exponential policy. | -Reaching `max-attempts` never terminalizes an uncertain `PENDING` operation: exact readback continues with backoff, and attempt count alone is not evidence of commit or absence. Expiry or unavailable readback likewise does not authorize a membership mutation or an invented terminal outcome. +Reaching `max-attempts` never terminalizes an uncertain `PENDING` operation: exact readback continues with capped exponential backoff, and attempt count alone is not evidence of commit or absence. Expiry or unavailable readback likewise does not authorize a membership mutation or an invented terminal outcome. The central catalog owns the initial-delay default and cap semantics. ## Proto Files diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 89d9d0c814..a5c0b10159 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -26,7 +26,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`; Account's proto and producer emit the lifecycle and generation fields. Game Session text `PLAY` validates exact account/tenant identity plus freshness, lifecycle, admission, membership version, authority generation, and evaluation time on supplied-authority branches. `ACTIVE` is required for admission; only fresh `MISSING` or `INACTIVE` membership can produce public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. Canonical eligibility and outcome mapping belong to [Authentication](../../system-architecture-authentication.md). This local consumer validation does not establish a live Account snapshot: current Account membership, entitlement, and grant gRPC handlers fail closed before reads because their requests cannot prove caller/target binding. The complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` remain absent. +The Account proto and producer response model declares `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; this is not a live runtime snapshot because current Account membership, entitlement, and grant gRPC handlers fail closed before reads when caller/target binding is unavailable. Game Session text `PLAY` validates exact account/tenant identity plus freshness, lifecycle, admission, membership version, authority generation, and evaluation time on supplied-authority branches. `ACTIVE` is required for admission; only fresh `MISSING` or `INACTIVE` membership can produce public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. Canonical eligibility and outcome mapping belong to [Authentication](../../system-architecture-authentication.md). The complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` remain absent. Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist, but current connect-token issuance uses membership existence, admission, version, and evaluation-time evidence without enforcing the emitted lifecycle or authority-generation fields. It does not yet validate the full private/playtest target or perform the required membership-version/generation baseline reread at issuance; a replay-cache hit also returns before fresh authority reads. Character discovery applies its local membership/admission checks after entitlement and target checks. These paths do not create or restore membership. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 03cca6f3c0..cf5ba1d51e 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -26,7 +26,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). Account runtime membership, entitlement, and grant handlers fail closed before data access because their requests lack typed caller/target binding; this status does not claim successful live public `PLAY`. Game Session `PLAY` validates lifecycle, authority generation, membership version, and evaluation time on supplied-authority branches. Eligible public-production missing or `INACTIVE` membership reaches `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Policy denial, invalid evidence, and unavailable authority remain distinct. Direct-text `JOIN` is implemented locally through Account's explicit writer; first-party browser `Join & Play` remains blocked at Gateway. Versioned locked COMMITTED audit/receipt readback is the only recovery path for uncertain JOIN outcomes; retained expired-scope `PENDING` intents remain retryable absent exact positive prior-commit evidence. PostgreSQL execution/concurrency, direct text-to-Logging end-to-end proof, and Account's independent issuance-time membership-version/authority-generation reread proof remain open. -- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy declared in rows 260-261 and the normative [machine-readable route matrix](./system-architecture-authz-route-matrix.yaml). Current Account development and production configuration no longer lists these methods as public gRPC bypasses. Their handlers deny before data access, including for the exact Game Session peer, until the typed caller/target contract is implemented. Missing-token, wrong-workload, and cross-tenant denial proof establish containment, not a working admission path or target snapshot. +- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact caller policies assigned to each method in the normative [machine-readable route matrix](./system-architecture-authz-route-matrix.yaml). Current Account development and production configuration no longer lists these methods as public gRPC bypasses. Their handlers deny before data access, including for the exact Game Session peer, until the typed caller/target contract is implemented. Missing-token, wrong-workload, and cross-tenant denial proof establish containment, not a working admission path or 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. - The `platformAdmin` privileged-control predicate applies to the exact internal-workload `account-service/IssueHumanOperatorAuthorizationReference` issuance route in addition to its declared route-class allowlist. This exact route identity does not add `internal_workload` to the support or billing-safe classification scopes; the separate automation issuance path prohibits privileged control. @@ -225,7 +225,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GET /auth/bootstrap/worlds/{worldSlug}/realms` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Accepts only the caller-bound `player-bootstrap` profile; applies live realm visibility and runtime entitlement checks, with private/playtest additionally requiring caller-bound `ACTIVE` membership and the applicable Account-owned realm-access grant. Private/playtest is not public onboarding. | | Account Service | `GET /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Accepts only the caller-bound `player-bootstrap` profile; this existing-character discovery operation declares `selected_character_requirement: none`, and its target binding and `connect_scope_match` check require the opaque server-issued `connectScopeId` to match the selected route target, alongside live membership, applicable realm-grant, entitlement, and admission-pointer checks. It creates no gameplay binding and does not perform `PLAY`'s final binding CAS. | | Account Service | `POST /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters` | `public_production_onboarding` (public branch); `player_bootstrap_tenant` (private/playtest branch) | **Target; not currently routable or implemented.** Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Bootstrap-authenticated Account facade derives `accountId` from the authenticated caller subject, declares `selected_character_requirement: none`, and requires its target binding plus `connect_scope_match` check to match the opaque server-issued discovery `connectScopeId`; existing caller-bound membership, applicable realm visibility/grant, runtime entitlement, and admission-pointer checks precede the retained target delegation to internal Entity Management `CreateCharacter`. Character creation creates no gameplay binding and does not perform `PLAY`'s final binding CAS. | -| Account Service | `POST /auth/bootstrap/join` | `public_production_onboarding` | **Implemented locally; `target_not_currently_routable` as public ingress.** The explicit Gateway route guard blocks exposure and the route is absent from `publicOpenAPI`. Accepts only caller-bound `player-bootstrap`, derives `accountId` from the authenticated subject, and requires the exact opaque server-issued discovery `connectScopeId` to match the selected public-production target. The local transaction commits membership, operation outcome, and tenant audit outbox together, but policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. PostgreSQL lost-acknowledgement/concurrency, pending-operation readback, and direct-client proof remain open. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [ADR 0025](./decisions/adr-0025-explicit-open-enrollment-membership.md). | +| Account Service | `POST /auth/bootstrap/join` | `public_production_onboarding` | **Implemented locally; `target_not_currently_routable` as public ingress.** The explicit Gateway route guard blocks exposure and the route is absent from `publicOpenAPI`. Accepts only caller-bound `player-bootstrap`, derives `accountId` from the authenticated subject, and requires the exact opaque server-issued discovery `connectScopeId` to match the selected public-production target. The local transaction commits membership, operation outcome, and tenant audit outbox together, but policy-digest revalidation does not prove that the exact target remains valid through Account commit; strict through-commit target-validity proof remains incomplete under [ADR 0025's Membership Transaction](./decisions/adr-0025-explicit-open-enrollment-membership.md#membership-transaction). PostgreSQL lost-acknowledgement/concurrency, pending-operation readback, and direct-client proof remain open. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). | | Logging & Admin | `POST /feature-flags/toggle`, `POST /tick-remediation/pause`, `POST /tick-remediation/resume` | `tenant_regular` operator ingress | **Target; not currently routable.** Exact `control-ui` profile and current operator role. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Each mutation also requires its action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption before enablement. | | Logging & Admin | `POST /moderation/actions` | `tenant_regular` operator ingress for `gameplay_ban`, `chat_mute`, and `chat_ban`; `account_scoped` platform-jurisdiction ingress for `platform_access_ban` | **Target; unavailable/gated.** The closed `action` selector selects exactly one matrix variant and rejects `account_security_lock`, unknown, and legacy values before branch authorization. Tenant-scoped categories retain the `tenant_regular` branch: `moderator`, `tenantAdmin`, and `platformAdmin` use the existing tenant membership/tenant-generation or global target-tenant-generation consequences. `platform_access_ban` uses the separate `account_scoped` branch: only global `platformAdmin` with `privileged_control`, explicit global target-account binding and platform scope, no `tenantId`, no tenant billing generation, and no membership or tenant-generation checks. Both variants link the root moderation policy-intent authorization contract: Logging & Admin redeems the local Account reference at its receiving boundary; any later owner-enforcement command uses a distinct identity/digest/reference/fingerprint and is redeemed by the selected owner. Target mutation contract: `durable_intent_then_moderation_record_idempotency`. Account remains the enforcement owner for the global restriction; target Game Session and Social & Groups enforcement reads the applicable owner-local durable restriction state or projection. **Current compatibility drift:** both consumers instead call the live `EvaluateModerationPolicy` read at their enforcement boundaries; that read is not a second target moderation authority. Owner-enforcement command coverage remains a recorded gap. | | Logging & Admin | `POST /reports` | `player_bootstrap_tenant` | **Target-only; not currently routable.** Accepts caller-bound `player-bootstrap`, derives `tenantId` and `reporterAccountId` from the authenticated caller and live membership, applies `moderation_report_policy`, and writes a caller-bound durable report record. | diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index d284008ad4..de4b8b9964 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -22,7 +22,7 @@ Implementation status and execution evidence belong in the owning trackers or PR FireMUD separates **global identity** from **per-game state** so that one person can participate in multiple games without data leakage between tenants. -Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. +Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. The required focused proof for this boundary is owned by [Data Separation per Service](#data-separation-per-service) and the [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md); no end-to-end proof yet demonstrates these target invariants. - **Platform account (`accountId`)** – A global identity record managed by the Account Service. Each human player has a single platform account, which is the subject of authentication and JWT issuance. - **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. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index d8d3306851..d7b3aea44b 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The local Account JOIN route/RPC and Game Session text dispatch now exist, but current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but these consumers do not enforce lifecycle or generation. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Direct-text and first-party end-to-end proof and the required membership reread remain incomplete. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Game Session text `PLAY` validates supplied membership snapshots for exact account/tenant identity and freshness; present memberships require a consistent `ACTIVE`/`INACTIVE` lifecycle and positive membership-version and membership-authority-generation values, while missing membership must be exact `MISSING` evidence with zero versions and no admission. It recommends public `JOIN_REQUIRED` only for missing or `INACTIVE` membership after fresh entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership remains denied. This supplied-authority classification does not establish live admission: Account runtime readers fail closed before data access, and Account connect-token issuance still lacks the required membership-version/authority-generation reread. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Direct-text and first-party end-to-end proof remain incomplete. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current runtime has no lifecycle-state predicate and its admission consumers enforce only `membershipExists` and `gameplayAdmissionAllowed`; `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current runtime validates pointer/visibility for this flow but not the private/playtest realm grant, so current shortcut and token behavior do not prove authorization. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`; Game Session text `PLAY` validates lifecycle, generation, membership version, caller/target identity, and freshness on supplied-authority branches, as described in [Authentication](./system-architecture-authentication.md#implementation-status). `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Account connect-token issuance is a separate partial consumer: it uses membership existence, admission, version, and evaluation-time evidence without the lifecycle/authority-generation checks applied by supplied-authority `PLAY`; the required issuance-time version/generation reread and private/playtest grant validation remain incomplete. These local checks do not establish live composed admission while Account runtime readers fail closed before reads. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -67,7 +67,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. - `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. - `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - Current public-production membership is missing or non-admitting in the current consumer evidence; lifecycle-specific `INACTIVE` classification remains target-only. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. The local Account route/RPC and Game Session text dispatch now exist, but end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Private/playtest membership or grant failure is not a public join fallback. +- `JOIN_REQUIRED` - On supplied-authority Game Session `PLAY` branches, fresh public-production membership must be missing or `INACTIVE`, and the earlier routing, scope, authority, fresh-entitlement, and `allowPublicJoin` gates must pass. `PLAY` validates exact caller/target identity, lifecycle, membership version, authority generation, and freshness; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Live Account runtime reads still fail before data access, so this local classification does not establish live admission. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. The local Account route/RPC and Game Session text dispatch now exist, but end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Current admission-reader containment and local classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status): Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`. A supplied-authority `JOIN_REQUIRED` classification does not establish live admission. Private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Current admission-reader containment and local classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status): Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`. A supplied-authority `JOIN_REQUIRED` classification does not establish live admission. Private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. Target behavior permits Game Session to present bounded semantic recent context only after fresh admission and when exact binding and episode evidence permit, before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); current Game Session suppresses private retained-context reads on reconnect. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads remain suppressed on reconnect and after attempted `LOGOUT`, while fresh `LOOK` remains available after accepted `PLAY`. Strict generation-fence enforcement and live recovery proof remain incomplete, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: 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 3718e7ae5b..eaff879ac0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca The Account JOIN worker's positive audit evidence includes an explicit version-1 COMMITTED receipt/projection marker and nonblank receiver identities from the locked scoped outbox row. Retained legacy IDs without that marker remain unresolved. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receiver persistence/readback remains unproved under #2940. -Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, the owner-local Account audit outbox and producer-side typed receipt validation, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct-text `JOIN` dispatch exist locally, but Gateway blocks external route exposure and first-party browser `Join & Play` remains unavailable. The bounded Account JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize, while absent or uncertain evidence remains pending with capped diagnostics/backoff, never because of expiry or attempt limit. PostgreSQL lost-acknowledgement/concurrency, direct text-client-to-Logging end-to-end proof, and Account's independent connect-token issuance-time membership-version/authority-generation reread proof remain open. Current `PLAY` and connect-token issuance remain partial: local `PLAY` validates lifecycle/version/generation on supplied-authority branches, but live Account runtime readers fail closed before data access. Account membership and realm-grant authorities remain separately owned. Namespace-aware binding, resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and the terminal post-logout `resumeContextGeneration` fence remain incomplete; private replay is currently suppressed fail-closed. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. +Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, the owner-local Account audit outbox and producer-side typed receipt validation, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct-text `JOIN` dispatch exist locally, but Gateway blocks external route exposure and first-party browser `Join & Play` remains unavailable. The bounded Account JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize, while absent or uncertain evidence remains pending with capped diagnostics/backoff, never because of expiry or attempt limit. PostgreSQL lost-acknowledgement/concurrency, direct text-client-to-Logging end-to-end proof, and Account's independent connect-token issuance-time membership-version/authority-generation reread proof remain open. Current `PLAY` and connect-token issuance remain partial: local `PLAY` validates lifecycle/version/generation on supplied-authority branches, but live Account runtime readers fail closed before data access. Account membership and realm-grant authorities remain separately owned. Namespace-aware binding, resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and durable post-logout `resumeContextGeneration` fencing remain incomplete. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. 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. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index d0fbe26e21..ffaad4e18a 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status -This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, first-party post-logout suppression, and broader client consumption are not yet proven. Deliberate-`LOGOUT` replay suppression remains an unimplemented blocker requiring focused `LOGOUT` → `LOGIN` → `PLAY` proof that no private context is replayed; this tracker does not claim the runtime fix. +This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, durable post-logout termination/generation fencing, and broader client consumption are not yet proven. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`, but focused recovery proof for this suppression boundary remains incomplete. Packet 5 moderation/communication/social provenance is represented by [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md), [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md); Packet 6 P0 shared consequences are represented by [ADR 0151](../../architecture/decisions/adr-0151-event-scoped-automated-tier-a-credential-compliance.md), [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md), [ADR 0153](../../architecture/decisions/adr-0153-measured-online-backup-rpo-and-future-pitr-trigger.md), [ADR 0154](../../architecture/decisions/adr-0154-automated-recovery-proof-and-differentiated-traffic-open-gates.md), [ADR 0155](../../architecture/decisions/adr-0155-automated-event-classified-post-restore-trust-reset.md), [ADR 0156](../../architecture/decisions/adr-0156-risk-tiered-progressive-rollout-with-compatibility-bounded-rollback.md), [ADR 0157](../../architecture/decisions/adr-0157-dependency-classified-liveness-readiness-and-route-admission.md), [ADR 0158](../../architecture/decisions/adr-0158-simplified-observability-degradation-without-fallback-alert-authority.md), and [ADR 0159](../../architecture/decisions/adr-0159-profile-dependent-independent-deadman-and-public-path-monitoring.md) where player-facing delivery, history, or privacy boundaries are affected. These links do not upgrade any implementation or verification state. @@ -22,7 +22,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | --- | --- | --- | --- | --- | --- | --- | --- | | EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. | `proven` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | -| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | +| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; durable logout termination and strict generation fencing remain incomplete. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and Game Session suppresses private retained-context reads on reconnect and after attempted `LOGOUT`. Durable `resumeContextGeneration` termination/fencing and focused recovery proof remain incomplete. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. | | EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused tests cover the shipped bounded substrate, but current gameplay-role classification translates global `platformAdmin` and legacy global `god` inputs into gameplay roles contrary to ADR 0026, while payload/policy surfaces retain `HIDDEN_STAFF` and player-facing disconnect disposition contrary to ADR 0046. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Remove global-role inputs from presence/capability resolution, remove `HIDDEN_STAFF` from account-profile presence policy, suppress disconnect disposition from player responses, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | @@ -51,7 +51,7 @@ This section records implementation and proof status only. The target command, p Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path. Realm and character discovery helpers are currently not required ceremony. `PlayCommandHandler` has focused unit response-classification coverage for supplied missing/`INACTIVE` public membership and fresh entitlement/policy evidence. In the live composition, Account's trusted-peer runtime membership, entitlement, and grant handlers return `FAILED_PRECONDITION` before reading; Game Session maps the membership response to `WORLD_ACCESS_DENIED`, and no successful composed public `PLAY` or live `JOIN_REQUIRED` through those handlers is established. Account connect-token issuance has separate current checks and outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority retains the applicable unavailable/invalid-authority outcome. An unambiguous eligible `PLAY` branch enters directly when its required authority is supplied; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical admission behavior and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispatch now exist locally; the browser bootstrap facade is present, but its public Gateway route remains denied and target-only. Account's transactional audit outbox and Logging receipt handling are also implemented locally. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, and direct text-to-Logging end-to-end coverage; a bounded Account worker now reads back abandoned JOIN `PENDING` intents, but that does not prove those runtime/recovery outcomes. The proto/producer exposes lifecycle/generation fields, and focused `PlayCommandHandlerTest` cases exercise `JOIN_REQUIRED` classification with supplied membership and fresh entitlement/policy responses. Live Account runtime readers still reject before data access, so that conditional unit behavior does not establish a live `JOIN_REQUIRED` or successful public `PLAY`; Game Session maps the live `FAILED_PRECONDITION` response to `WORLD_ACCESS_DENIED`. Complete event/authority-tuple propagation and reconnect-freshness proof remain incomplete, as does the connect-token membership-authority-generation reread. Connect-token missing-membership/policy-denial mappings have focused `AccountServiceImplTest` coverage. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispatch now exist locally; the browser bootstrap facade is present, but its public Gateway route remains denied and target-only. Account's transactional audit outbox and producer-side typed receipt validation/verified-projection marker are implemented locally; Logging & Admin receiver persistence/readback remains unavailable and unproved under #2940. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, and direct text-to-Logging end-to-end coverage; a bounded Account worker now reads back abandoned JOIN `PENDING` intents, but that does not prove those runtime/recovery outcomes. The proto/producer exposes lifecycle/generation fields, and focused `PlayCommandHandlerTest` cases exercise `JOIN_REQUIRED` classification with supplied membership and fresh entitlement/policy responses. Live Account runtime readers still reject before data access, so that conditional unit behavior does not establish a live `JOIN_REQUIRED` or successful public `PLAY`; Game Session maps the live `FAILED_PRECONDITION` response to `WORLD_ACCESS_DENIED`. Complete event/authority-tuple propagation and reconnect-freshness proof remain incomplete, as does the connect-token membership-authority-generation reread. Connect-token missing-membership/policy-denial mappings have focused `AccountServiceImplTest` coverage. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation @@ -61,8 +61,8 @@ The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispa ### Transcript, History, and Room Views -- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. `LOGOUT` clears live presence and reconnect eligibility in storage, but the first-party connect-context replay handler currently ignores that eligibility and may replay retained rows; durable retained rows are distinct from reconnect eligibility. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). -- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. The handler-side eligibility check owns the post-logout suppression fix; post-logout first-party replay still contradicts canonical termination behavior, and full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. +- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; durable episode termination is not implemented. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). +- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. Local read suppression does not prove durable `resumeContextGeneration` termination/fencing or live recovery behavior, and full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. - Current behavior: Game Logic composes ordinary floor-free `LookResult` data from World Management and Entity Management; Game Session enforces access and renders the result. Current request/proto evidence carries no causal-floor evidence, so target propagation and participant proof remain gaps linked to [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md). `LOOK`, `QUICKLOOK`, movement refresh, localization, brief/color handling, and bounded error mapping are covered. The current renderer also writes disposable legacy cache values; reads remain authoritative/uncached, and this incomplete scope plus ten-minute TTL does not prove the target causal-floor/freshness contract. Combat-sensitive brief-on-move and broader world-content localization remain incomplete. ### Communication, Social, and Presence 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 eee18c2989..9886230dc6 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 @@ -55,7 +55,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer is implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. Current Account membership reads and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` admits only an exact safe `ACTIVE` snapshot; actionable public `JOIN_REQUIRED` requires a fresh Account response matching the exact account/tenant, validated lifecycle/version/generation/evaluation time, and either missing (`MISSING`) or existing `INACTIVE` membership, plus fresh entitlement confirming gameplay availability and `allowPublicJoin`. Other non-admitting states are denied. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers validate the trusted peer then fail with `FAILED_PRECONDITION` before reads, so local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`; the live membership failure maps to `WORLD_ACCESS_DENIED`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text `PLAY` maps either case to `WORLD_ACCESS_DENIED` before grant lookup. Supplied-authority text `PLAY` then performs the Account-owned grant check, and a grant never substitutes for membership. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; canonical admission behavior and status remain owned by [Authentication](../../architecture/system-architecture-authentication.md#implementation-status). +Account's explicit public-production membership writer and Game Session direct-text JOIN invocation are implemented locally; first-party browser JOIN remains blocked at Gateway. Game Session validates lifecycle, membership version, authority generation, caller/target identity, and freshness on supplied-authority PLAY branches, and recommends public JOIN_REQUIRED only for missing or INACTIVE membership after fresh entitlement and allowPublicJoin checks. An ACTIVE but non-admitting membership is denied. The proto's uint64 generation and incomplete Account issuance reread/private-grant validation remain implementation gaps; live Account readers fail before data access, so composed admission is unproved. Canonical admission rules belong to [Authentication](../../architecture/system-architecture-authentication.md#implementation-status); Account and Game Session implementation/proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. Current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate the applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. @@ -83,7 +83,7 @@ Remote followup persistence and projection use one normalized `{playableStateSco ### Realm-Scoped Playable State -Tenant membership and character ownership do not imply a shared gameplay namespace. Each realm carries explicit `stateScope` and `characterCreationPolicy`; shared-state realms use a tenant-live `playableStateKey`, while isolated realms, including playtest forks, use an instance-local key. `CHARS` is a realm-local roster with explicit creation policy. The scope-aware roster contract is used by bootstrap character discovery, `REALMS`, `CHARS`, `PLAY`, and `TELL`; isolated realms cannot read or mutate the tenant's production roster through tenant-wide or bare-character shortcuts. +Realm-local character discovery and creation use the selected realm's state scope and creation policy across bootstrap, `REALMS`, `CHARS`, `PLAY`, and `TELL`; isolated realms must not reach the tenant's production roster. Entity still uses legacy `playableStateKey` resolution, so stable namespace isolation remains partial and unproved. The target identity and shared-versus-isolated rules belong to [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#realm-state-model) and [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). For persistent/shared mutating smoke, this namespace boundary would be the mutation boundary, but the required restricted-synthetic verifier and proof remain unavailable. The bounded run-owned Compose mutation/teardown boundary is implemented, but persistent/shared identity/namespace/fence isolation remains unproved. Follow the [canonical testing owner](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) for the boundary contract. 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 53c1fefef8..aa66a4f2b4 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 @@ -40,7 +40,7 @@ These links add decision provenance and shared-runtime consequences only; capabi The following current-state findings refine the existing partial/drift status; owner documents retain the target contract details: - `SF-1.2` / `SF-2.1`: Account's current implementation includes global registration and explicit public-membership `JOIN` locally (see #2847). PostgreSQL execution, pending-operation recovery, retained-row disposition, and direct text-to-Logging end-to-end proof for the registration/JOIN path remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). -- `SF-1.2` / `SF-2.1`: Account V25 enforces one live profile per `(tenant_id, account_id)` while allowing the same global account to have one profile in each tenant. Its named preflight fails closed on retained duplicate tuples without rewriting them. The PostgreSQL cases for cross-tenant reuse, same-tenant rejection, and retained-duplicate migration failure compile but were Docker-skipped, so runtime database proof and any required retained-row disposition remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). +- `SF-1.2` / `SF-2.1`: Account V25 enforces one live profile per `(tenant_id, account_id)` and its named preflight fails on retained duplicates without rewriting them. Cross-tenant reuse, same-tenant rejection, and retained-duplicate PostgreSQL cases compiled but were Docker-skipped; database proof and any required retained-row disposition remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-1.2` / `SF-2.1`: Account's live `subscription` table has neither a current/non-superseded tenant uniqueness invariant nor provider subscription identity/history. Current subscription creation fails closed before mutation, while retained/local subscription rows still lack current-row uniqueness and provider identity/history. Runtime entitlement reads require exactly one explicit subscription row for the tenant; zero or multiple rows return retryable `ENTITLEMENT_UNAVAILABLE`. The target retained-history, replacement, webhook, and provider-reconciliation lifecycle is not implemented. A partial index or provider-ID backfill cannot be invented without that owner lifecycle and retained-row disposition. This concrete gap is routed to Player Access capability `AA-1.4`, with `AA-1.5` as a consumer consequence; see [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#implementation-status) and [Player Access and Session](./player-access-and-session.md#capability-status). - `SF-2.1`: Account V22/V23 canonicalize retained `accounts.email` values and validate a new check without proven rolling- or rollback-compatibility with older binaries. Before affected deployment, Account needs service- and environment-specific no-overlap and retained-data evidence or a forward-compatible rollout path, plus old-era and mixed-binary proof. No existing deployment state is inferred; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-2.1`: Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows with per-family deleted counts and oldest-expired-row lag. The cleanup now matches the current credential issuer/validator's process-local clock for timezone-less rows, but cross-node timezone normalization and retained-row conversion remain open. Six focused cleanup unit cases executed locally; seven PostgreSQL integration cases passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. Atomic token consumption, session revocation, and complete ADR 0163 retention classes, horizons, blockers, holds, and cross-service proof remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). This tracker records owner-local status only and does not alter the normative retention contract. diff --git a/dev-tools/README.md b/dev-tools/README.md index 4b113c1f64..699f4efdb2 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -45,7 +45,7 @@ The `pr-review`, `report-worktree-pr-topology.sh`, and `maintenance/cloc-report. - `restores/` – restore, state-reset, and external-credential validation helpers; see `restores/README.md` for the script map. - `smoke/` – shared smoke defaults and the run-owned Compose claim/capability helper. - `seed/` – local and test data seeding helpers. -- `tests/` – contract tests for repo-owned tooling. +- `tests/` – contract tests for repo-owned tooling, including [account-workload-namespace-contract.sh](tests/account-workload-namespace-contract.sh) for offline Account Helm namespace binding and `extraEnv` preservation/collision proof. - `validation/` – repo policy and static validation scripts used by Gradle and CI. The documentation lock is sourced from the unpinned direct roots in `config/docs/requirements.in` and generated into `config/docs/requirements.txt` with the repository Python version and `pip-compile --allow-unsafe --generate-hashes --index-url=https://pypi.org/simple --output-file=config/docs/requirements.txt config/docs/requirements.in`. The existing lock seeds compilation and preserves satisfying package pins unless you explicitly request an upgrade. When the installed pip-tools version mis-serializes its default index options into an unsupported header, set `CUSTOM_COMPILE_COMMAND` to that exact command so the generated header remains parseable. Keep the source roots and lock hashes in sync; do not edit lock hashes manually. diff --git a/dev-tools/tests/account-workload-namespace-contract.sh b/dev-tools/tests/account-workload-namespace-contract.sh new file mode 100644 index 0000000000..c1de7ece44 --- /dev/null +++ b/dev-tools/tests/account-workload-namespace-contract.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CHART_DIR="$ROOT_DIR/k8s/helm/account-service" +TEMP_DIR="$(mktemp -d)" +trap 'rm -rf -- "$TEMP_DIR"' EXIT + +if ! command -v helm >/dev/null 2>&1; then + echo "helm is required to render the Account workload namespace contract" >&2 + exit 1 +fi + +DEFAULT_RENDER="$TEMP_DIR/default.yaml" +CUSTOM_RENDER="$TEMP_DIR/custom.yaml" +COLLISION_RENDER="$TEMP_DIR/collision.yaml" + +helm template account-default "$CHART_DIR" --namespace default >"$DEFAULT_RENDER" +helm template account-custom "$CHART_DIR" \ + --namespace pr-2848 \ + --set-string extraEnv.ORDINARY_SETTING=preserved \ + >"$CUSTOM_RENDER" + +python3 - "$DEFAULT_RENDER" "$CUSTOM_RENDER" <<'PY' +import pathlib +import sys + +import yaml + + +def account_environment(path): + documents = [ + document + for document in yaml.safe_load_all(pathlib.Path(path).read_text(encoding="utf-8")) + if isinstance(document, dict) + ] + deployment = next( + ( + document + for document in documents + if document.get("kind") == "Deployment" + and document.get("metadata", {}).get("name") == "account-service" + ), + None, + ) + if deployment is None: + raise SystemExit(f"{path}: rendered Account Deployment is missing") + containers = deployment.get("spec", {}).get("template", {}).get("spec", {}).get("containers", []) + account = next( + (container for container in containers if container.get("name") == "account-service"), + None, + ) + if account is None: + raise SystemExit(f"{path}: rendered Account container is missing") + return account.get("env", []) + + +for path in sys.argv[1:]: + env = account_environment(path) + matches = [entry for entry in env if entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE"] + if len(matches) != 1: + raise SystemExit( + f"{path}: expected exactly one FIREMUD_GRPC_WORKLOAD_NAMESPACE entry, found {len(matches)}" + ) + expected = { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + } + if matches[0] != expected: + raise SystemExit(f"{path}: workload namespace is not sourced from metadata.namespace: {matches[0]}") + +custom_env = account_environment(sys.argv[2]) +ordinary = [entry for entry in custom_env if entry.get("name") == "ORDINARY_SETTING"] +if ordinary != [{"name": "ORDINARY_SETTING", "value": "preserved"}]: + raise SystemExit(f"custom render did not preserve extraEnv: {ordinary}") +PY + +if helm template account-collision "$CHART_DIR" \ + --namespace pr-2848 \ + --set-string extraEnv.FIREMUD_GRPC_WORKLOAD_NAMESPACE=forged \ + >"$COLLISION_RENDER" 2>"$TEMP_DIR/collision.err"; then + echo "Account chart accepted a controller-owned workload namespace override" >&2 + exit 1 +fi +if ! grep -Fq 'extraEnv must not set controller-owned FIREMUD_GRPC_WORKLOAD_NAMESPACE' "$TEMP_DIR/collision.err"; then + echo "Account chart collision failed for an unexpected reason" >&2 + cat "$TEMP_DIR/collision.err" >&2 + exit 1 +fi diff --git a/k8s/helm/account-service/templates/deployment.yaml b/k8s/helm/account-service/templates/deployment.yaml index bde01874a2..fcb1c9389c 100644 --- a/k8s/helm/account-service/templates/deployment.yaml +++ b/k8s/helm/account-service/templates/deployment.yaml @@ -1,5 +1,8 @@ apiVersion: apps/v1 kind: Deployment +{{- if hasKey (.Values.extraEnv | default dict) "FIREMUD_GRPC_WORKLOAD_NAMESPACE" }} +{{- fail "extraEnv must not set controller-owned FIREMUD_GRPC_WORKLOAD_NAMESPACE" }} +{{- end }} metadata: name: account-service spec: @@ -23,6 +26,10 @@ spec: ports: - containerPort: 8080 env: + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace {{- range $key, $value := .Values.extraEnv }} - name: {{ $key }} value: "{{ $value }}" 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 f18c38ff5e..ad98bc3f3b 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 @@ -42,6 +42,7 @@ public class AccountJoinReconciliationService { private static final Logger logger = LoggerFactory.getLogger(AccountJoinReconciliationService.class); private static final int MAX_BATCH_SIZE = 100; + private static final long MAX_BACKOFF_MILLIS = 300_000L; private static final Pattern SHA256_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); private static final Set JOIN_AUDIT_FIELDS = Set.of("accountId", "tenantId", "worldSlug", "realmSlug", "membershipVersion", "requestId"); @@ -389,7 +390,7 @@ private ReconciliationResult recordUnresolvedAttempt( operation.nextReconciliationAttemptAt(), now, reason, - nextAttemptAt(now)); + nextAttemptAt(now, operation.reconciliationAttemptCount())); if (!recorded) { return ReconciliationResult.SKIPPED; } @@ -435,14 +436,28 @@ private ReconciliationResult recordUnavailableAttempt(JoinOperation candidate, I } } - private Instant nextAttemptAt(Instant attemptedAt) { + private Instant nextAttemptAt(Instant attemptedAt, int persistedAttemptCount) { try { - return attemptedAt.plusMillis(backoffMillis); + return attemptedAt.plusMillis(retryDelayMillis(persistedAttemptCount)); } catch (DateTimeException | ArithmeticException ex) { throw new IllegalStateException("JOIN reconciliation backoff is outside timestamp range", ex); } } + private long retryDelayMillis(int persistedAttemptCount) { + long cap = Math.max(backoffMillis, MAX_BACKOFF_MILLIS); + long delay = backoffMillis; + int remainingDoublings = Math.max(0, persistedAttemptCount); + while (remainingDoublings > 0 && delay < cap) { + if (delay > cap / 2) { + return cap; + } + delay *= 2; + remainingDoublings--; + } + return delay; + } + private static UUID joinAuditEventId(String requestId) { return UUID.nameUUIDFromBytes( ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 52c55cac8e..47ee2ac770 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -36,11 +36,9 @@ import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; -import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; -import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.PingService; @@ -749,23 +747,16 @@ public void requestPasswordReset( net.firedevops.firemud.account.v1.RequestPasswordResetRequest request, StreamObserver responseObserver) { - try { - accountService.requestPasswordReset(new PasswordResetRequest(request.getEmail())); - var response = - net.firedevops.firemud.account.v1.RequestPasswordResetResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.RequestPasswordResetResponse.newBuilder() - .setSuccess(false) - .setError(appError("RequestPasswordReset", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.RequestPasswordResetResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "RequestPasswordReset", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -774,24 +765,16 @@ public void completePasswordReset( net.firedevops.firemud.account.v1.CompletePasswordResetRequest request, StreamObserver responseObserver) { - try { - accountService.completePasswordReset( - new CompletePasswordResetRequest(request.getToken(), request.getNewPassword())); - var response = - net.firedevops.firemud.account.v1.CompletePasswordResetResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.CompletePasswordResetResponse.newBuilder() - .setSuccess(false) - .setError(appError("CompletePasswordReset", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.CompletePasswordResetResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "CompletePasswordReset", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override 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..5955eff9dc 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 @@ -58,7 +58,7 @@ class AccountJoinPostgresIntegrationTest { private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); private static final String WORLD_SLUG = "join-proof-world"; private static final String REALM_SLUG = "production"; - private static final String NAMESPACE_ID = "join-proof-namespace"; + private static final String NAMESPACE_ID = "4f9e5c68-6251-4b22-8c3a-a0ed4a2d6bc1"; private static final long GAME_INSTANCE_ID = 44L; private static final long CATALOG_REVISION = 23L; private static final long POINTER_VERSION = 17L; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index b90b031dbe..dafec6feae 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -68,7 +68,7 @@ class AccountJoinReconciliationPostgresIntegrationTest { private static final UUID REALM_ID = UUID.fromString("a825f7ef-0ea3-4e8c-bf7c-a20242b4c931"); private static final String WORLD_SLUG = "join-reconciliation-world"; private static final String REALM_SLUG = "production"; - private static final String NAMESPACE_ID = "join-reconciliation-namespace"; + private static final String NAMESPACE_ID = "c3b77762-3cc2-4f76-9fc8-5f4938fe7924"; private static final long GAME_INSTANCE_ID = 73L; private static final long CATALOG_REVISION = 29L; private static final long POINTER_VERSION = 11L; @@ -419,7 +419,7 @@ private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture) { private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture, int attempts) { int updated = dsl.execute( - "UPDATE account_join_operations SET status = 'PENDING', outcome = NULL, membership_id = NULL, outcome_membership_version = NULL, outcome_membership_authority_generation = NULL, reconciliation_attempt_count = ?, last_reconciliation_attempt_at = CASE WHEN ? = 0 THEN NULL ELSE CURRENT_TIMESTAMP - INTERVAL '2 seconds' END, last_reconciliation_attempt_reason = CASE WHEN ? = 0 THEN NULL ELSE 'PRIOR_RECONCILIATION_ATTEMPT' END, next_reconciliation_attempt_at = CURRENT_TIMESTAMP - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED'", + "UPDATE account_join_operations SET status = 'PENDING', outcome = NULL, membership_id = NULL, outcome_membership_version = NULL, outcome_membership_authority_generation = NULL, reconciliation_attempt_count = ?, last_reconciliation_attempt_at = CASE WHEN ? = 0 THEN NULL ELSE pg_catalog.timezone('UTC', CURRENT_TIMESTAMP) - INTERVAL '2 seconds' END, last_reconciliation_attempt_reason = CASE WHEN ? = 0 THEN NULL ELSE 'PRIOR_RECONCILIATION_ATTEMPT' END, next_reconciliation_attempt_at = pg_catalog.timezone('UTC', CURRENT_TIMESTAMP) - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED'", attempts, attempts, attempts, @@ -438,7 +438,7 @@ private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture, int a private void setReconciliationAttempts(JoinFixture fixture, int attempts) { int updated = dsl.execute( - "UPDATE account_join_operations SET reconciliation_attempt_count = ?, last_reconciliation_attempt_at = CURRENT_TIMESTAMP - INTERVAL '2 seconds', last_reconciliation_attempt_reason = 'PRIOR_RECONCILIATION_ATTEMPT', next_reconciliation_attempt_at = CURRENT_TIMESTAMP - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'PENDING'", + "UPDATE account_join_operations SET reconciliation_attempt_count = ?, last_reconciliation_attempt_at = pg_catalog.timezone('UTC', CURRENT_TIMESTAMP) - INTERVAL '2 seconds', last_reconciliation_attempt_reason = 'PRIOR_RECONCILIATION_ATTEMPT', next_reconciliation_attempt_at = pg_catalog.timezone('UTC', CURRENT_TIMESTAMP) - INTERVAL '1 second', updated_at = CURRENT_TIMESTAMP WHERE request_id = ? AND status = 'PENDING'", attempts, fixture.requestId()); assertThat(updated).isEqualTo(1); 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 c4b429974e..ef7a89bbb1 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 @@ -163,7 +163,7 @@ void missingMembershipAfterScopeExpiryStaysPendingAndReschedulesAtTheAttemptThre NOW.minusSeconds(1), NOW, "MEMBERSHIP_EVIDENCE_ABSENT", - NOW.plusMillis(5_000))) + NOW.plusMillis(40_000))) .thenReturn(true); fixture.service.reconcileDueOperations(NOW); @@ -176,7 +176,7 @@ void missingMembershipAfterScopeExpiryStaysPendingAndReschedulesAtTheAttemptThre NOW.minusSeconds(1), NOW, "MEMBERSHIP_EVIDENCE_ABSENT", - NOW.plusMillis(5_000)); + NOW.plusMillis(40_000)); verify(fixture.joinOperations, never()) .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); verifyNoInteractions(fixture.auditOutbox); @@ -219,7 +219,7 @@ void attemptThresholdIsReportedOnceAndCappedCountStillReschedules() { NOW.plusMillis(5_000), NOW.plusMillis(6_000), "JOIN_AUDIT_ENVELOPE_ABSENT", - NOW.plusMillis(11_000))) + NOW.plusMillis(16_000))) .thenReturn(true); fixture.service.reconcileDueOperations(NOW.plusMillis(6_000)); @@ -244,7 +244,7 @@ void attemptThresholdIsReportedOnceAndCappedCountStillReschedules() { NOW.plusMillis(5_000), NOW.plusMillis(6_000), "JOIN_AUDIT_ENVELOPE_ABSENT", - NOW.plusMillis(11_000)); + NOW.plusMillis(16_000)); } @Test @@ -262,7 +262,7 @@ void readbackExceptionAtTheThresholdStillSchedulesAnotherAttempt() { NOW.minusSeconds(1), NOW, "JOIN_READBACK_UNAVAILABLE", - NOW.plusMillis(5_000))) + NOW.plusMillis(20_000))) .thenReturn(true); fixture.service.reconcileDueOperations(NOW); @@ -275,11 +275,58 @@ void readbackExceptionAtTheThresholdStillSchedulesAnotherAttempt() { NOW.minusSeconds(1), NOW, "JOIN_READBACK_UNAVAILABLE", - NOW.plusMillis(5_000)); + NOW.plusMillis(20_000)); assertThat(reconciliationCounter(fixture, "unresolved")).isEqualTo(1); assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isZero(); } + @Test + void retryDelayDoublesFromInitialDelayAndSaturatesWithoutArithmeticOverflow() { + assertRetryDelay(0, 12, 5_000, 5_000); + assertRetryDelay(1, 12, 5_000, 10_000); + assertRetryDelay(5, 12, 5_000, 160_000); + assertRetryDelay(6, 12, 5_000, 300_000); + assertRetryDelay(2, 2, 5_000, 20_000); + assertRetryDelay(Integer.MAX_VALUE, Integer.MAX_VALUE, 5_000, 300_000); + assertRetryDelay(1, 2, Long.MAX_VALUE, Long.MAX_VALUE); + } + + private static void assertRetryDelay( + int attemptCount, int maxAttempts, long initialDelayMillis, long expectedDelayMillis) { + Fixture fixture = fixture(maxAttempts, initialDelayMillis); + JoinOperation pending = pendingOperation(attemptCount, NOW.minusSeconds(1)); + stubDue(fixture, pending); + 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.empty()); + Instant expectedNextAttempt = NOW.plusMillis(expectedDelayMillis); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + attemptCount, + maxAttempts, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + expectedNextAttempt)) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + attemptCount, + maxAttempts, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_EVIDENCE_ABSENT", + expectedNextAttempt); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + @Test void wrongPayloadDigestStaysPending() { Fixture fixture = fixture(3); @@ -454,6 +501,10 @@ void concurrentCallerTerminalizationIsSkippedAfterAccountAndOperationLocks() { } private static Fixture fixture(int maxAttempts) { + return fixture(maxAttempts, 5_000); + } + + private static Fixture fixture(int maxAttempts, long backoffMillis) { AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); AccountConnectScopeRepository connectScopes = mock(AccountConnectScopeRepository.class); AccountTenantMembershipRepository memberships = mock(AccountTenantMembershipRepository.class); @@ -472,7 +523,7 @@ private static Fixture fixture(int maxAttempts) { transactionManager, 10, maxAttempts, - 5_000); + backoffMillis); return new Fixture( service, joinOperations, connectScopes, memberships, auditOutbox, meterRegistry); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 639a6a424b..47404c6da4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -1826,6 +1826,47 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } + @Test + void requestPasswordResetFailsClosedWithoutAuthorizedInternalCaller() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = + new RecordingObserver<>(); + + service.requestPasswordReset( + net.firedevops.firemud.account.v1.RequestPasswordResetRequest.newBuilder() + .setEmail("player@example.com") + .build(), + observer); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void completePasswordResetFailsClosedBeforeTokenConsumption() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = + new RecordingObserver<>(); + + service.completePasswordReset( + net.firedevops.firemud.account.v1.CompletePasswordResetRequest.newBuilder() + .setToken("reset-token") + .setNewPassword("new-password") + .build(), + observer); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void deleteAccountRequiresAdminRole() { PingService pingService = Mockito.mock(PingService.class); From 2015b28f3a0cae8896cc26bab7138b3ac9bcd4b3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 20:23:23 +1300 Subject: [PATCH 48/55] Strengthen JOIN recovery diagnostics and authority proof --- ...nt-and-tenant-scoped-game-relationships.md | 2 +- .../account-service/configuration.md | 4 + .../account-service/runtime-and-data.md | 4 +- .../game-session-service/api-contracts.md | 2 +- .../system-architecture-multi-tenancy.md | 2 +- .../system-architecture-overview.md | 2 +- .../system-architecture-protocol-bridging.md | 6 +- .../system-architecture-reconnection.md | 6 +- design/grpc-docs/grpc-api.md | 4 +- dev-tools/certs/clean-dev-certs.sh | 2 +- dev-tools/certs/ensure-dev-certs.sh | 2 +- dev-tools/certs/generate-dev-certs.sh | 2 +- ...ocal-compose-workload-identity-contract.sh | 30 +++++ .../v1/logging_admin_service.proto | 6 +- .../AccountJoinOperationRepository.java | 22 ++++ .../AccountJoinReconciliationService.java | 45 +++++++ ...ReconciliationPostgresIntegrationTest.java | 31 +++++ .../AccountJoinReconciliationServiceTest.java | 84 ++++++++++++ .../service/impl/AccountGrpcServiceTest.java | 6 +- .../config/GatewayRouteTestSupport.java | 23 +++- .../config/GatewayRouteTestSupportTest.java | 123 ++++++++++++++++++ 21 files changed, 387 insertions(+), 21 deletions(-) create mode 100644 services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java diff --git a/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md b/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md index 0624429fd5..c087be5c21 100644 --- a/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md +++ b/design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md @@ -31,7 +31,7 @@ The current implementation still carries legacy `accounts.tenant_id` drift. That - One global platform account owns credentials, platform-wide username and email identity, recovery state, linked external identities, and account-security lifecycle. - Registration creates only the global account. It does not create tenant membership, roles, a profile, a character, an entitlement, or gameplay authority. - Explicit `JOIN` creates the durable account-to-tenant membership for one game according to the accepted admission contract. -- The canonical membership relation enforces exactly one row per `(account_id, tenant_id)` with a database unique constraint. Account serializes `JOIN` on that membership key. An exact retry with the same request ID and digest replays that operation's stored outcome. A concurrent request with a different request ID or digest waits for the first membership-key transition, then records its own durable no-op outcome referencing the canonical membership; it does not replay another operation's stored result, insert another row, or emit another logical membership event. +- The canonical membership relation enforces exactly one row per `(account_id, tenant_id)` with a database unique constraint. Account serializes `JOIN` on that membership key. An exact retry with the same request ID and digest replays that operation's stored outcome only when the current-policy gate below passes; unavailable or unsafe policy does not permit replay. A concurrent request with a different request ID or digest waits for the first membership-key transition, then records its own durable no-op outcome referencing the canonical membership; it does not replay another operation's stored result, insert another row, or emit another logical membership event. - Every `JOIN` carries a caller-stable operation ID (`requestId`) and a canonical digest whose preimage includes `operationKind=JOIN`, the authenticated account, verified caller binding, verified target, and other authority-bearing inputs. Account persists those inputs with the operation ID, digest, lifecycle status, and terminal outcome in durable storage before returning a terminal result. Before replaying a stored terminal result, Account performs the current-policy check; unavailable or unsafe current policy fails closed without overwriting or re-executing the stored result, and a later retry under the same policy may replay it. A changed policy or digest is rejected as `IDEMPOTENCY_CONFLICT`; an unresolved or ambiguous operation remains pending and never becomes an implicit success. - The membership transition and its durable audit/outbox event are committed atomically with the same persisted `JOIN` operation ID and digest. An exact retry therefore replays that one stored outcome and cannot create a second membership transition or logical event; a concurrent distinct operation records its own no-op outcome after the canonical row is visible and also emits no transition event. The operation record, membership row, transition evidence, and event must be sufficient to reconcile a lost response without re-executing the join. - Leaving is a distinct operation kind with its own stable operation ID, canonical digest, stored outcome, membership transition, and audit/outbox event. A later rejoin is a new `JOIN` operation and a distinct `INACTIVE` -> `ACTIVE` transition; it must not replay or mutate the earlier leave outcome. `JOIN` is not a general lifecycle repair and cannot restore any state other than `INACTIVE`. diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index 5eda41c146..4fcb57454a 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -66,6 +66,10 @@ Changing any of the three JWT lifetime variables—`FIREMUD_AUTH_JWT_EXPIRATION_ Reaching `max-attempts` never terminalizes an uncertain `PENDING` operation: exact readback continues with capped exponential backoff, and attempt count alone is not evidence of commit or absence. Expiry or unavailable readback likewise does not authorize a membership mutation or an invented terminal outcome. The central catalog owns the initial-delay default and cap semantics. +Each invocation samples the aggregate number of `PENDING` operations due at its captured time before loading the bounded, stably ordered page. The `account.join.reconciliation.due.backlog` gauge is the last successful aggregate count; `account.join.reconciliation.due.not.selected` is `max(due backlog - batch-size, 0)`, the estimated due work beyond one page's capacity. The aggregate query reads no operation rows and takes no per-account row locks. These gauges have no account, tenant, or request tags. When the count query fails, both numeric gauges retain their last successful values and `account.join.reconciliation.due.backlog.sample.unknown` becomes `1`; it returns to `0` after a successful sample. The existing `account.join.reconciliation.operations{result="failure"}` counter records the count failure, and the bounded page still runs. + +Operators should alert when `account.join.reconciliation.due.not.selected > 0` while `account.join.reconciliation.due.backlog.sample.unknown == 0`; this means a successful sample found more due work than one invocation can read back. A value of `1` for the unknown gauge means the numeric samples are stale and cannot establish that the backlog is clear; the service logs a warning for each over-capacity sample and for each failed count. The aggregate and page queries use the same captured time but are separate reads, so concurrent rescheduling can make the excess an estimate rather than an exact identity of rows skipped. This is observability only: it does not alter page ordering, retry timing, operation state, or membership. + ## Proto Files The gRPC schemas for this service live in [`protos/account/v1`](../../../../protos/account/v1). Use `./gradlew generateProto` to regenerate Java stubs when the definitions change. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index a5c0b10159..70f8cda196 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -288,11 +288,11 @@ Account-first bootstrap authenticates before tenant selection and accepts config Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers still fail closed before reads because their requests cannot prove caller/target binding, so those local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). -The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Logging receipt behavior is locally implemented, but the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Broader reconnect/cutover consumption of admission-pointer truth and operator pointer tooling are incomplete. +The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Account-side Logging receipt validation is implemented; the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Broader reconnect/cutover consumption of admission-pointer truth and operator pointer tooling are incomplete. `GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows; focused cardinality/retry proof does not establish the full snapshot/freshness contract, including explicit free/trial rows, authoritative current-row selection, `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and delivery. `CommitTenantCapacityAdmission` has a synchronized target request/replay contract including `mutationDigest`, but its RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. -Every current Account deletion entry fails closed unconditionally with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation; no retained-operation check currently enables or blocks deletion. Bounded JOIN receipt cleanup/minimization and deletion reconciliation remain unimplemented retention follow-through. Account's retention/deletion workflow owns that work under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), including safe disposition of retained terminal JOIN receipts and unknown outcomes tracked in #2848. No universal retention duration is implied. +Every current Account deletion entry fails closed unconditionally with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation; no retained-operation check currently enables or blocks deletion. Bounded JOIN receipt retention/deletion cleanup and deletion reconciliation remain unimplemented; producer-payload minimization is implemented but does not establish that cleanup. Account's retention/deletion workflow owns that work under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), including safe disposition of retained terminal JOIN receipts and unknown outcomes tracked in #2848. No universal retention duration is implied. ## Monetization and Notification Domain Notes diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..dc935f8208 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -117,7 +117,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - Admission-pointer requests identify the durable `{tenantId, realmId}` route after selector resolution; read/audit responses carry `worldSlug`/`realmSlug` from the referenced catalog snapshot, the runtime route version separately from catalog/policy revision, and, for private/playtest targets, the positive `playtestStateGeneration`. Public-production admission and first-join membership creation consume current catalog visibility/public-production facts with entitlement checks instead of inferring behavior from `realmSlug`; display-only changes do not become runtime cutovers. - Admission-pointer audit/list responses now also expose the `preparedVersionUpgradeId` used by a cutover write so operator history preserves the same proof identity that the mutation validated; private/playtest audit/readback retains the applicable lifecycle ID and generation, while public-production responses omit them. -**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` also returns `JOIN_REQUIRED` when a membership exists but `gameplayAdmissionAllowed=false`. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. +**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** supplied-authority text `PLAY` returns `JOIN_REQUIRED` only for eligible missing or `INACTIVE` public membership; an `ACTIVE` but non-admitting membership returns `WORLD_ACCESS_DENIED`, consistent with the canonical [Authentication admission boundary](../../system-architecture-authentication.md#in-band-play-admission-boundary). Current connect-token issuance does not yet validate the private/playtest realm grant; see [Authentication implementation status](../../system-architecture-authentication.md#implementation-status) for the owner boundary and status. - **Admission-pointer CAS inputs:** existing-row writes compare the exact `expectedPointerVersion` and `expectedCatalogRevision` pair. The current owner-local no-record insert requires `0/0` as its expected-absent precondition; because no row exists to version-check, insert-race safety comes from runtime-target locking and database uniqueness constraints, not a row-version CAS. Neither condition is proof of realm/catalog initialization or permission to create a pointer. The `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed until their complete owner contracts are supported. Initial admission still requires the separate World lifecycle, canonical realm/catalog identity, pointer/audit transaction, and exact owner-readback proof described in [Initial admission bind](#initial-admission-bind). diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index de4b8b9964..256796a75c 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -22,7 +22,7 @@ Implementation status and execution evidence belong in the owning trackers or PR FireMUD separates **global identity** from **per-game state** so that one person can participate in multiple games without data leakage between tenants. -Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. The required focused proof for this boundary is owned by [Data Separation per Service](#data-separation-per-service) and the [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md); no end-to-end proof yet demonstrates these target invariants. +Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Focused proof requirements for this boundary are owned by [Data Separation per Service](#data-separation-per-service) and the [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md); current implementation and proof status are recorded in the [realm-routing tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md#current-status) and [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). - **Platform account (`accountId`)** – A global identity record managed by the Account Service. Each human player has a single platform account, which is the subject of authentication and JWT issuance. - **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. diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index cce61e5336..814b001f14 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -529,7 +529,7 @@ Gameplay authentication is transport-specific. Credential-bearing Telnet and oth The receiver token is the exact `game-session-account-delegation` JWT profile with audience `account-service`; it is an Account-issued private backend credential, never a client gameplay credential. Its registry and rotation rules do not define the active gameplay-session lifetime or the bounded continuity/reconnect cache lifetime. If the Account response is lost during credential-bearing text login, Game Session retries with the same `requestId` and exact request digest. Account resumes matching pending work or returns the stored committed result/terminal outcome; it must not mint a second token merely because the first response was not observed. A confirmed binding-CAS conflict or superseded binding causes Game Session to keep the candidate unusable and issue Account's idempotent retire request for that exact operation and token identity. An ambiguous timeout instead remains fail-closed and provisional while Game Session reconciles the expected binding generation plus operation identity against the authoritative binding: it retires the candidate only after proving that the CAS did not commit, and completes installation or the canonical superseded outcome when the committed operation is found. Account performs bounded orphan cleanup after the operation's lease/expiry horizon; an orphan registry record is never sufficient to make a gameplay binding admissible. Proof must cover Account success followed by response loss, confirmed binding-CAS conflict, ambiguous CAS reconciliation for both committed and uncommitted outcomes, retry with the same request ID, retry with a conflicting digest, and cleanup/reconciliation after each cross-service failure window. The protocol uses ordered durable evidence, idempotent owner-side operations, and fail-closed provisional state; it does not claim a cross-store transaction. -After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Current admission-reader containment and local response-classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding; Game Session maps a live membership-read failure to `WORLD_ACCESS_DENIED`. Its locally supplied-authority `JOIN_REQUIRED` classification is not live admission proof. The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch now exist locally, but this does not establish frontend or production readiness: PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and membership lifecycle/generation rereads remain unproved. Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). +After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Current admission, implementation, and proof status is recorded by [Authentication](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Session recovery/takeover is authorized by the gameplay binding plus current Account identity, membership, entitlement, and revocation authority; it does not require the previous backend token registry record to remain valid. When transport-specific reauthentication is required, the client must complete the applicable fresh credential/bootstrap and connect-context steps before backend calls resume. A missing or expired prior token therefore causes replacement or reauthentication, not acceptance of stale token state. > 🔗 See [Authentication & Authorization](./system-architecture-authentication.md) and [Reconnection Strategy](./system-architecture-reconnection.md) for detailed JWT format and session flow. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index d7b3aea44b..832b8549dc 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Game Session text `PLAY` validates supplied membership snapshots for exact account/tenant identity and freshness; present memberships require a consistent `ACTIVE`/`INACTIVE` lifecycle and positive membership-version and membership-authority-generation values, while missing membership must be exact `MISSING` evidence with zero versions and no admission. It recommends public `JOIN_REQUIRED` only for missing or `INACTIVE` membership after fresh entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership remains denied. This supplied-authority classification does not establish live admission: Account runtime readers fail closed before data access, and Account connect-token issuance still lacks the required membership-version/authority-generation reread. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Direct-text and first-party end-to-end proof remain incomplete. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Supplied-authority text `PLAY` must validate exact account/tenant identity, freshness, consistent `ACTIVE`/`INACTIVE` lifecycle, and positive membership-version and membership-authority-generation values; missing membership is exact `MISSING` evidence with zero versions and no admission. Public `JOIN_REQUIRED` follows only missing or `INACTIVE` membership after fresh entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership remains denied. Current implementation and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers currently fail closed before data access, so supplied-authority classification is not proof of live admission; composed text/browser proof and connect-token issuance status remain with those owners. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`; Game Session text `PLAY` validates lifecycle, generation, membership version, caller/target identity, and freshness on supplied-authority branches, as described in [Authentication](./system-architecture-authentication.md#implementation-status). `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Account connect-token issuance is a separate partial consumer: it uses membership existence, admission, version, and evaluation-time evidence without the lifecycle/authority-generation checks applied by supplied-authority `PLAY`; the required issuance-time version/generation reread and private/playtest grant validation remain incomplete. These local checks do not establish live composed admission while Account runtime readers fail closed before reads. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Account runtime, supplied-authority `PLAY`, and connect-token issuance implementation and proof status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers currently fail closed before data access, so this target sequence is not live composed admission proof. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -67,7 +67,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. - `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. - `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - On supplied-authority Game Session `PLAY` branches, fresh public-production membership must be missing or `INACTIVE`, and the earlier routing, scope, authority, fresh-entitlement, and `allowPublicJoin` gates must pass. `PLAY` validates exact caller/target identity, lifecycle, membership version, authority generation, and freshness; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Live Account runtime reads still fail before data access, so this local classification does not establish live admission. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. The local Account route/RPC and Game Session text dispatch now exist, but end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Private/playtest membership or grant failure is not a public join fallback. +- `JOIN_REQUIRED` - On supplied-authority Game Session `PLAY` branches, fresh public-production membership must be missing or `INACTIVE`, and the earlier routing, scope, authority, fresh-entitlement, and `allowPublicJoin` gates must pass. `PLAY` validates exact caller/target identity, lifecycle, membership version, authority generation, and freshness; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime readers currently fail before data access, so this supplied-authority classification does not establish live admission; current implementation and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. Private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index a21b6126e0..14e530983b 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,7 +10,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission authority and local classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding; Game Session maps a live membership-read failure to `WORLD_ACCESS_DENIED`. Its locally supplied-authority `JOIN_REQUIRED` classification is not live admission proof. No successful public `PLAY` or first-party browser `JOIN` is established. Account's explicit JOIN operation and direct-text scope/dispatch seams exist locally, while the public Gateway join route remains denied. PostgreSQL execution, direct text-to-Logging proof, unknown-outcome recovery, and the independent connect-token membership-version/authority-generation issuance reread remain open; connect-token issuance retains its separate local response classification and grant-validation gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; the target authority and error detail remain in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission, implementation, and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; token issuance persistence and retention status is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). - **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -78,8 +78,8 @@ A retained-edge upstream rebind, including a qualifying hidden Game Session rest Reconnection uses two distinct client flows: -- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its `JOIN` procedure; local direct-text REALMS-scope/JOIN dispatch and the Account JOIN RPC exist, while PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and lifecycle/generation rereads remain unproved. Ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session's local `PLAY` response classification uses supplied authority and returns `JOIN_REQUIRED` only when eligible public-production membership is missing or `INACTIVE`; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, and the resulting live membership failure maps to `WORLD_ACCESS_DENIED`; local classification does not establish live `JOIN_REQUIRED` or successful public `PLAY`. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. -- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the browser bootstrap join facade exists locally, but the complete frontend/runtime flow and proof remain incomplete. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. +- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its `JOIN` procedure. Ordering, membership classification, and direct-text scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); current implementation and proof status is recorded by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. +- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; current browser/runtime implementation and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 00ba7efbcc..de06574560 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -9834,7 +9834,7 @@ plus scoped tick pause/resume used for rollback safety. | payload_digest | [string](#string) | | | | status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | | outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | -| audit_projection_version | [int32](#int32) | | Version 1 attests an exact receipt linked atomically to a distinct audit log projection. Zero or unsupported versions cannot verify delivery or historical producer provenance. | +| audit_projection_version | [int32](#int32) | | Version 1 attests the receipt/projection link. Positive delivery evidence also requires a COMMITTED receipt and matching receiver identities for the exact scoped outbox row, not payload replay. Zero or unsupported versions cannot verify delivery or historical producer provenance. | @@ -9978,7 +9978,7 @@ plus scoped tick pause/resume used for rollback safety. | status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | | outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| audit_projection_version | [int32](#int32) | | Same receipt/projection attestation as CreateLogEventResponse; never payload replay proof. Zero or unsupported versions cannot verify delivery or historical producer provenance. | +| audit_projection_version | [int32](#int32) | | Same version-1 receipt/projection evidence rule as CreateLogEventResponse: a COMMITTED receipt with receiver identities matching the exact scoped outbox row; it is never payload replay proof. Zero or unsupported versions cannot verify delivery or historical producer provenance. | diff --git a/dev-tools/certs/clean-dev-certs.sh b/dev-tools/certs/clean-dev-certs.sh index d4ec9cf709..1d939ed51d 100644 --- a/dev-tools/certs/clean-dev-certs.sh +++ b/dev-tools/certs/clean-dev-certs.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" # Remove generated certificates so tooling can start from scratch without # deleting the tracked helper scripts in dev-tools/certs/. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index ac45f0721f..8ba80edd3a 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" CERT_DIR="${1:-$SCRIPT_DIR}" GENERATOR="$SCRIPT_DIR/generate-dev-certs.sh" WORKLOAD_NAMESPACE="local" diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index f44715eb86..a24728e1b7 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" refuse_symlink_path() { local path="$1" diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index b74ba14352..93d4f235ba 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -77,6 +77,36 @@ assert_invalid_existing_bundle_is_preserved() { assert_mode 640 "$unmanaged_file" } +# Defaults derived from a copied checkout must use its physical path even +# when each helper is invoked through a symlinked checkout ancestor. +default_path_fixture="$CERT_DIR/default-path-fixture" +default_path_checkout="$default_path_fixture/checkout" +default_path_alias="$default_path_fixture/checkout-alias" +mkdir -p "$default_path_checkout/dev-tools/certs" +for helper in ensure-dev-certs.sh generate-dev-certs.sh clean-dev-certs.sh; do + cp "$ROOT_DIR/dev-tools/certs/$helper" "$default_path_checkout/dev-tools/certs/$helper" +done +ln -s "$default_path_checkout" "$default_path_alias" +default_path_cert_dir="$default_path_checkout/dev-tools/certs" +default_path_alias_cert_dir="$default_path_alias/dev-tools/certs" +bash "$default_path_alias_cert_dir/generate-dev-certs.sh" +[[ -f "$default_path_cert_dir/ca.crt" && -f "$default_path_cert_dir/server.crt" ]] || { + echo "default certificate generation did not write into the copied physical checkout" >&2 + exit 1 +} +bash "$default_path_alias_cert_dir/ensure-dev-certs.sh" +[[ -f "$default_path_cert_dir/local-runtime/default/client.crt" ]] || { + echo "default certificate setup did not write into the copied physical checkout" >&2 + exit 1 +} +bash "$default_path_alias_cert_dir/clean-dev-certs.sh" +[[ ! -e "$default_path_cert_dir/ca.crt" \ + && ! -e "$default_path_cert_dir/local-runtime" \ + && ! -e "$default_path_cert_dir/workloads" ]] || { + echo "default certificate cleanup did not clean the copied physical checkout" >&2 + exit 1 +} + assert_workload_certificate() { local workload="$1" local certificate="$CERT_DIR/local-runtime/$workload/workloads/$workload.crt" diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index 6871831122..764ebf8c6b 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -64,7 +64,8 @@ message CreateLogEventResponse { string payload_digest = 9; AccountAuditReceiptStatus status = 10; AccountAuditReceiptOutcome outcome = 11; - // Version 1 attests an exact receipt linked atomically to a distinct audit log projection. + // Version 1 attests the receipt/projection link. Positive delivery evidence also requires a + // COMMITTED receipt and matching receiver identities for the exact scoped outbox row, not payload replay. // Zero or unsupported versions cannot verify delivery or historical producer provenance. int32 audit_projection_version = 12; } @@ -94,7 +95,8 @@ message ReadLogEventReceiptResponse { AccountAuditReceiptStatus status = 9; AccountAuditReceiptOutcome outcome = 10; shared.v1.ErrorDetail error = 11; - // Same receipt/projection attestation as CreateLogEventResponse; never payload replay proof. + // Same version-1 receipt/projection evidence rule as CreateLogEventResponse: a COMMITTED receipt + // with receiver identities matching the exact scoped outbox row; it is never payload replay proof. // Zero or unsupported versions cannot verify delivery or historical producer provenance. int32 audit_projection_version = 12; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index b5daad6efb..77a5ef6aac 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -77,6 +77,28 @@ public List findDuePendingReconciliation(Instant now, int limit) .fetch(AccountJoinOperationRepository::toJoinOperation); } + /** Counts due PENDING operations without loading rows or taking per-account locks. */ + public long countDuePendingReconciliation(Instant now) { + if (now == null) { + throw new IllegalArgumentException("JOIN reconciliation time is required"); + } + Long count = + dsl.select(org.jooq.impl.DSL.count().cast(Long.class)) + .from(ACCOUNT_JOIN_OPERATIONS) + .where( + ACCOUNT_JOIN_OPERATIONS + .STATUS + .eq("PENDING") + .and( + ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.le( + toLocalDateTime(now)))) + .fetchOne(0, Long.class); + if (count == null) { + throw new IllegalStateException("JOIN reconciliation due-operation count was unavailable"); + } + return count; + } + /** * Records one reconciliation attempt only if the pending row still has the observed attempt count * and due time. The count saturates at the configured diagnostic threshold. A false result means 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 ad98bc3f3b..6160fd25ae 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 @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import java.nio.charset.StandardCharsets; import java.time.DateTimeException; @@ -11,6 +12,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; @@ -61,6 +63,9 @@ public class AccountJoinReconciliationService { private final Counter unresolved; private final Counter failures; private final Counter maxAttemptsReached; + private final AtomicLong dueBacklog = new AtomicLong(); + private final AtomicLong dueButNotSelected = new AtomicLong(); + private final AtomicLong dueBacklogSampleUnknown = new AtomicLong(1); public AccountJoinReconciliationService( AccountJoinOperationRepository joinOperationRepository, @@ -98,11 +103,28 @@ public AccountJoinReconciliationService( this.unresolved = counter(meterRegistry, "unresolved"); this.failures = counter(meterRegistry, "failure"); this.maxAttemptsReached = counter(meterRegistry, "max_attempts_reached"); + Gauge.builder("account.join.reconciliation.due.backlog", dueBacklog, AtomicLong::doubleValue) + .description("Last successfully sampled count of due PENDING Account JOIN operations") + .register(meterRegistry); + Gauge.builder( + "account.join.reconciliation.due.not.selected", + dueButNotSelected, + AtomicLong::doubleValue) + .description("Due JOIN operations beyond the configured bounded page capacity") + .register(meterRegistry); + Gauge.builder( + "account.join.reconciliation.due.backlog.sample.unknown", + dueBacklogSampleUnknown, + AtomicLong::doubleValue) + .description( + "One when the latest due JOIN backlog count failed and retained values are stale") + .register(meterRegistry); } /** Processes one bounded due page using the caller's captured time for deterministic rechecks. */ public void reconcileDueOperations(Instant now) { Objects.requireNonNull(now, "JOIN reconciliation time is required"); + sampleDueBacklog(now); final List dueOperations; try { dueOperations = joinOperationRepository.findDuePendingReconciliation(now, batchSize); @@ -118,6 +140,29 @@ public void reconcileDueOperations(Instant now) { } } + private void sampleDueBacklog(Instant now) { + try { + long count = joinOperationRepository.countDuePendingReconciliation(now); + long excess = count > batchSize ? count - batchSize : 0L; + dueBacklog.set(count); + dueButNotSelected.set(excess); + dueBacklogSampleUnknown.set(0); + if (count > batchSize) { + logger.warn( + "JOIN reconciliation due backlog {} exceeds bounded page size {} by {}", + count, + batchSize, + excess); + } + } catch (RuntimeException ex) { + failures.increment(); + dueBacklogSampleUnknown.set(1); + logger.warn( + "JOIN reconciliation due backlog count is unavailable; retaining the last successful sample ({})", + ex.getClass().getSimpleName()); + } + } + /** Convenience entry point for direct operational invocation. */ public void reconcileDueOperations() { reconcileDueOperations(Instant.now()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index dafec6feae..167cc948af 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -138,6 +138,37 @@ void reconciliationIntentDefaultUsesUtcForDueReadbackInNonUtcDatabaseSession() { }); } + @Test + void dueAggregateCountsOnlyPendingRowsDueAtTheCapturedTime() { + Instant capturedNow = Instant.now().plusSeconds(10); + long baselineCount = joinOperationRepository.countDuePendingReconciliation(capturedNow); + + JoinFixture due = committedEvidencePendingFixture(); + JoinFixture future = committedEvidencePendingFixture(); + JoinFixture terminal = fixture("active"); + JoinPublicProductionResult terminalResult = join(terminal); + assertThat(terminalResult.success()).isTrue(); + assertThat(terminalResult.outcomeCode()).isEqualTo("JOINED"); + + LocalDateTime futureDueAt = + LocalDateTime.ofInstant(capturedNow.plusSeconds(3_600), ZoneOffset.UTC); + assertThat( + dsl.execute( + "UPDATE account_join_operations SET next_reconciliation_attempt_at = ? WHERE request_id = ? AND status = 'PENDING'", + futureDueAt, + future.requestId())) + .isEqualTo(1); + + assertThat(joinOperationRepository.countDuePendingReconciliation(capturedNow)) + .isEqualTo(baselineCount + 1); + List duePage = + joinOperationRepository.findDuePendingReconciliation(capturedNow, 100); + assertThat(duePage).extracting(JoinOperation::requestId).contains(due.requestId()); + assertThat(duePage) + .extracting(JoinOperation::requestId) + .doesNotContain(future.requestId(), terminal.requestId()); + } + @Test void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplicates() { JoinFixture fixture = fixture("active"); 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 ef7a89bbb1..9df682a400 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 @@ -55,6 +55,86 @@ class AccountJoinReconciliationServiceTest { private static final String REALM_SLUG = "production"; private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + @Test + void dueBacklogMetricsExposeBoundedPageExcessWithoutLoadingRows() { + Fixture fixture = fixture(3); + when(fixture.joinOperations.countDuePendingReconciliation(NOW)).thenReturn(14L); + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)).thenReturn(List.of()); + + fixture.service.reconcileDueOperations(NOW); + + assertThat(reconciliationGauge(fixture, "due.backlog")).isEqualTo(14); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isEqualTo(4); + assertThat(reconciliationGauge(fixture, "due.backlog.sample.unknown")).isZero(); + verify(fixture.joinOperations).findDuePendingReconciliation(NOW, 10); + verify(fixture.joinOperations, never()).lockAccount(ACCOUNT_ID); + } + + @Test + void dueBacklogMetricsClearWhenTheSampledQueueFallsBelowThePage() { + Fixture fixture = fixture(3); + when(fixture.joinOperations.countDuePendingReconciliation(NOW)).thenReturn(12L, 2L, 0L); + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)).thenReturn(List.of()); + + fixture.service.reconcileDueOperations(NOW); + assertThat(reconciliationGauge(fixture, "due.backlog")).isEqualTo(12); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isEqualTo(2); + + fixture.service.reconcileDueOperations(NOW); + assertThat(reconciliationGauge(fixture, "due.backlog")).isEqualTo(2); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isZero(); + + fixture.service.reconcileDueOperations(NOW); + assertThat(reconciliationGauge(fixture, "due.backlog")).isZero(); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isZero(); + assertThat(reconciliationGauge(fixture, "due.backlog.sample.unknown")).isZero(); + } + + @Test + void dueBacklogCountFailureKeepsLastSampleAndStillRunsReadbackSafely() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + when(fixture.joinOperations.countDuePendingReconciliation(NOW)) + .thenReturn(13L) + .thenThrow(new IllegalStateException("transient count failure")); + when(fixture.joinOperations.findDuePendingReconciliation(NOW, 10)) + .thenReturn(List.of(), List.of(pending)); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_SCOPE_EVIDENCE_ABSENT", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + fixture.service.reconcileDueOperations(NOW); + + assertThat(reconciliationGauge(fixture, "due.backlog")).isEqualTo(13); + assertThat(reconciliationGauge(fixture, "due.not.selected")).isEqualTo(3); + assertThat(reconciliationGauge(fixture, "due.backlog.sample.unknown")).isEqualTo(1); + verify(fixture.joinOperations, org.mockito.Mockito.times(2)) + .findDuePendingReconciliation(NOW, 10); + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "JOIN_SCOPE_EVIDENCE_ABSENT", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verifyNoInteractions(fixture.memberships, fixture.auditOutbox); + assertThat(reconciliationCounter(fixture, "failure")).isEqualTo(1); + } + @Test void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { Fixture fixture = fixture(5); @@ -738,6 +818,10 @@ private static double reconciliationCounter(Fixture fixture, String result) { .count(); } + private static double reconciliationGauge(Fixture fixture, String suffix) { + return fixture.meterRegistry.get("account.join.reconciliation." + suffix).gauge().value(); + } + private record Fixture( AccountJoinReconciliationService service, AccountJoinOperationRepository joinOperations, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 47404c6da4..c4e571d952 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -671,7 +671,11 @@ void credentialMethodsRejectAbsentAndWrongGameSessionPeersBeforeServiceCall() { new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/world-management-service", WORKLOAD_NAMESPACE, - "world-management-service")); + "world-management-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); for (GrpcPeerIdentity peer : rejectedPeers) { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java index f85f946417..9e818e6563 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java @@ -9,9 +9,13 @@ import org.springframework.cloud.gateway.filter.FilterDefinition; import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition; import org.springframework.cloud.gateway.route.RouteDefinition; +import org.springframework.http.server.PathContainer; +import org.springframework.web.util.pattern.PathPatternParser; final class GatewayRouteTestSupport { + private static final PathPatternParser PATH_PATTERN_PARSER = new PathPatternParser(); + private GatewayRouteTestSupport() {} static RouteDefinition route(GatewayProperties gatewayProperties, String routeId) { @@ -63,6 +67,12 @@ static void assertNoConfiguredPath(GatewayProperties gatewayProperties, String p .collect(Collectors.toSet()); assertThat(configuredPaths).doesNotContain(path); + if (isConcretePath(path)) { + assertThat(configuredPaths) + .noneMatch( + configuredPath -> + PATH_PATTERN_PARSER.parse(configuredPath).matches(PathContainer.parsePath(path))); + } } static void assertNoRouteWithPathAndMethod( @@ -74,7 +84,8 @@ static void assertNoRouteWithPathAndMethod( route.getPredicates().stream() .filter(predicate -> "Path".equalsIgnoreCase(predicate.getName())) .flatMap(predicate -> predicate.getArgs().values().stream()) - .anyMatch(path::equals) + .anyMatch( + configuredPath -> pathPatternMatches(configuredPath, path)) && (route.getPredicates().stream() .noneMatch( predicate -> "Method".equalsIgnoreCase(predicate.getName())) @@ -91,10 +102,20 @@ static void assertSocialChatAndFriendsAreEdgeGated(GatewayProperties gatewayProp assertThat(gatewayProperties.getRoutes().stream().map(RouteDefinition::getId)) .doesNotContain("social-chat", "social-friends"); assertNoConfiguredPath(gatewayProperties, "/api/social/**"); + assertNoConfiguredPath(gatewayProperties, "/api/social/chat/messages"); + assertNoConfiguredPath(gatewayProperties, "/api/social/friends"); assertNoConfiguredPathStartsWith(gatewayProperties, "/api/social/chat"); assertNoConfiguredPathStartsWith(gatewayProperties, "/api/social/friends"); } + private static boolean isConcretePath(String path) { + return path.indexOf('*') < 0 && path.indexOf('{') < 0 && path.indexOf('}') < 0; + } + + private static boolean pathPatternMatches(String configuredPath, String probePath) { + return PATH_PATTERN_PARSER.parse(configuredPath).matches(PathContainer.parsePath(probePath)); + } + static void assertHasStripPrefixTwo(GatewayProperties gatewayProperties, String routeId) { assertHasStripPrefix(gatewayProperties, routeId, "2"); } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java new file mode 100644 index 0000000000..0e093e9b69 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition; +import org.springframework.cloud.gateway.route.RouteDefinition; + +class GatewayRouteTestSupportTest { + + @Test + void assertNoConfiguredPathRejectsWildcardAndPathVariableMatches() { + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/design/**"), null)), + "/api/design/assets")) + .isInstanceOf(AssertionError.class); + + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/design/{resource}"), null)), + "/api/design/assets")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoConfiguredPathPreservesExactWildcardPatternAssertion() { + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/social/**"), null)), "/api/social/**")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoRouteWithPathAndMethodRejectsMatchingWildcardAndPathVariableRoutes() { + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), "POST")), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/{resource}"), "POST")), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoRouteWithPathAndMethodTreatsMissingMethodAsMatchingAndOtherMethodAsNonmatching() { + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), null)), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + + assertThatCode( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), "GET")), + "/api/design/assets", + "POST")) + .doesNotThrowAnyException(); + + assertThatCode( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/other/**"), "POST")), + "/api/design/assets", + "POST")) + .doesNotThrowAnyException(); + } + + @Test + void assertNoRouteWithPathAndMethodChecksEveryConfiguredPathPattern() { + RouteDefinition route = route(List.of("/api/unrelated/**", "/api/design/{resource}"), "POST"); + + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route), "/api/design/assets", "POST")) + .isInstanceOf(AssertionError.class); + } + + private static GatewayProperties gatewayProperties(RouteDefinition... routes) { + GatewayProperties properties = new GatewayProperties(); + properties.setRoutes(List.of(routes)); + return properties; + } + + private static RouteDefinition route(List paths, String method) { + RouteDefinition route = new RouteDefinition(); + List predicates = new java.util.ArrayList<>(); + PredicateDefinition pathPredicate = new PredicateDefinition(); + pathPredicate.setName("Path"); + LinkedHashMap pathPatterns = new LinkedHashMap<>(); + for (int index = 0; index < paths.size(); index++) { + pathPatterns.put("_genkey_" + index, paths.get(index)); + } + pathPredicate.setArgs(pathPatterns); + predicates.add(pathPredicate); + if (method != null) { + predicates.add(new PredicateDefinition("Method=" + method)); + } + route.setPredicates(predicates); + return route; + } +} From 546dbb1b42e78865be750a9e02efb0eba5734307 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 20:43:25 +1300 Subject: [PATCH 49/55] Tighten audit projection proof and centralize bridge status --- .../system-architecture-protocol-bridging.md | 2 +- .../repository/AccountRepositoryIntegrationTest.java | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 832b8549dc..79d693e202 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. In current Game Session `PLAY`, focused unit tests exercise conditional response classification using supplied Account membership and entitlement evidence. The live Account membership, entitlement, and grant RPCs require the trusted Game Session peer but return `FAILED_PRECONDITION` before reading data; Game Session maps the membership failure to `WORLD_ACCESS_DENIED`. Thus those tests do not establish live `JOIN_REQUIRED` or successful composed public `PLAY` through these handlers. The local Account JOIN operation and Game Session text dispatch exist, while direct-text end-to-end proof and membership lifecycle/generation rereads remain incomplete; the public Gateway `/api/account/auth/bootstrap/join` route remains denied. Account connect-token issuance remains a separate Account-owned surface: current public membership/policy and non-public enrollment/access outcomes belong to that endpoint and do not establish text `PLAY` results. In particular, `CONNECT_TOKEN_REJECTED` is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from an Account endpoint error with the same name. Detailed current implementation and proof status remains with [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md). +The precedence and error rows below are the normative target inventory. Current implementation and proof status is recorded in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). In particular, `CONNECT_TOKEN_REJECTED` is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from an Account endpoint error with the same name. Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. 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 a557f5b334..5e0a5b1117 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 @@ -325,7 +325,14 @@ void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { jdbc.update( "UPDATE account_audit_outbox SET receiver_audit_projection_version = 2 WHERE audit_event_id = ?", committedEventId)) - .isInstanceOf(org.springframework.dao.DataAccessException.class); + .isInstanceOf(org.springframework.dao.DataAccessException.class) + .hasStackTraceContaining("account_audit_outbox_projection_version_check"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_audit_projection_version FROM account_audit_outbox WHERE audit_event_id = ?", + Integer.class, + committedEventId)) + .isEqualTo(1); assertThat(outbox.pending(10, Instant.now())) .noneMatch(envelope -> envelope.auditEventId().equals(minimizedEventId)) .noneMatch(envelope -> envelope.auditEventId().equals(committedEventId)); From 754883f364ccb3cda7b753554d37bd8abd03362f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:04:56 +1300 Subject: [PATCH 50/55] Clarify canonical identity and JOIN capability status --- .../architecture/system-architecture-authz-route-matrix.yaml | 4 ++-- design/architecture/system-architecture-frontend.md | 2 +- design/architecture/system-architecture-multi-tenancy.md | 4 +++- .../design-alignment/consequential-decision-inventory.md | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 95d75a76fd..e585bb6981 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -1185,9 +1185,9 @@ routes: implementation_status: known_drift: - membership_authority_generation_snapshot_and_consumer_proof_remains_target_only - - join_unknown_database_outcome_recovery_and_reconciliation_remains_target_only + - bounded_Account_readback_reconciler_is_implemented_locally_but_PostgreSQL_runtime_unknown_outcome_and_concurrency_proof_remain_unavailable - join_audit_receipt_retention_and_safe_watermark_proof_remains_target_only - - postgresql_runtime_and_direct_text_end_to_end_proof_unavailable + - direct_text_to_Logging_end_to_end_proof_unavailable - service: game-session-service route: PLAY scope: tenant diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 42855b4488..029da17661 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -134,7 +134,7 @@ All new frontend features that interact with protected APIs should reuse the sha - `ADMISSION_POINTER_UNAVAILABLE` – Keep the current auth state for reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid catalog/pointer evidence, show a retriable gameplay-admission unavailable message, rerun bootstrap discovery or reconciliation, and only then retry lobby admission with bounded backoff; never substitute a cached tenant or runtime target. Unreachable or timed-out pointer authority is `AUTH_UNAVAILABLE` instead. - Target-state `REALM_UNAVAILABLE` – Keep the current auth state when the resolved realm pointer is complete and `CLOSED`, create no gameplay binding, and wait for fresh discovery or an authoritative availability change rather than fast-looping retries. This is distinct from reachable invalid pointer evidence (`ADMISSION_POINTER_UNAVAILABLE`) and unreachable or timed-out pointer authority (`AUTH_UNAVAILABLE`). - `CONNECT_CONTEXT_INVALID` – Keep the current auth state, force gameplay reconnect flow (`connect-token` refresh + new socket + `LOGIN`), and block `PLAY` retries on the current socket. -- `CONNECT_SCOPE_MISMATCH` – Keep the current auth state, discard the entire discovery snapshot bundle and all connect-token metadata derived from it, including `realmId` and `catalogRevision`, and rerun bootstrap discovery. Do not expose an actionable current repair until the required issuance reread and runtime/deployment proof are complete; the local join route/writer and text dispatch already exist. Target behavior additionally completes `Join & Play` when the newly selected public target requires membership, performs required character discovery/creation, requests a fresh connect token only from the newly returned bundle, and retries on a new socket. +- `CONNECT_SCOPE_MISMATCH` – **Current limitation:** Keep the current auth state, discard the entire discovery snapshot bundle and all connect-token metadata derived from it, including `realmId` and `catalogRevision`, and rerun bootstrap discovery. Do not expose an actionable current repair until the required issuance reread and runtime/deployment proof are complete; the local join route/writer and text dispatch already exist. **Target behavior:** Complete `Join & Play` when the newly selected public target requires membership, perform required character discovery/creation, request a fresh connect token only from the newly returned bundle, and retry on a new socket. Client rule for discovery-issued selectors: diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 256796a75c..3038cd0283 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -22,7 +22,9 @@ Implementation status and execution evidence belong in the owning trackers or PR FireMUD separates **global identity** from **per-game state** so that one person can participate in multiple games without data leakage between tenants. -Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Focused proof requirements for this boundary are owned by [Data Separation per Service](#data-separation-per-service) and the [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md); current implementation and proof status are recorded in the [realm-routing tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md#current-status) and [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). +Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. Current implementation and proof status are recorded in the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). + +The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Focused proof requirements for this boundary are owned by [Data Separation per Service](#data-separation-per-service) and the [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md); current implementation and proof status are recorded in the [realm-routing tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md#current-status). - **Platform account (`accountId`)** – A global identity record managed by the Account Service. Each human player has a single platform account, which is the subject of authentication and JWT issuance. - **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. diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 0fee2e6a3f..4dadf1f083 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -149,7 +149,7 @@ No implementation-blocking import override is active. Record an override here wi ### Packet 2: Identity, Authority, And Security -Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`; the Account explicit `JOIN` path, including browser `POST /auth/bootstrap/join`, and direct-text REALMS-scope/JOIN dispatch now exist locally. Current Account authority-reader containment and local `PLAY` classification are recorded in [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status), [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status): runtime membership, entitlement, and grant reads fail closed with `FAILED_PRECONDITION` before Account data access pending typed caller/target binding, and the live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`. The supplied-authority `JOIN_REQUIRED` classification is a local seam, not live admission proof. Full workflow/deployment/PostgreSQL/direct text-to-Logging proof, pending unknown-outcome reconciliation, and membership lifecycle/generation rereads remain open. The target admission contract remains owned by [Authentication](../../architecture/system-architecture-authentication.md#login-and-session-flow); current implementation and proof gaps are tracked in the [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status), including [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof). The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices, not proof claims. +Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`. The target admission contract remains owned by [Authentication](../../architecture/system-architecture-authentication.md#login-and-session-flow). Implementation and proof status belong to [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status), [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status), including [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof). The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices. Packet 2 count reconciliation: the 31 reviewed decisions are covered by the checked dispositions for ADRs 0020-0050, excluding the historical service-scan alias. The Packet 2 disposition contains exactly those 31 reviewed decisions; the alias is navigation-only and is not a checked disposition row. From da8d9cbe176992ab71ca8c417426a31d6eb3b118 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:18:54 +1300 Subject: [PATCH 51/55] Clarify Telnet proof and bound client certificate failures --- .../tcp-proxy-service/protocols.md | 2 +- dev-tools/certs/ensure-dev-certs.sh | 5 ++- ...ocal-compose-workload-identity-contract.sh | 33 +++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index 22ce3c5559..420ef18c3a 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -110,7 +110,7 @@ Current rules: - any future adapter-carried attach hint must remain advisory and must not bypass the current conditional `JOIN` path described above or the target discovery-first sequence owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. -- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, while otherwise admitting existing members may use the abbreviated current `LOGIN` -> `PLAY` -> `LOOK` path. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). +- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, but successful `LOGIN` -> `PLAY` -> `LOOK` admission is not established because the live Account membership handler rejects before reading and Game Session maps that failure to `WORLD_ACCESS_DENIED`. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Metrics give observability into each Telnet connection while keeping Prometheus label cardinality bounded: diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 8ba80edd3a..f40151d47a 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -193,7 +193,10 @@ ensure_compose_mtls_certs() { return 1 fi done - openssl verify -CAfile "$authority_dir/ca.crt" "$authority_dir/client.crt" >/dev/null + if ! openssl verify -CAfile "$authority_dir/ca.crt" "$authority_dir/client.crt" >/dev/null 2>&1; then + echo "Compose mTLS shared client certificate does not verify under authority CA." >&2 + return 1 + fi if ! certificate_matches_private_key "$authority_dir/client.crt" "$authority_dir/client.key"; then echo "Compose mTLS shared client certificate and private key do not match." >&2 return 1 diff --git a/dev-tools/tests/local-compose-workload-identity-contract.sh b/dev-tools/tests/local-compose-workload-identity-contract.sh index 93d4f235ba..6aa4b54066 100644 --- a/dev-tools/tests/local-compose-workload-identity-contract.sh +++ b/dev-tools/tests/local-compose-workload-identity-contract.sh @@ -457,6 +457,39 @@ assert_invalid_existing_bundle_is_preserved "$key_mismatch_case" key-mismatch other_authority="$CERT_DIR/other-authority" bash "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" "$other_authority" >/dev/null + +# An invalid shared client leaf in the run-owned Compose authority fixture +# fails closed with a bounded certificate diagnostic. +compose_mtls_run_id="invalid-client-cert-${BASHPID}" +compose_mtls_project="firemud-smoke-$compose_mtls_run_id" +compose_mtls_ownership="$CERT_DIR/compose-mtls-ownership" +compose_mtls_project_key="$(printf '%s' "$compose_mtls_project" | sha256sum | awk '{print $1}')" +compose_mtls_fixture="$compose_mtls_ownership/$compose_mtls_project_key.grpc-mtls" +mkdir -m 700 -- "$compose_mtls_ownership" + +ensure_owned_compose_mtls_fixture() { + FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$compose_mtls_ownership" \ + FIREMUD_SMOKE_RUN_ID="$compose_mtls_run_id" \ + COMPOSE_PROJECT_NAME="$compose_mtls_project" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$compose_mtls_fixture" +} + +ensure_owned_compose_mtls_fixture >/dev/null +cp -- "$other_authority/client.crt" "$compose_mtls_fixture/authority/client.crt" +chmod 644 "$compose_mtls_fixture/authority/client.crt" +compose_mtls_invalid_output="$CERT_DIR/invalid-compose-mtls-client.output" +if ensure_owned_compose_mtls_fixture >"$compose_mtls_invalid_output" 2>&1; then + echo "ensure-dev-certs accepted an untrusted Compose mTLS shared client certificate" >&2 + exit 1 +fi +rg -Fq 'Compose mTLS shared client certificate does not verify under authority CA.' \ + "$compose_mtls_invalid_output" || { + echo "ensure-dev-certs did not report the untrusted Compose mTLS shared client certificate" >&2 + cat "$compose_mtls_invalid_output" >&2 + exit 1 +} + wrong_issuer_case="$CERT_DIR/invalid-wrong-issuer-bundle" copy_generic_bundle "$CERT_DIR" "$wrong_issuer_case" for file in server.crt server.key client.crt client.key dev-cert.pem dev-key.pem; do From 75a8b74a187ed5e211f94e1ae055723f4e98d398 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 00:11:41 +1300 Subject: [PATCH 52/55] test(account): strengthen containment fixtures and proof status --- .../architecture/system-architecture-reconnection.md | 2 +- .../player-experience-commands-and-communication.md | 4 ++-- .../realm-routing-and-playable-state.md | 2 +- .../repository/AccountMigrationVersionTest.java | 11 +++++++++-- .../service/impl/VirtualCurrencyGrpcServiceTest.java | 4 +++- .../config/GatewayRouteTestSupport.java | 4 +--- 6 files changed, 17 insertions(+), 10 deletions(-) diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 14e530983b..93af0314a4 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -11,7 +11,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. - **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission, implementation, and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; token issuance persistence and retention status is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). -- **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. +- **Runtime authority checks** – `PLAY` attempts membership and tenant-entitlement checks before fresh entry or resume/takeover, but its local classification uses supplied authority and does not prove positive live checks. Account's runtime readers fail closed before data reads until typed caller/target binding is available; see [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift). - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index ffaad4e18a..642a7f6e1e 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -49,9 +49,9 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path. Realm and character discovery helpers are currently not required ceremony. `PlayCommandHandler` has focused unit response-classification coverage for supplied missing/`INACTIVE` public membership and fresh entitlement/policy evidence. In the live composition, Account's trusted-peer runtime membership, entitlement, and grant handlers return `FAILED_PRECONDITION` before reading; Game Session maps the membership response to `WORLD_ACCESS_DENIED`, and no successful composed public `PLAY` or live `JOIN_REQUIRED` through those handlers is established. Account connect-token issuance has separate current checks and outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority retains the applicable unavailable/invalid-authority outcome. An unambiguous eligible `PLAY` branch enters directly when its required authority is supplied; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical admission behavior and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text behavior exposes `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path. `PlayCommandHandler` has focused unit response-classification coverage for supplied membership and entitlement/policy responses. In live composition, Account runtime membership, entitlement, and grant readers fail closed before data access; Game Session maps the membership failure to `WORLD_ACCESS_DENIED`, so successful composed public `PLAY` and live `JOIN_REQUIRED` are not established. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispatch now exist locally; the browser bootstrap facade is present, but its public Gateway route remains denied and target-only. Account's transactional audit outbox and producer-side typed receipt validation/verified-projection marker are implemented locally; Logging & Admin receiver persistence/readback remains unavailable and unproved under #2940. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, and direct text-to-Logging end-to-end coverage; a bounded Account worker now reads back abandoned JOIN `PENDING` intents, but that does not prove those runtime/recovery outcomes. The proto/producer exposes lifecycle/generation fields, and focused `PlayCommandHandlerTest` cases exercise `JOIN_REQUIRED` classification with supplied membership and fresh entitlement/policy responses. Live Account runtime readers still reject before data access, so that conditional unit behavior does not establish a live `JOIN_REQUIRED` or successful public `PLAY`; Game Session maps the live `FAILED_PRECONDITION` response to `WORLD_ACCESS_DENIED`. Complete event/authority-tuple propagation and reconnect-freshness proof remain incomplete, as does the connect-token membership-authority-generation reread. Connect-token missing-membership/policy-denial mappings have focused `AccountServiceImplTest` coverage. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispatch now exist locally; the browser bootstrap facade is present, but its public Gateway route remains denied and target-only. Account's transactional audit outbox and producer-side typed receipt validation/verified-projection marker are implemented locally; Logging & Admin receiver persistence/readback remains unavailable and unproved under #2940. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, direct text-to-Logging end-to-end coverage, complete event/authority-tuple propagation, and reconnect freshness. The bounded Account worker reads back abandoned JOIN `PENDING` intents, but this does not prove runtime/recovery outcomes. Connect-token membership-authority-generation reread remains incomplete; focused Account unit coverage exercises missing-membership and policy-denial mappings. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation 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 9886230dc6..d584ced5ea 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 @@ -57,7 +57,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res Account's explicit public-production membership writer and Game Session direct-text JOIN invocation are implemented locally; first-party browser JOIN remains blocked at Gateway. Game Session validates lifecycle, membership version, authority generation, caller/target identity, and freshness on supplied-authority PLAY branches, and recommends public JOIN_REQUIRED only for missing or INACTIVE membership after fresh entitlement and allowPublicJoin checks. An ACTIVE but non-admitting membership is denied. The proto's uint64 generation and incomplete Account issuance reread/private-grant validation remain implementation gaps; live Account readers fail before data access, so composed admission is unproved. Canonical admission rules belong to [Authentication](../../architecture/system-architecture-authentication.md#implementation-status); Account and Game Session implementation/proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). -First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. Current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate the applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. +First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. On fresh `/auth/connect-token` issuance or a replay-cache miss, the current path revalidates pointer/visibility and membership but does not validate the applicable grant; a cached-success replay can return before those fresh reads. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; the current bare-world-slug selection re-resolves current authority only when unique in the catalog. Canonical tenant-scoped stable selector resolution remains a separate gap. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, terminal-outcome recovery, and direct text-to-Logging proof remain unproved. Account's bounded readback-only worker for abandoned JOIN `PENDING` intents is implemented, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and complete pending-operation recovery/reconciliation remain open. This is distinct from the browser/WebSocket bootstrap snapshot. 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 211338bcfb..d469ec4998 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 @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; +import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @@ -12,9 +13,15 @@ class AccountMigrationVersionTest { @Test - void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws IOException { + void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() + throws IOException, URISyntaxException { List migrations; - try (var files = Files.list(Path.of("src/main/resources/db/migration"))) { + var migrationDirectory = + Path.of( + Objects.requireNonNull( + AccountMigrationVersionTest.class.getClassLoader().getResource("db/migration")) + .toURI()); + try (var files = Files.list(migrationDirectory)) { migrations = files .map(path -> Objects.requireNonNull(path.getFileName()).toString()) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java index 6d21109aae..2c73d0ff03 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java @@ -91,7 +91,9 @@ public void onNext(T value) { } @Override - public void onError(Throwable t) {} + public void onError(Throwable error) { + throw new AssertionError("Expected an application-level fail-closed response", error); + } @Override public void onCompleted() {} diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java index 9e818e6563..79c4d7cb19 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java @@ -69,9 +69,7 @@ static void assertNoConfiguredPath(GatewayProperties gatewayProperties, String p assertThat(configuredPaths).doesNotContain(path); if (isConcretePath(path)) { assertThat(configuredPaths) - .noneMatch( - configuredPath -> - PATH_PATTERN_PARSER.parse(configuredPath).matches(PathContainer.parsePath(path))); + .noneMatch(configuredPath -> pathPatternMatches(configuredPath, path)); } } From 1c4f3c004db342e928da124d519a6bf0ad95a93b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 00:45:54 +1300 Subject: [PATCH 53/55] Clarify Account proof boundaries and cover unauthenticated deletion denial --- .../account-service/runtime-and-data.md | 4 ++-- .../account-service/stripe-integration.md | 2 +- .../decision-inventory-cross-cutting.md | 2 +- .../realm-routing-and-playable-state.md | 2 +- .../service/impl/AccountGrpcServiceTest.java | 16 ++++++++++++++++ 5 files changed, 21 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index db56ab42d6..36bc17b464 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -58,7 +58,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. - **Target state:** global Account registration creates only global account/security state and a platform-scoped audit outbox entry in the same transaction; successful JOIN records a separate tenant-scoped event using its exact committed `tenantId`. Account preserves one stable event identity and envelope across retries. Logging & Admin owns the typed receipt, exact-payload digest, readback, minimized-evidence, and retention contract; see [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Logging & Admin is not a second authority for Account state. -- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; unavailable, timeout, mismatched, and ambiguous responses leave that identity `PENDING` and never mint a replacement. The receiver's target exact payload-byte digest validation and durable readback remain unavailable in this front; the producer cannot treat its request/response validation as proof that those separate receiver capabilities exist. After a matching terminal minimized receipt, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. +- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; unavailable, timeout, mismatched, and ambiguous responses leave that identity `PENDING` and never mint a replacement. The receiver's target exact payload-byte digest validation and durable readback remain unavailable in this front; the producer cannot treat its request/response validation as proof that those separate receiver capabilities exist. After a matching receipt supplies both terminal status and minimized evidence, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. - JOIN first commits a policy-independent `PENDING` intent; only an available entitlement result binds the policy digest, `allowPublicJoin`, and entitlement version for the membership/outbox/outcome transaction. An expired scope on a retained `PENDING` request returns retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation. The bounded Account reconciler is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence, while absent or uncertain evidence remains pending with capped diagnostics and backoff. It never reissues an expired scope or terminalizes by expiry or attempt limit. PostgreSQL unknown-outcome/concurrency proof remains open. - **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN append to the durable outbox and validate matching receipt responses as described above; receipt delivery/readback remains fail-closed until the separate receiver capability is present and proved. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). @@ -290,7 +290,7 @@ Account-first bootstrap authenticates before tenant selection and accepts config Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers still fail closed before reads because their requests cannot prove caller/target binding, so those local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). -The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Account-side Logging receipt validation is implemented; the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Broader reconnect/cutover consumption of admission-pointer truth and operator pointer tooling are incomplete. +The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Account-side Logging receipt validation is implemented; the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Reconnect flow consumption of admission-pointer truth remains incomplete; replacement cutover flow consumption remains incomplete, and operator pointer tooling is incomplete. `GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows; focused cardinality/retry proof does not establish the full snapshot/freshness contract, including explicit free/trial rows, authoritative current-row selection, `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and delivery. `CommitTenantCapacityAdmission` has a synchronized target request/replay contract including `mutationDigest`, but its RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 721f8b3916..493d0e244c 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -173,7 +173,7 @@ The Account Service exposes gRPC and REST endpoints for initiating and inspectin - `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred and gated. The RPC returns `FAILED_PRECONDITION` before `PaymentService` or Stripe invocation, so it cannot create a v1 entitlement. The underlying provider-mutating method remains unsupported. Only a separately typed hosting-billing operation may call Stripe. - `CreateDonation` – Existing generic donation substrate; unsupported/deferred and gated. The RPC returns `FAILED_PRECONDITION` before service/provider invocation; its retained provider-mutating method remains unsupported and is not a v1 product path. - `RefundPayment` – Existing generic refund substrate; unsupported/deferred and gated. The RPC preserves `success=false` and returns a `FAILED_PRECONDITION` `ErrorDetail` before service/provider dispatch. Hosting refunds use a separately typed operation and durable workflow; future marketplace refunds require the accepted value-conservation contract. -- `CreateSubscription` – Target one recurring hosting subscription for an immutable `tenantId` and initial `plan_code`, with caller-stable `requestId`, explicit instrument selection, and Account-resolved billing-owner authorization. Account computes the versioned digest from normalized fields and the resolved owner; neither owner nor digest is caller supplied. Exact retries replay the durable operation and changed intent returns `IDEMPOTENCY_CONFLICT`; provider `subscription_provisioning_request_id` remains a separate identity. The current proto lacks the caller retry identity, owner-resolution evidence, and instrument-selection input, so the handler fails with `FAILED_PRECONDITION` before local/provider mutation rather than manufacturing an active subscription. +- `CreateSubscription` – Target one recurring hosting subscription for an immutable `tenantId` and initial `plan_code`, with caller-stable `requestId`, explicit instrument selection, and Account-resolved billing-owner authorization. Account computes the versioned digest from normalized fields and the resolved owner; neither owner nor digest is caller supplied. Exact retries replay the durable operation and changed intent returns `IDEMPOTENCY_CONFLICT`; provider `subscription_provisioning_request_id` remains a separate identity. The current proto lacks the caller-stable `requestId`, owner-resolution evidence, and instrument-selection input, so the handler fails with `FAILED_PRECONDITION` before local/provider mutation rather than manufacturing an active subscription. - `UpdateSubscription` – Apply a plan, instrument, cancellation, or other supported mutation to an existing immutable `subscriptionId` using a distinct operation identity and expected row version; it rejects creation-only fields and any `tenantId` change. - `TransferBillingOwner` – Start or recover the audited provider-replacement handoff through the `subscription_transfer` state machine and guarded update of the canonical subscription row. - Subscription and transaction query APIs – Must be split into explicit tenant-scoped billing-safe, cross-tenant support-safe, and cross-tenant billing-safe variants (no mixed-mode endpoint behavior). Per-tenant caller-bound billing history is visible to `tenantAdmin`; global `platformAdmin`/`billingAdmin` access uses cross-tenant billing-safe variants only. diff --git a/design/project-management/design-alignment/decision-inventory-cross-cutting.md b/design/project-management/design-alignment/decision-inventory-cross-cutting.md index dfaed2d834..c1be33d38b 100644 --- a/design/project-management/design-alignment/decision-inventory-cross-cutting.md +++ b/design/project-management/design-alignment/decision-inventory-cross-cutting.md @@ -94,7 +94,7 @@ The first 22 source-index entries are the counted cross-cutting partition. `WE`, | Key | Primary capability | Secondary capabilities | Question -> current choice | Status | I/R | Sources / explicit ADR | Strongest alternative | ADR recommendation | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `AUTH-01` | `AA-3.1` | `AA-2.1`, `AA-3.3`, `SF-1.2` | What identifies gameplay selection/admission and controller ownership? Stable `worldSlug`/`realmSlug` and snapshot-bound ordinals are lobby selectors. Selection/admission resolves the authoritative gameplay binding `{tenantId, realmId, gameInstanceId, characterId}` plus the applicable pointer/fence, `playableStateNamespaceId`, and server-derived scope evidence; `gameInstanceId` remains the active-runtime fence/value, and slugs and ordinals never grant authority. Separately, the single-controller uniqueness key is exactly `{tenantId, playableStateNamespaceId, characterId}`; `gameInstanceId` is not part of controller uniqueness. | `accepted-explicit` | H/hard | `AU § Contract Decisions (Normative)`; `MT § Identity & Tenant Model`; [ADR 0168](../../architecture/decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [Session Behavior](../../architecture/system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) | Opaque handles for every selection, durable slug authority, fresh-catalog ordinal reuse, or per-instance controller identity. | Human review revised and superseded ADR 0005 on 2026-07-21. ADRs 0122 and 0132 continue to own stable playable-state namespaces and namespace-scoped controller transfer. | -| `AUTH-02` | `AA-2.1` | `PO-2.2`, `PO-2.1`, `SF-1.3`, `EA-3.1` | What is the player authentication sequence? Public `WORLDS` remains a browse-only pre-authentication mode. The target authenticated WebSocket flow is player bootstrap -> membership-aware discovery -> conditional explicit `JOIN` for first public-production entry -> character selection or creation -> single-use connect token -> WebSocket -> bare `LOGIN` -> `PLAY`. Browsers carry the token in the protected cookie; explicitly classified non-browser WebSocket clients use the dedicated handshake header. Returning members skip the public-production `JOIN` step only after the target current `ACTIVE` membership and exact reread evidence pass. Grant-backed admission requires existing durable `membershipLifecycleState=ACTIVE` membership and separately validates the applicable realm grant; a grant never creates or substitutes for membership. A nonmember must use the Account-owned membership lifecycle, such as explicit `JOIN`/`Join & Play` for eligible public production, before admission. Telnet and other non-WebSocket text clients retain credential-bearing protocol `LOGIN`. Ordinary gameplay supports `PASSWORD` or verified-email `EMAIL_OTP` without mandatory TOTP. **Current state:** the dedicated non-browser WebSocket handshake header is target-only and unavailable; unsupported header use is rejected as `CONNECT_TOKEN_REJECTED` without cookie fallback or carrier inference. Game Session validates lifecycle, authority-generation, membership-version, and evaluation-time fields in local `PLAY` response classification. Supplied-authority local classification returns `JOIN_REQUIRED` only for missing or `INACTIVE` eligible public-production membership after fresh positive entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so no live `JOIN_REQUIRED` or successful public `PLAY` is established; the resulting live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same policy gates, while its membership-version/authority-generation issuance rereads remain unproved. Account `JOIN` and direct-text dispatch/scope seams exist locally, but the public Gateway JOIN route remains denied. PostgreSQL, pending-outcome recovery, and direct text-to-Logging proof remain open. | `accepted-explicit` | H/hard | [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0029](../../architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md); `AU § Login and Session Flow`; `GW § Tenant-Aware Edge Connect Token (Gameplay Handshake)`; `RC § When Reauthentication Is Required` | Complete WebSocket login at the handshake, replay credentials in WebSocket `LOGIN`, or require TOTP/WebAuthn for every gameplay connection. | Revised and accepted by human decision; ADR 0021 records the sequence and factors, while ADR 0029 subsequently standardizes connect-token carriage for every public non-proxy WebSocket. | +| `AUTH-02` | `AA-2.1` | `PO-2.2`, `PO-2.1`, `SF-1.3`, `EA-3.1` | What is the player authentication sequence? Public `WORLDS` remains a browse-only pre-authentication mode. The target authenticated WebSocket flow is player bootstrap -> membership-aware discovery -> conditional explicit `JOIN` for first public-production entry -> character selection or creation -> single-use connect token -> WebSocket -> bare `LOGIN` -> `PLAY`. Browsers carry the token in the protected cookie; explicitly classified non-browser WebSocket clients use the dedicated handshake header. Returning members skip the public-production `JOIN` step only after the target current `ACTIVE` membership and exact reread evidence pass. Grant-backed admission requires existing durable `membershipLifecycleState=ACTIVE` membership and separately validates the applicable realm grant; a grant never creates or substitutes for membership. A nonmember must use the Account-owned membership lifecycle, such as explicit `JOIN`/`Join & Play` for eligible public production, before admission. Telnet and other non-WebSocket text clients retain credential-bearing protocol `LOGIN`. Ordinary gameplay supports `PASSWORD` or verified-email `EMAIL_OTP` without mandatory TOTP. | `accepted-explicit` | H/hard | [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0029](../../architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md); `AU § Login and Session Flow`; `GW § Tenant-Aware Edge Connect Token (Gameplay Handshake)`; `RC § When Reauthentication Is Required` | Complete WebSocket login at the handshake, replay credentials in WebSocket `LOGIN`, or require TOTP/WebAuthn for every gameplay connection. | Revised and accepted by human decision; ADR 0021 records the sequence and factors, while ADR 0029 subsequently standardizes connect-token carriage for every public non-proxy WebSocket. Implementation status and proof gaps are tracked in the [Player Access and Session tracker](../implementation-tracking/player-access-and-session.md#current-status). | | `AUTH-03` | `AA-1.3` | `AA-1.2`, `AA-1.5`, `AA-2.3`, `SF-1.3`, `SF-2.2` | Who owns identity, revocation, entitlements, and gameplay bindings? Account owns durable account, token, revocation, membership, entitlement, and the single issued-token registry authority; JWT-presenting registry-backed control-plane, bootstrap, and admission operations perform exactly one registry lookup, while Game Session owns gameplay bindings and derives typed execution context and Gateway has only bounded edge checks. The dedicated `gameplay-connect` artifact remains outside the issued-token registry and uses its own single-use replay fence. | `accepted-explicit` | H/hard | [ADR 0022](../../architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); `AU § Responsibility Split`; `OV § Authentication Modes and Boundaries`; `RM § Notes on Movement and Moderation Contracts` | Introduce a dedicated IAM service, make Gateway the general identity authority, or use TTL-only tokens. | Affirmed by human decision; ADR 0022 records one writer per authority and separates accepted design from revocation/session implementation gaps. | | `AUTH-04` | `SF-1.3` | `AA-1.2`, `PO-1.1`, `PO-2.1`, `PO-4.4` | How are protected routes authorized? One machine-readable route policy governs strict token profiles, explicit tenant/cross-tenant scopes, generated completeness checks, and runtime denial of unclassified routes; services retain domain checks. | `accepted-explicit` | H/hard | [ADR 0023](../../architecture/decisions/adr-0023-central-route-authorization-governance.md); `AU § Auth Middleware Algorithm (Normative)`; `AU § Global Role to Route-Class Matrix (Normative)`; `OV § Admin Entry Points and Traffic Surfaces` | Service-local role checks, Gateway-only authorization, or a general-purpose external policy engine. | Revised and accepted by human decision; policy/proof upkeep is an accepted security tradeoff and current enforcement gaps are explicit. | | `AUTH-05` | `SF-1.3` | `SF-1.2`, `SF-1.1`, `GR-1.1`, `PO-3.2` | How is internal player delegation trusted? Concrete mTLS workload identity and exact method caller allowlists authorize the trusted gameplay service; unsigned typed `PlayerExecutionContext` carries validated scope, while mutations retain operation-specific idempotency. | `accepted-explicit` | H/hard | [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md); `AU § Gameplay Player Execution Context Contract (Normative)`; `SE § Gameplay Workload Trust`; `GR § TLS Requirements` | Per-RPC signed/replay-guarded attestations, signed attestations without replay storage, or generic backend JWTs carrying player identity. | Revised and accepted by human decision after two-sided adversarial review; the current first-party trust domain explicitly accepts allowlisted-intermediary impersonation risk to avoid universal hot-path attestation cost. | 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 d584ced5ea..ebd5c70052 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 @@ -95,7 +95,7 @@ The legacy Automation `PATCH /factions/{id}/reputation` controller has been remo ### Recorded Proof -The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet end-to-end proved. The evidence records focused proof for the local Account JOIN writer and direct-text scope/request handoff in addition to sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, and logout handling (the recorded `LOGOUT_UNAVAILABLE` case fails closed and does not prove successful logout activation), tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove the full `WORLDS`, `REALMS`, `JOIN`, `CHARS`, and `PLAY` sequence, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, complete separated-revision consumer convergence, or bounded active-session drain. Account's bounded PENDING readback worker does not establish PostgreSQL/lost-acknowledgement proof or terminal-outcome recovery. These are historical validation facts; the decision review did not rerun them. +The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet end-to-end proved. The evidence records focused proof for the local Account JOIN writer and direct-text scope/request handoff in addition to sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, and logout handling (the recorded `LOGOUT_UNAVAILABLE` case fails closed and does not prove successful logout activation), tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove the full `WORLDS`, `REALMS`, `JOIN`, `CHARS`, and `PLAY` sequence, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, complete separated-revision consumer convergence, or bounded active-session drain. First-party bootstrap and local protocol proof do not establish selected-realm `PLAY`: the `Entity.ListCharactersByAccount` request and response still lack stable namespace proof; see the [Entity Management runtime/data status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). Account's bounded PENDING readback worker does not establish PostgreSQL/lost-acknowledgement proof or terminal-outcome recovery. These are historical validation facts; the decision review did not rerun them. ## Active Gaps diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index c4e571d952..04a234ba9f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -1669,6 +1669,22 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } + @Test + void deleteAccountRejectsMissingSessionBeforeUnavailableWorkflow() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + SessionContext.clear(); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.deleteAccount(DeleteAccountRequest.newBuilder().setAccountId("2").build(), observer); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void deleteAccountRejectsZeroAccountIdBeforeDelete() { PingService pingService = Mockito.mock(PingService.class); From 72d540819aa3b3da985eca86d95dd94c20dc295d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:23:14 +1300 Subject: [PATCH 54/55] 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 9a9f2ecd4a..b564f15ee3 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 afcca7c140b5e8312a578ffd029bf98f35fa561d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:28:26 +1300 Subject: [PATCH 55/55] 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 b564f15ee3..9d69e3b49f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1011,7 +1011,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) {