From 1b37fd0a76353c52f6458036f972756e6148d4d1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 13:12:48 +1300 Subject: [PATCH 01/46] Converge runtime membership carrier wording on tenant map --- design/architecture/system-architecture-frontend.md | 2 +- .../system-architecture-jwt-and-token-contracts.md | 2 +- design/architecture/system-architecture-redis-ops-access.md | 2 +- design/architecture/system-architecture-redis.md | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 846fe46c0c..c4af428a55 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -101,7 +101,7 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - **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 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. + - 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 exact one-tenant `membershipVersion` map 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 complete map 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. - The React client does not store or expose `control-ui` JWTs for gameplay. It may hold only the short-lived, memory-only `player-bootstrap` token described in the authentication design and use it solely for gameplay bootstrap surfaces such as bootstrap discovery, bootstrap-authenticated character discovery and character creation, `POST /auth/bootstrap/join`, and `POST /auth/connect-token`. diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index add7da17bc..c014230df3 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -45,7 +45,7 @@ The pre-v1 grant cutover is direct: a JWT, issued-token registry record, authori The tuple is copied without renaming or reinterpretation into every applicable registry-backed JWT/registry claim, payload, lease, binding, refresh request, rebind proof, and installation acknowledgement. `issuanceFence` is copied alongside the tuple as the Account composite authority fence captured by the issuance transaction or CAS; it is not a substitute for any tuple member. -For persisted and cross-service gameplay carriers specifically, `membershipVersion` is the exact one-tenant map `{tenantId: version}` in the gameplay binding, Account lease, `rebindHandle`, rotation carrier, and exact retry evidence. Each carrier compares the complete key/value map, not a scalar or a partial/merged value. This does not change the scalar shape of Account's `GetTenantMembershipForRuntime` response; the map is the gameplay-carrier representation only. The map remains a separate predicate from `authorityTuple.membershipAuthorityGeneration`, which must also be compared exactly. +For Account's `GetTenantMembershipForRuntime` response and persisted or cross-service gameplay carriers, `membershipVersion` is the exact one-tenant map `{tenantId: version}`. The response, gameplay binding, Account lease, `rebindHandle`, rotation carrier, and exact retry evidence compare the complete key/value map, not a scalar or a partial/merged value. A receiver may extract a scalar for process-local calculations only after validating that map; it must not transmit or persist the scalar as `membershipVersion`. The map remains a separate predicate from `authorityTuple.membershipAuthorityGeneration`, which must also be compared exactly. For the `gameplay-connect` token and `X-Firemud-Connect-Context`, Account derives the caller-bound `authorityTuple.membershipAuthorityGeneration` and the separate `membershipVersion` map from the same authoritative membership snapshot for the exact selected tenant. They remain independent predicates and neither may be reconstructed from the other, a cached projection, or a later read. Before continuation, including reconnect/resume, Game Session must compare both values together against one fresh Account membership snapshot; if either comparison cannot be established from that snapshot, continuation fails closed. diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index e6c815ca6a..8697f429fc 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -203,7 +203,7 @@ The public CLI surface listed above is target state only; it is not currently im - **Canonical `RecoveryEvidenceField` definition:** `RecoveryEvidenceField = { kind: VALUE, value: T } | { kind: NOT_APPLICABLE }`, where `kind` is the closed enum `{VALUE, NOT_APPLICABLE}`. The persisted and wire representation of the non-applicable arm is exactly `{kind: "NOT_APPLICABLE"}`; null, omission, blank strings, `""`, `"N/A"`, `"NONE"`, numeric or boolean sentinels, arbitrary identifiers, and any unrecognized enum value are rejected before persistence, comparison, acknowledgement, or recovery. Every recovery carrier and evidence field references this definition; carrier classes define only which fields are applicable and must not restate the union or assign alternate sentinel semantics. The shorthand `field=NOT_APPLICABLE` below means that exact tagged union arm. - Recovery carriers use the versioned discriminator `recoveryCarrierSchemaVersion=1` and closed `recoveryCarrierClass` values: `STANDALONE_BINDING_LOCAL`, `PARENT_OWNED_REGION_TENANT_LOCAL`, `LINKED_GLOBAL_CHILD`, and `STANDALONE_GLOBAL_OPERATION`. `STANDALONE_BINDING_LOCAL` is the standalone binding-local arm: every parent/child-only identity, lifecycle, and fence field plus `linkRevision` is the exact typed `NOT_APPLICABLE` arm, while the local operation's own applicable `operationFence`, local scope, and local coverage evidence remain concrete as applicable. `PARENT_OWNED_REGION_TENANT_LOCAL` is not that arm: it carries the applicable `parentRecoveryOperationId`, `parentLifecycle`, parent `operationFence`/`parentOperationFence`, distinct `parentCoverageFence`, exact parent `resolvedScope`, and concrete `linkRevision`; child-only fields are `NOT_APPLICABLE` unless a separate linked child edge makes them applicable. `LINKED_GLOBAL_CHILD` carries only the child-owned identity, lifecycle, operation/coverage fences, scope, snapshot, acknowledgements, and coverage generation; the parent tuple remains on its independent edge and parent-consumption record. `STANDALONE_GLOBAL_OPERATION` carries the exact typed `NOT_APPLICABLE` parent arm and self-binds its own global operation identity, lifecycle, operation fence, scope, snapshot, and coverage evidence. Validators reject missing or fabricated class-specific fields, including a parent tuple on a standalone binding-local or child result, a `NOT_APPLICABLE` parent tuple on parent-owned local repair, or a missing `resolvedScope`/`linkRevision` on a parent-owned local carrier. - All carrier classes reference the canonical definition above. They do not redefine `NOT_APPLICABLE`, use nullable fields, or introduce class-specific sentinel values. -- Rebind `membershipVersion` has one canonical carrier shape everywhere: `type MembershipVersionMap = { [tenantId: TenantId]: MembershipVersion }`, with runtime cardinality exactly one, the sole key equal to the binding's `tenantId`, and the value equal to the Account-issued version. The preserved `schemaVersion=2` payload, Account's opaque `rebindHandle` binding (shown only as Account-side evidence), the Game Session binding, rebind request/validation/readback, and every example must use this exact map. A scalar, null, omitted map, blank or differently keyed tenant, extra tenant, aggregate/latest value, or a map merged from separate carriers fails closed. Account's `GetTenantMembershipForRuntime` response remains scalar; only the persisted and cross-service gameplay carrier wraps that value in this exact one-tenant map, independently from `authorityTuple.membershipAuthorityGeneration`. +- Rebind `membershipVersion` has one canonical carrier shape everywhere: `type MembershipVersionMap = { [tenantId: TenantId]: MembershipVersion }`, with runtime cardinality exactly one, the sole key equal to the binding's `tenantId`, and the value equal to the Account-issued version. Account's `GetTenantMembershipForRuntime` response, the preserved `schemaVersion=2` payload, Account's opaque `rebindHandle` binding (shown only as Account-side evidence), the Game Session binding, rebind request/validation/readback, and every example must use this exact map. A scalar, null, omitted map, blank or differently keyed tenant, extra tenant, aggregate/latest value, or a map merged from separate carriers fails closed. A receiver may use a scalar only for process-local calculations after validating the exact map; `authorityTuple.membershipAuthorityGeneration` remains an independent predicate. - Canonical rebind carrier example (the handle remains opaque; `handleBinding` is conceptual Account-side evidence): ```json diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 2e92f3f34d..e82d5d20d2 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -288,7 +288,7 @@ Authenticated gameplay session keys capture: - Socket binding metadata and transport details. - Active `characterId` / `tenantId` context plus the target resolved `playableStateNamespaceId` and server-derived `playableStateScope` for the character binding. The target one-controller key is `{tenantId, playableStateNamespaceId, characterId}`; the binding value/evidence retains `sessionId`, `gameInstanceId`, and `bindingGeneration`. - Target-state authenticated-session contract (not a current runtime guarantee): server-side auth token identity used for Account and other control-plane calls on behalf of this session (`authTokenHash`, `authTokenIssuedAt`, `authTokenExpiresAt`, and `tokenGeneration`), so planned refresh, resume, and mid-session revocation checks can be performed without exposing JWTs to gameplay clients. For the exact active registry record, `authTokenIssuedAt == registry.iat`, `authTokenExpiresAt == registry.exp`, and `tokenGeneration == registry.tokenGeneration`; these are equality checks, not lower/upper-bound checks against Redis TTL or the current time. -- The protected `rebindHandle`, immutable continuity anchor `continuityBindingExpiresAt`, complete `membershipBaseline`, and complete `authorityTuple` are required to complete a restart or resume rotation and verify that gameplay admission authority still exists without exposing the private delegation JWT to gameplay clients. The baseline includes the exact one-tenant `membershipBaseline.membershipVersion` map `{tenantId: version}` from the same Account snapshot as its lifecycle state and membership authority generation. The exact nested tuple field is `authorityTuple.membershipAuthorityGeneration`; it is stored as part of the complete tuple and is never replaced by a standalone tuple member. A duplicate top-level `membershipAuthorityGeneration` field outside the baseline and tuple is forbidden; readers and CAS scripts reject it rather than merging it with or choosing precedence over the nested fields. The Account-issued handle binds the exact token hash, signed `jti` and `nbf`, token lineage, gameplay binding, unchanged complete `membershipBaseline`, complete canonical `outboxCheckpoints` set, authority tuple, and exact `issuanceFence` captured for that issuance; only Account may open and validate it, and Game Session treats it as opaque. Account's `GetTenantMembershipForRuntime` response remains scalar; only `membershipBaseline.membershipVersion` wraps that value in the exact one-tenant map for the persisted and cross-service gameplay carrier. +- The protected `rebindHandle`, immutable continuity anchor `continuityBindingExpiresAt`, complete `membershipBaseline`, and complete `authorityTuple` are required to complete a restart or resume rotation and verify that gameplay admission authority still exists without exposing the private delegation JWT to gameplay clients. The baseline includes the exact one-tenant `membershipBaseline.membershipVersion` map `{tenantId: version}` from the same Account snapshot as its lifecycle state and membership authority generation. The exact nested tuple field is `authorityTuple.membershipAuthorityGeneration`; it is stored as part of the complete tuple and is never replaced by a standalone tuple member. A duplicate top-level `membershipAuthorityGeneration` field outside the baseline and tuple is forbidden; readers and CAS scripts reject it rather than merging it with or choosing precedence over the nested fields. The Account-issued handle binds the exact token hash, signed `jti` and `nbf`, token lineage, gameplay binding, unchanged complete `membershipBaseline`, complete canonical `outboxCheckpoints` set, authority tuple, and exact `issuanceFence` captured for that issuance; only Account may open and validate it, and Game Session treats it as opaque. Account's `GetTenantMembershipForRuntime` response carries the exact one-tenant map too; the persisted gameplay baseline retains and compares it without scalarizing. - The binding also stores the complete canonical `outboxCheckpoints` set: one exact `{outboxStreamKey, outboxSequence}` entry for every applicable authority stream, canonicalized in stream-key order. It is independent freshness evidence, not an aggregate maximum or an authority replacement. Binding refresh atomically replaces the complete `membershipBaseline`, `authorityTuple`, and complete checkpoint set from one Account-issued binding lease; rebind, token rotation, and their retry carriers carry the baseline unchanged and compare the complete object, including the exact tenant key, value, and map shape of `membershipBaseline.membershipVersion`, never a scalar, omitted map, merged value, or aggregate-only checkpoint. `membershipBaseline.membershipVersion` remains an independent predicate from both `membershipBaseline.membershipAuthorityGeneration` and `authorityTuple.membershipAuthorityGeneration`. - Tick-region participation metadata (for example active region bindings and reconnect context). Per-entity command queues remain under `tick:{tenantRegionTag}:queue:` and are reset-tolerant coordination state, not durable session payload. - Session-local coordination metadata (for example reconnect state, transport-level pacing, and other per-connection ephemeral fields). @@ -425,8 +425,8 @@ The canonical preserved-session rebind predicate requires all of the following b - A complete canonical `schemaVersion=2` authenticated gameplay session payload, including `issuanceFence`, `rebindHandle`, `continuityBindingExpiresAt`, the complete `membershipBaseline` with its exact one-tenant `membershipBaseline.membershipVersion` map and `membershipBaseline.membershipAuthorityGeneration`, the complete `authorityTuple` including its separate `authorityTuple.membershipAuthorityGeneration`, and the complete canonical `outboxCheckpoints` set; a missing, `schemaVersion=1`, unsupported, duplicate-field, or incomplete record fails closed and cannot be rebound. - Target-state exact-token predicate (not a current runtime guarantee): an exact `session:auth:token:` registry record addressed by the payload's `authTokenHash` that is present, active, unrevoked, and unexpired. The binding's `authTokenIssuedAt`, `authTokenExpiresAt`, and `tokenGeneration` must equal the registry record's `iat`, `exp`, and `tokenGeneration` exactly; Redis TTL, current time, or a newer/older value cannot satisfy any of those fields. Account must validate the payload's opaque `rebindHandle` and prove that its bound token hash, signed `jti` and `nbf`, token lineage, account identity, profile, audience, and exact `issuanceFence` match that registry record and the gameplay binding exactly. The registry is authoritative for `jti`, `tokenGeneration`, `iat`, and `exp`; the Account-validated handle is authoritative for the original signed `nbf`, exact issuance fence, and expected exact-token identity used for comparison. Neither source may substitute for or repair the other, and Game Session must not parse or invent those handle values locally. -- The Account-validated `rebindHandle` must also bind and match the gameplay binding's complete unchanged `membershipBaseline` and complete stream-key-ordered `outboxCheckpoints` set. The baseline comparison is exact over every member, including presence, one tenant key, the version value in `membershipBaseline.membershipVersion`, and `membershipBaseline.membershipAuthorityGeneration`, and is independent from the separate `authorityTuple.membershipAuthorityGeneration` predicate. A scalarized baseline map or checkpoint set, missing baseline member, extra-tenant, differently keyed, stale, regressed, contradictory, or aggregate-only membership value or checkpoint fails closed; scalar authentication fields retain their declared scalar types. Rebind must not merge handle and binding values or retain only a latest checkpoint. Account's `GetTenantMembershipForRuntime` response remains scalar and is not changed by this persisted/cross-service carrier requirement. -- Current Account authority for the exact account and tenant, including the applicable `issuerAuthGeneration`, `accountAuthorityGeneration`, `tenantAuthorityGeneration`, `authorityTuple.membershipAuthorityGeneration`, and non-public realm-grant identity (ordinary private or playtest, always lifecycle-bound) and `grantVersion` when applicable, plus the complete current `membershipBaseline` from one authoritative Account snapshot, public-production entitlement, revocation, authority-freshness lease, and the complete exact `outboxCheckpoints` set for every applicable authority stream. The scalar membership version from `GetTenantMembershipForRuntime` is wrapped only as the exact one-tenant `membershipBaseline.membershipVersion` map inside that complete gameplay carrier. Missing, extra, stale, regressed, or aggregate-only baseline or checkpoint evidence fails closed. For an entitlement read that is unavailable, only the same-binding public-production continuity fallback below may apply; it never supplies current authority evidence. +- The Account-validated `rebindHandle` must also bind and match the gameplay binding's complete unchanged `membershipBaseline` and complete stream-key-ordered `outboxCheckpoints` set. The baseline comparison is exact over every member, including presence, one tenant key, the version value in `membershipBaseline.membershipVersion`, and `membershipBaseline.membershipAuthorityGeneration`, and is independent from the separate `authorityTuple.membershipAuthorityGeneration` predicate. A scalarized baseline map or checkpoint set, missing baseline member, extra-tenant, differently keyed, stale, regressed, contradictory, or aggregate-only membership value or checkpoint fails closed; scalar authentication fields retain their declared scalar types. Rebind must not merge handle and binding values or retain only a latest checkpoint. Account's `GetTenantMembershipForRuntime` response and the persisted carrier both use the same exact one-tenant map shape. +- Current Account authority for the exact account and tenant, including the applicable `issuerAuthGeneration`, `accountAuthorityGeneration`, `tenantAuthorityGeneration`, `authorityTuple.membershipAuthorityGeneration`, and non-public realm-grant identity (ordinary private or playtest, always lifecycle-bound) and `grantVersion` when applicable, plus the complete current `membershipBaseline` from one authoritative Account snapshot, public-production entitlement, revocation, authority-freshness lease, and the complete exact `outboxCheckpoints` set for every applicable authority stream. The exact one-tenant `membershipVersion` map from `GetTenantMembershipForRuntime` is retained as `membershipBaseline.membershipVersion` inside that complete gameplay carrier, without scalarizing or reconstructing it. Missing, extra, stale, regressed, or aggregate-only baseline or checkpoint evidence fails closed. For an entitlement read that is unavailable, only the same-binding public-production continuity fallback below may apply; it never supplies current authority evidence. - A valid `continuityBindingExpiresAt` and either the immutable `resumeDeadline` for a disconnected binding or a trusted connected-session fallback proof when the binding remains connected and `resumeDeadline` is absent. The proof is bound to the exact session/binding identity, `binding_generation`, `authTokenHash`, `issuanceFence`, connection episode with `connectionState=CONNECTED`, and positive Account entitlement evaluation; it carries `connectedSessionDeadline = evaluatedAt + 5 minutes`, using the Account-stamped `evaluatedAt` and the same synchronized-clock/skew rules as the entitlement continuity window. Socket liveness, Redis key presence/TTL, current time, reconnect attempts, and token rotation cannot create or extend that proof. The rebind does not extend any deadline, together with the current operation/region epoch and lease-fence evidence. - A successful invocation of the region-lease bridge with the validated identity and generation; the canonical session record, `session:game:index:*`, and `sessionctx:*` are not authority substitutes. From 7ec19003cc6f403ffaf76983efb9944d40f53d4f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 13:27:22 +1300 Subject: [PATCH 02/46] Assemble fenced membership snapshot evidence without enabling RPC --- .../account-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 2 + ...countMembershipAuthorityEventProducer.java | 401 ++++++++++++++---- .../AccountJoinPostgresIntegrationTest.java | 107 ++++- .../NeverJoinedMembershipSnapshotTest.java | 127 +++++- 5 files changed, 521 insertions(+), 118 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1cffa6fb33..4c8e646aa7 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -28,6 +28,8 @@ The live runtime membership response carries `accountId`, `tenantId`, `membershi 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. +An unwired Account membership-snapshot reader now forms an exact one-tenant version map, a complete ordered four-stream checkpoint set, and separate positive membership source-event evidence only from a fenced local transaction. Its issuer, account, and tenant streams can presently prove sequence zero only while their durable generation and source-version baselines remain at one and no committed outbox head exists; advanced upstream history fails closed until its source-event proof is implemented. A never-joined pair's positive version/generation baseline and absence history are read under the same fence; a changed account-local issuance fence is preserved. This reader is not the gRPC response, does not authenticate the runtime caller, and does not enable the denied method or Game Session admission. + 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. 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 3160dda159..4863d687e0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca The unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's exact one-tenant `membershipVersion` map in the producer, strict shared codec, canonical digest vectors, immutable evidence, and Account exact retry/readback comparisons. The Account producer may extract a local numeric value only after validating the map; it does not persist or transmit a scalar event field. Shared codec and Account/Game Session vector tests execute locally; PostgreSQL JOIN/reconciliation tests compile but skip without Docker, and the runtime membership RPC remains denied until its complete same-snapshot producer and consumer proof is ready. The unactivated Account ring materializer also binds a dedicated service-account username in the protected source record and checks the server-reported identity before Secret access, but sole-writer RBAC, protected custody, authenticated receipt, deployment readback, and live readiness remain unproved, so no Account ring mount is published. +The staged Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. This is a local producer boundary, not a wire response or Game Session consumer: the runtime RPC remains denied. The exact local Account check executed 377 unit tests, while all 78 PostgreSQL integration tests were skipped without Docker, including the new advanced-upstream negative case. + 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 durable post-logout episode fencing 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/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index a28f9627bf..7f51db151c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -3,7 +3,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -52,6 +54,11 @@ value = "EI_EXPOSE_REP2", justification = "Injected repositories are internal Spring collaborators.") public class AccountMembershipAuthorityEventProducer { + private static final Comparator OUTBOX_CHECKPOINT_ORDER = + Comparator.comparing( + OutboxCheckpointEntry::outboxStreamKey, + AccountMembershipAuthorityEventProducer::compareUnsignedUtf8); + private final AccountJoinOperationRepository joinOperationRepository; private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; private final AccountRepository accountRepository; @@ -173,6 +180,8 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( throw new IllegalStateException( "Current Account membership differs from its V31 authority generation"); } + List upstreamCheckpoints = + readBaselineUpstreamCheckpoints(identity, authoritySnapshot); String streamKey = membershipStreamKey(identity); Checkpoint checkpoint = @@ -211,19 +220,25 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( "MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType()), authoritySnapshot); + List checkpoints = new ArrayList<>(upstreamCheckpoints); + checkpoints.add( + new OutboxCheckpointEntry( + checkpoint.outboxStreamKey(), Long.toString(checkpoint.outboxSequence()))); + checkpoints = orderedCheckpoints(checkpoints); return new PositiveMembershipSnapshot( true, verified.accountId(), verified.tenantId(), verified.membershipLifecycleState(), verified.gameplayAdmissionAllowed(), - membershipVersionValue(verified, identity), + membershipVersionMap(verified, identity), verified.membershipAuthorityGeneration(), verified.roles(), verified.authorityTuple(), verified.issuanceFence(), Instant.now(), - List.of(checkpoint), + checkpoints, + List.of(sourceEvidence(checkpoint, event)), transitionReceipt, verified); } @@ -244,7 +259,9 @@ public PositiveMembershipSnapshot enrollProvenRetainedActivePair( identity.tenantUuid(), verifiedProvenance(identity), new ProvenPositiveCheckpoint( - Long.parseLong(positive.membershipVersion()), + Long.parseLong( + membershipVersionValue( + positive.membershipVersion(), identity.tenantUuid().toString())), Long.parseLong(positive.membershipAuthorityGeneration()), Long.parseLong(event.outboxSequence()), event.eventId(), @@ -268,7 +285,10 @@ public PositiveMembershipSnapshot readCurrentPairBoundPositiveMembershipSnapshot MembershipEvent event = positive.authorityEvent(); if (!verifiedProvenance(identity).equals(pair.provenance()) || !pair.membershipExists() - || pair.membershipVersion() != Long.parseLong(positive.membershipVersion()) + || pair.membershipVersion() + != Long.parseLong( + membershipVersionValue( + positive.membershipVersion(), identity.tenantUuid().toString())) || pair.membershipAuthorityGeneration() != Long.parseLong(positive.membershipAuthorityGeneration()) || pair.lastEventSequence() != Long.parseLong(event.outboxSequence()) @@ -289,17 +309,15 @@ public PositiveMembershipSnapshot readCurrentPairBoundPositiveMembershipSnapshot @Transactional(propagation = Propagation.MANDATORY) public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( long accountId, long legacyTenantId) { + if (accountId <= 0L || legacyTenantId <= 0L) { + throw new IllegalArgumentException("Account and retained tenant identities must be positive"); + } joinOperationRepository.lockAccount(accountId); Identity identity = resolveIdentity(accountId, legacyTenantId); if (membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId).isPresent()) { throw new IllegalStateException("Never-joined Account membership row is not absent"); } transitionReceiptRepository.assertNewMembershipTransitionCanStart(accountId, legacyTenantId); - String streamKey = membershipStreamKey(identity); - if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { - throw new IllegalStateException( - "Never-joined Account membership has committed event history"); - } PairAuthority pair = pairAuthorityRepository .readForUpdate(identity.accountUuid(), identity.tenantUuid()) @@ -307,7 +325,11 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( CompositeSnapshot authority = readSnapshot(identity); ScopeState member = only(authority.memberships(), "membership"); requireMatchingFence(authority, member, identity.accountUuid()); - requireNoUnmodeledCutoff(identity); + List upstreamCheckpoints = + readBaselineUpstreamCheckpoints(identity, authority); + String streamKey = membershipStreamKey(identity); + OutboxCheckpointEntry membershipCheckpoint = + requireSequenceZeroCheckpoint(streamKey, member, "membership"); if (!verifiedProvenance(identity).equals(pair.provenance()) || pair.membershipExists() || pair.lastEventSequence() != 0L @@ -327,15 +349,20 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( List.of(), Optional.empty(), Optional.empty()); + List checkpoints = new ArrayList<>(upstreamCheckpoints); + checkpoints.add(membershipCheckpoint); + checkpoints = orderedCheckpoints(checkpoints); return new NeverJoinedMembershipSnapshot( identity.accountUuid().toString(), identity.tenantUuid().toString(), - decimal(pair.membershipVersion()), + Map.of(identity.tenantUuid().toString(), decimal(pair.membershipVersion())), decimal(pair.membershipAuthorityGeneration()), tuple, decimal(authority.issuanceFence().value()), Instant.now(), - streamKey); + streamKey, + checkpoints, + List.of()); } /** @@ -721,7 +748,7 @@ private Checkpoint appendAndReadBack( if (!newMembership && !callerBoundAuthorityInvalidated) { throw new IllegalStateException("Membership reactivation must invalidate caller authority"); } - requireNoUnmodeledCutoff(identity); + readBaselineUpstreamCheckpoints(identity, snapshot); RoleSnapshot roles = requireRoleSnapshot(identity, membership); String streamKey = membershipStreamKey(identity); String expectedEventId = eventIdForRequest(requestId); @@ -956,13 +983,16 @@ private MembershipEvent verifyStoredEvent(Event event, Identity identity, String return verified; } - /** - * Extracts Account's local numeric membership value only after validating the complete canonical - * one-tenant event carrier. The event itself and all equality checks retain the map unchanged. - */ - private String membershipVersionValue(MembershipEvent event, Identity identity) { + /** Retains the verified event's exact immutable one-tenant map in the local snapshot. */ + private Map membershipVersionMap(MembershipEvent event, Identity identity) { String tenantId = identity.tenantUuid().toString(); Map versions = event.membershipVersion(); + membershipVersionValue(versions, tenantId); + return Map.copyOf(versions); + } + + /** Extracts a process-local scalar only after validating the complete map. */ + private String membershipVersionValue(Map versions, String tenantId) { String version = versions.get(tenantId); if (versions.size() != 1 || !versions.containsKey(tenantId) @@ -974,15 +1004,87 @@ private String membershipVersionValue(MembershipEvent event, Identity identity) return version; } - private void requireNoUnmodeledCutoff(Identity identity) { - Optional accountCutoff = - authorityOutboxRepository.readCheckpoint(accountStreamKey(identity.accountUuid())); - Optional tenantCutoff = - authorityOutboxRepository.readCheckpoint(tenantStreamKey(identity.tenantUuid())); - if (accountCutoff.isPresent() || tenantCutoff.isPresent()) { + private static int compareUnsignedUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int comparison = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private List readBaselineUpstreamCheckpoints( + Identity identity, CompositeSnapshot snapshot) { + ScopeState tenant = only(snapshot.tenants(), "tenant"); + if (!AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER) + .equals(snapshot.issuer().scope()) + || !AuthorityScope.account(identity.accountUuid()).equals(snapshot.account().scope()) + || !AuthorityScope.tenant(identity.tenantUuid()).equals(tenant.scope()) + || !AuthorityScope.membership(identity.accountUuid(), identity.tenantUuid()) + .equals(only(snapshot.memberships(), "membership").scope())) { + throw new IllegalStateException( + "Account authority snapshot does not cover the exact issuer/account/tenant scopes"); + } + + return orderedCheckpoints( + List.of( + requireSequenceZeroCheckpoint( + accountStreamKey(identity.accountUuid()), snapshot.account(), "account"), + requireSequenceZeroCheckpoint(issuerStreamKey(), snapshot.issuer(), "issuer"), + requireSequenceZeroCheckpoint( + tenantStreamKey(identity.tenantUuid()), tenant, "tenant"))); + } + + private OutboxCheckpointEntry requireSequenceZeroCheckpoint( + String streamKey, ScopeState scope, String scopeLabel) { + // The composite generation read holds the source rows. V31 advances source_version with every + // generation change; V33 keeps committed streams/events immutable and authority writers commit + // them with the applicable source generation. Both pristine generation state and an absent + // V33 head are required before zero is reported. + if (scope.generation() != 1L || scope.sourceVersion() != 1L) { + throw new IllegalStateException( + "Account " + + scopeLabel + + " authority generation cannot prove its sequence-zero baseline"); + } + if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { + throw new IllegalStateException( + "Account " + scopeLabel + " authority stream has committed history"); + } + return new OutboxCheckpointEntry(streamKey, "0"); + } + + private List orderedCheckpoints(List checkpoints) { + if (checkpoints == null || checkpoints.isEmpty()) { + throw new IllegalArgumentException("Account authority checkpoints are required"); + } + ArrayList ordered = new ArrayList<>(checkpoints); + ordered.sort(OUTBOX_CHECKPOINT_ORDER); + for (int index = 1; index < ordered.size(); index++) { + if (ordered.get(index - 1).outboxStreamKey().equals(ordered.get(index).outboxStreamKey())) { + throw new IllegalArgumentException( + "Account authority checkpoint stream keys must be unique"); + } + } + return List.copyOf(ordered); + } + + private OutboxSourceEvidence sourceEvidence(Checkpoint checkpoint, Event event) { + if (!checkpointMatches(checkpoint, event)) { throw new IllegalStateException( - "Account JOIN cannot form optional security or billing cutoff evidence from retained events"); + "Account authority source event differs from its exact outbox checkpoint"); } + return new OutboxSourceEvidence( + checkpoint.outboxStreamKey(), + Long.toString(checkpoint.outboxSequence()), + event.eventId(), + event.eventDigest()); } private RoleSnapshot requireRoleSnapshot(Identity identity, AccountTenantMembership membership) { @@ -1102,6 +1204,10 @@ private String membershipStreamKey(Identity identity) { + identity.tenantUuid(); } + private String issuerStreamKey() { + return canonicalIssuerStreamKey(); + } + private String accountStreamKey(UUID accountUuid) { return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountUuid; } @@ -1149,22 +1255,61 @@ public record NewMembershipBaseline(long membershipVersion, long membershipAutho } /** - * Local V36 absence evidence. Its scalar version is not the canonical durable/wire carrier, and - * it carries no event identity/digest or gameplay admission. + * One immutable Account authority checkpoint; event identity remains separate source evidence. */ + public record OutboxCheckpointEntry(String outboxStreamKey, String outboxSequence) { + public OutboxCheckpointEntry { + Objects.requireNonNull(outboxStreamKey, "authority outbox stream key is required"); + Objects.requireNonNull(outboxSequence, "authority outbox sequence is required"); + if (!outboxStreamKey.startsWith(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX) + || !isNonnegativeCanonicalDecimal(outboxSequence)) { + throw new IllegalArgumentException("Account authority checkpoint is not canonical"); + } + } + } + + /** Positive committed source-event identity kept outside the two-field checkpoint carrier. */ + public record OutboxSourceEvidence( + String outboxStreamKey, String outboxSequence, String eventId, String eventDigest) { + public OutboxSourceEvidence { + Objects.requireNonNull(outboxStreamKey, "authority outbox stream key is required"); + Objects.requireNonNull(outboxSequence, "authority outbox sequence is required"); + if (eventId == null || eventId.isBlank()) { + throw new IllegalArgumentException("source event ID is required"); + } + Objects.requireNonNull(eventDigest, "source event digest is required"); + if (!outboxStreamKey.startsWith(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX) + || !isPositiveCanonicalDecimal(outboxSequence) + || !eventDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "Account authority source event evidence is not canonical"); + } + } + } + + /** + * Local V36 absence evidence with an exact one-tenant membership-version map. The sequence-zero + * checkpoints carry no source event identity or digest and never authorize gameplay. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The constructor stores immutable Map.copyOf and List.copyOf values.") public record NeverJoinedMembershipSnapshot( String accountId, String tenantId, - String membershipVersion, + Map membershipVersion, String membershipAuthorityGeneration, AuthorityTuple authorityTuple, String issuanceFence, Instant evaluatedAt, - String outboxStreamKey) { + String outboxStreamKey, + List outboxCheckpoints, + List outboxSourceEvidence) { public NeverJoinedMembershipSnapshot { accountId = requireCanonicalUuid(accountId, "canonical Account UUID"); tenantId = requireCanonicalUuid(tenantId, "canonical tenant UUID"); - membershipVersion = requirePositiveCanonicalDecimal(membershipVersion, "membership version"); + membershipVersion = + requireExactPositiveVersionMap(membershipVersion, tenantId, "membership version"); membershipAuthorityGeneration = requirePositiveCanonicalDecimal( membershipAuthorityGeneration, "membership authority generation"); @@ -1173,16 +1318,19 @@ public record NeverJoinedMembershipSnapshot( Objects.requireNonNull(evaluatedAt, "Account evaluation time is required"); outboxStreamKey = Objects.requireNonNull(outboxStreamKey, "membership stream key is required"); + outboxCheckpoints = requireOrderedCheckpointSet(outboxCheckpoints); + outboxSourceEvidence = List.copyOf(outboxSourceEvidence); - if (!isPositiveCanonicalDecimal(authorityTuple.issuerAuthGeneration()) - || !isPositiveCanonicalDecimal(authorityTuple.accountAuthorityGeneration()) + if (!"1".equals(authorityTuple.issuerAuthGeneration()) + || !"1".equals(authorityTuple.accountAuthorityGeneration()) || authorityTuple.tenantAuthorityGeneration().size() != 1 || authorityTuple.membershipAuthorityGeneration().size() != 1 || !authorityTuple.tenantAuthorityGeneration().containsKey(tenantId) || !authorityTuple.membershipAuthorityGeneration().containsKey(tenantId) - || !isPositiveCanonicalDecimal(authorityTuple.tenantAuthorityGeneration().get(tenantId)) + || !"1".equals(authorityTuple.tenantAuthorityGeneration().get(tenantId)) || !membershipAuthorityGeneration.equals( authorityTuple.membershipAuthorityGeneration().get(tenantId)) + || !"1".equals(membershipVersion.get(tenantId)) || !authorityTuple.privateRealmGrantVersions().isEmpty() || authorityTuple.accountSecurityCutoff().isPresent() || authorityTuple.tenantBillingCutoff().isPresent()) { @@ -1200,10 +1348,17 @@ public record NeverJoinedMembershipSnapshot( throw new IllegalArgumentException( "Never-joined Account membership stream key is not canonical"); } - } - - public long outboxSequence() { - return 0L; + List expectedCheckpoints = + requireOrderedCheckpointSet( + List.of( + new OutboxCheckpointEntry(accountStreamKey(accountId), "0"), + new OutboxCheckpointEntry(canonicalIssuerStreamKey(), "0"), + new OutboxCheckpointEntry(outboxStreamKey, "0"), + new OutboxCheckpointEntry(tenantStreamKey(tenantId), "0"))); + if (!expectedCheckpoints.equals(outboxCheckpoints) || !outboxSourceEvidence.isEmpty()) { + throw new IllegalArgumentException( + "Never-joined Account snapshot must contain only four sequence-zero checkpoints"); + } } public boolean membershipExists() { @@ -1221,86 +1376,93 @@ public List roles() { public boolean gameplayAdmissionAllowed() { return false; } - - private static String requireCanonicalUuid(String value, String field) { - Objects.requireNonNull(value, field + " is required"); - try { - if (!UUID.fromString(value).toString().equals(value)) { - throw new IllegalArgumentException(field + " must be a canonical lowercase UUID"); - } - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException( - field + " must be a canonical lowercase UUID", exception); - } - return value; - } - - private static String requirePositiveCanonicalDecimal(String value, String field) { - Objects.requireNonNull(value, field + " is required"); - if (!isPositiveCanonicalDecimal(value)) { - throw new IllegalArgumentException( - field + " must be a positive canonical unsigned decimal string"); - } - return value; - } - - private static boolean isPositiveCanonicalDecimal(String value) { - return value != null && value.matches("[1-9][0-9]*"); - } } /** Immutable positive membership evidence assembled from one fenced Account transaction. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The constructor stores immutable Map.copyOf and List.copyOf values.") public record PositiveMembershipSnapshot( boolean membershipExists, String accountId, String tenantId, String membershipLifecycleState, boolean gameplayAdmissionAllowed, - String membershipVersion, + Map membershipVersion, String membershipAuthorityGeneration, List roles, AuthorityTuple authorityTuple, String issuanceFence, Instant evaluatedAt, - List outboxCheckpoints, + List outboxCheckpoints, + List outboxSourceEvidence, MembershipTransitionReceipt transitionReceipt, MembershipEvent authorityEvent) { public PositiveMembershipSnapshot { - Objects.requireNonNull(accountId, "canonical Account UUID is required"); - Objects.requireNonNull(tenantId, "canonical tenant UUID is required"); + accountId = requireCanonicalUuid(accountId, "canonical Account UUID"); + tenantId = requireCanonicalUuid(tenantId, "canonical tenant UUID"); Objects.requireNonNull(membershipLifecycleState, "membership lifecycle is required"); - Objects.requireNonNull(membershipVersion, "membership version is required"); + membershipVersion = + requireExactPositiveVersionMap(membershipVersion, tenantId, "membership version"); Objects.requireNonNull( membershipAuthorityGeneration, "membership authority generation is required"); + membershipAuthorityGeneration = + requirePositiveCanonicalDecimal( + membershipAuthorityGeneration, "membership authority generation"); roles = List.copyOf(roles); Objects.requireNonNull(authorityTuple, "complete authority tuple is required"); - Objects.requireNonNull(issuanceFence, "Account issuance fence is required"); + issuanceFence = requirePositiveCanonicalDecimal(issuanceFence, "Account issuance fence"); Objects.requireNonNull(evaluatedAt, "Account evaluation time is required"); - outboxCheckpoints = List.copyOf(outboxCheckpoints); + outboxCheckpoints = requireOrderedCheckpointSet(outboxCheckpoints); + outboxSourceEvidence = List.copyOf(outboxSourceEvidence); Objects.requireNonNull(transitionReceipt, "membership transition receipt is required"); Objects.requireNonNull(authorityEvent, "canonical membership authority event is required"); + String membershipStreamKey = membershipStreamKey(accountId, tenantId); + String membershipSequence = authorityEvent.outboxSequence(); + if (!isPositiveCanonicalDecimal(membershipSequence)) { + throw new IllegalArgumentException( + "Positive Account membership event sequence must be canonical and positive"); + } + List expectedCheckpoints = + requireOrderedCheckpointSet( + List.of( + new OutboxCheckpointEntry(accountStreamKey(accountId), "0"), + new OutboxCheckpointEntry(canonicalIssuerStreamKey(), "0"), + new OutboxCheckpointEntry(membershipStreamKey, membershipSequence), + new OutboxCheckpointEntry(tenantStreamKey(tenantId), "0"))); + List expectedSourceEvidence = + List.of( + new OutboxSourceEvidence( + membershipStreamKey, + membershipSequence, + authorityEvent.eventId(), + authorityEvent.eventDigest())); + if (!membershipExists || !"ACTIVE".equals(membershipLifecycleState) || !gameplayAdmissionAllowed || !accountId.equals(authorityEvent.accountId()) || !tenantId.equals(authorityEvent.tenantId()) + || !membershipStreamKey.equals(authorityEvent.outboxStreamKey()) || !membershipLifecycleState.equals(authorityEvent.membershipLifecycleState()) - || !membershipVersion.matches("[1-9][0-9]*") - || !Map.of(tenantId, membershipVersion).equals(authorityEvent.membershipVersion()) + || !membershipVersion.equals(authorityEvent.membershipVersion()) || !membershipAuthorityGeneration.equals(authorityEvent.membershipAuthorityGeneration()) || !roles.equals(authorityEvent.roles()) || !authorityTuple.equals(authorityEvent.authorityTuple()) || !issuanceFence.equals(authorityEvent.issuanceFence()) + || !"1".equals(authorityTuple.issuerAuthGeneration()) + || !"1".equals(authorityTuple.accountAuthorityGeneration()) + || !Map.of(tenantId, "1").equals(authorityTuple.tenantAuthorityGeneration()) + || !Map.of(tenantId, membershipAuthorityGeneration) + .equals(authorityTuple.membershipAuthorityGeneration()) || !membershipAuthorityGeneration.equals( authorityTuple.membershipAuthorityGeneration().get(tenantId)) - || outboxCheckpoints.size() != 1 - || !outboxCheckpoints.contains( - new Checkpoint( - authorityEvent.outboxStreamKey(), - Long.parseLong(authorityEvent.outboxSequence()), - authorityEvent.eventId(), - authorityEvent.eventDigest())) + || !authorityTuple.privateRealmGrantVersions().isEmpty() + || authorityTuple.accountSecurityCutoff().isPresent() + || authorityTuple.tenantBillingCutoff().isPresent() + || !expectedCheckpoints.equals(outboxCheckpoints) + || !expectedSourceEvidence.equals(outboxSourceEvidence) || !transitionReceipt.requestId().equals(authorityEvent.requestId())) { throw new IllegalArgumentException( "Positive Account membership snapshot evidence is internally inconsistent"); @@ -1308,6 +1470,87 @@ public record PositiveMembershipSnapshot( } } + private static String requireCanonicalUuid(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + try { + if (!UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID"); + } + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID", exception); + } + return value; + } + + private static String requirePositiveCanonicalDecimal(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (!isPositiveCanonicalDecimal(value)) { + throw new IllegalArgumentException( + field + " must be a positive canonical unsigned decimal string"); + } + return value; + } + + private static boolean isPositiveCanonicalDecimal(String value) { + return value != null && value.matches("[1-9][0-9]*"); + } + + private static boolean isNonnegativeCanonicalDecimal(String value) { + return value != null && value.matches("0|[1-9][0-9]*"); + } + + private static Map requireExactPositiveVersionMap( + Map value, String tenantId, String field) { + Objects.requireNonNull(value, field + " map is required"); + if (value.size() != 1 + || !value.containsKey(tenantId) + || !isPositiveCanonicalDecimal(value.get(tenantId))) { + throw new IllegalArgumentException(field + " must be a positive canonical one-tenant map"); + } + return Map.copyOf(value); + } + + private static List requireOrderedCheckpointSet( + List checkpoints) { + Objects.requireNonNull(checkpoints, "Account authority checkpoints are required"); + List copy = List.copyOf(checkpoints); + ArrayList ordered = new ArrayList<>(copy); + ordered.sort(OUTBOX_CHECKPOINT_ORDER); + if (!copy.equals(ordered)) { + throw new IllegalArgumentException( + "Account authority checkpoints must use canonical stream-key order"); + } + for (int index = 1; index < copy.size(); index++) { + if (copy.get(index - 1).outboxStreamKey().equals(copy.get(index).outboxStreamKey())) { + throw new IllegalArgumentException( + "Account authority checkpoint stream keys must be unique"); + } + } + return copy; + } + + private static String membershipStreamKey(String accountId, String tenantId) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + } + + private static String canonicalIssuerStreamKey() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "issuer/" + + AccountServiceImpl.ACCOUNT_JWT_ISSUER; + } + + private static String accountStreamKey(String accountId) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountId; + } + + private static String tenantStreamKey(String tenantId) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantId; + } + private record Identity( long accountId, long legacyTenantId, 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 43315d3894..3fd04dd2d1 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 @@ -38,6 +38,8 @@ import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -855,7 +857,9 @@ void positiveMembershipSnapshotReturnsExactCommittedAuthorityEvidence() { assertThat(snapshot.tenantId()).isEqualTo(fixture.tenantUuid().toString()); assertThat(snapshot.membershipLifecycleState()).isEqualTo("ACTIVE"); assertThat(snapshot.gameplayAdmissionAllowed()).isTrue(); - assertThat(snapshot.membershipVersion()).isEqualTo(Long.toString(joined.membershipVersion())); + assertThat(snapshot.membershipVersion()) + .isEqualTo( + Map.of(fixture.tenantUuid().toString(), Long.toString(joined.membershipVersion()))); assertThat(snapshot.authorityEvent().membershipVersion()) .isEqualTo( Map.of(fixture.tenantUuid().toString(), Long.toString(joined.membershipVersion()))); @@ -868,15 +872,17 @@ void positiveMembershipSnapshotReturnsExactCommittedAuthorityEvidence() { assertThat(snapshot.authorityEvent().requestId()).isEqualTo(fixture.requestId()); assertThat(snapshot.transitionReceipt().requestId()).isEqualTo(fixture.requestId()); assertThat(snapshot.transitionReceipt().membershipId()).isEqualTo(joined.membershipId()); - assertThat(snapshot.outboxCheckpoints()).hasSize(1); - assertThat(snapshot.outboxCheckpoints().getFirst().outboxStreamKey()) - .isEqualTo(authorityStreamKey(fixture)); - assertThat(snapshot.outboxCheckpoints().getFirst().outboxSequence()) - .isEqualTo(Long.parseLong(snapshot.authorityEvent().outboxSequence())); - assertThat(snapshot.outboxCheckpoints().getFirst().sourceEventId()) - .isEqualTo(snapshot.authorityEvent().eventId()); - assertThat(snapshot.outboxCheckpoints().getFirst().sourceEventDigest()) - .isEqualTo(snapshot.authorityEvent().eventDigest()); + assertThat(snapshot.outboxCheckpoints()) + .containsExactlyElementsOf( + expectedMembershipOutboxCheckpoints( + fixture, snapshot.authorityEvent().outboxSequence())); + assertThat(snapshot.outboxSourceEvidence()) + .containsExactly( + new OutboxSourceEvidence( + authorityStreamKey(fixture), + snapshot.authorityEvent().outboxSequence(), + snapshot.authorityEvent().eventId(), + snapshot.authorityEvent().eventDigest())); } @Test @@ -977,9 +983,11 @@ void neverJoinedSnapshotRequiresAndRetainsDurablePairBaselineBeforeFirstJoin() { assertThat(absence.gameplayAdmissionAllowed()).isFalse(); assertThat(absence.accountId()).isEqualTo(fixture.accountUuid().toString()); assertThat(absence.tenantId()).isEqualTo(fixture.tenantUuid().toString()); - assertThat(absence.membershipVersion()).isEqualTo("1"); + assertThat(absence.membershipVersion()).isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); assertThat(absence.membershipAuthorityGeneration()).isEqualTo("1"); - assertThat(absence.outboxSequence()).isZero(); + assertThat(absence.outboxCheckpoints()) + .containsExactlyElementsOf(expectedMembershipOutboxCheckpoints(fixture, "0")); + assertThat(absence.outboxSourceEvidence()).isEmpty(); assertThat(absence.outboxStreamKey()).isEqualTo(authorityStreamKey(fixture)); assertThat(absence.authorityTuple().membershipAuthorityGeneration()) .containsEntry(fixture.tenantUuid().toString(), "1"); @@ -1002,9 +1010,12 @@ void neverJoinedSnapshotRequiresAndRetainsDurablePairBaselineBeforeFirstJoin() { assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(baselineRow); var retriedAbsence = readNeverJoinedMembershipSnapshot(fixture); - assertThat(retriedAbsence.membershipVersion()).isEqualTo("1"); + assertThat(retriedAbsence.membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); assertThat(retriedAbsence.membershipAuthorityGeneration()).isEqualTo("1"); - assertThat(retriedAbsence.outboxSequence()).isZero(); + assertThat(retriedAbsence.outboxCheckpoints()) + .containsExactlyElementsOf(expectedMembershipOutboxCheckpoints(fixture, "0")); + assertThat(retriedAbsence.outboxSourceEvidence()).isEmpty(); assertThat(countAuthorityMembershipEvents(fixture)).isZero(); JoinPublicProductionResult joined = join(fixture); @@ -1016,17 +1027,21 @@ void neverJoinedSnapshotRequiresAndRetainsDurablePairBaselineBeforeFirstJoin() { assertThat(joined.membershipAuthorityGeneration()).isEqualTo(1L); assertThat(positive.membershipExists()).isTrue(); assertThat(positive.gameplayAdmissionAllowed()).isTrue(); - assertThat(positive.membershipVersion()).isEqualTo("2"); + assertThat(positive.membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); assertThat(positive.membershipAuthorityGeneration()).isEqualTo("1"); assertThat(positive.authorityEvent().outboxSequence()).isEqualTo("1"); assertThat(positive.authorityEvent().eventId()).isNotBlank(); assertThat(positive.authorityEvent().eventDigest()).matches("sha256:[0-9a-f]{64}"); - assertThat(positive.outboxCheckpoints()).hasSize(1); - var checkpoint = positive.outboxCheckpoints().getFirst(); - assertThat(checkpoint.outboxStreamKey()).isEqualTo(authorityStreamKey(fixture)); - assertThat(checkpoint.outboxSequence()).isEqualTo(1L); - assertThat(checkpoint.sourceEventId()).isEqualTo(positive.authorityEvent().eventId()); - assertThat(checkpoint.sourceEventDigest()).isEqualTo(positive.authorityEvent().eventDigest()); + assertThat(positive.outboxCheckpoints()) + .containsExactlyElementsOf(expectedMembershipOutboxCheckpoints(fixture, "1")); + assertThat(positive.outboxSourceEvidence()) + .containsExactly( + new OutboxSourceEvidence( + authorityStreamKey(fixture), + "1", + positive.authorityEvent().eventId(), + positive.authorityEvent().eventDigest())); assertThat(joinedPairRow) .containsEntry("membership_exists", true) .containsEntry("membership_version", 2L) @@ -1082,6 +1097,28 @@ void neverJoinedSnapshotRejectsPairBaselineContradictingV31Authority() { .hasMessageContaining("differs from its positive pair baseline"); } + @Test + void neverJoinedSnapshotRejectsAdvancedUpstreamGenerationWithoutSourceEvent() { + JoinFixture advancedTenant = fixture("active"); + preparePairAuthorityBaseline(advancedTenant); + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 WHERE scope_kind = 'TENANT' " + + "AND tenant_uuid = ?", + advancedTenant.tenantUuid()); + + assertThat( + countAuthorityStreamEvents( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "tenant/" + + advancedTenant.tenantUuid())) + .isZero(); + assertThatThrownBy(() -> readNeverJoinedMembershipSnapshot(advancedTenant)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "tenant authority generation cannot prove its sequence-zero baseline"); + } + private AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot readPositiveMembershipSnapshot(JoinFixture fixture) { return new TransactionTemplate(transactionManager) @@ -1732,6 +1769,25 @@ private String authorityStreamKey(JoinFixture fixture) { + fixture.tenantUuid(); } + private List expectedMembershipOutboxCheckpoints( + JoinFixture fixture, String membershipSequence) { + return List.of( + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + fixture.accountUuid(), + "0"), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "issuer/" + + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + "0"), + new OutboxCheckpointEntry(authorityStreamKey(fixture), membershipSequence), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + fixture.tenantUuid(), + "0")); + } + private long countAuthorityMembershipEvents(JoinFixture fixture) { return Objects.requireNonNull( dsl.resultQuery( @@ -1741,6 +1797,15 @@ private long countAuthorityMembershipEvents(JoinFixture fixture) { .fetchOne(0, Long.class)); } + private long countAuthorityStreamEvents(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)); + } + private long countAuthorityMembershipStreams(JoinFixture fixture) { return Objects.requireNonNull( dsl.resultQuery( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java index 6bb6d3c608..7ca7f0a6d8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java @@ -7,6 +7,9 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; @@ -25,15 +28,35 @@ class NeverJoinedMembershipSnapshotTest { @Test void constructsEventFreeNonAdmittingSnapshotWithCompleteTuple() { - var snapshot = snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", completeTuple(), "9", STREAM_KEY); + var snapshot = snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", completeTuple(), "1", STREAM_KEY); assertThat(snapshot.membershipExists()).isFalse(); assertThat(snapshot.membershipLifecycleState()).isEqualTo("MISSING"); assertThat(snapshot.roles()).isEmpty(); assertThat(snapshot.gameplayAdmissionAllowed()).isFalse(); - assertThat(snapshot.outboxSequence()).isZero(); + assertThat(snapshot.membershipVersion()).containsOnly(Map.entry(TENANT_ID, "1")); + assertThat(snapshot.outboxCheckpoints()) + .containsExactly( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + ACCOUNT_ID, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, "0"), + new OutboxCheckpointEntry(STREAM_KEY, "0"), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + TENANT_ID, "0")); + assertThat(snapshot.outboxSourceEvidence()).isEmpty(); assertThat(snapshot.authorityTuple().membershipAuthorityGeneration()) .containsEntry(TENANT_ID, "1"); + assertThatThrownBy(() -> snapshot.membershipVersion().put(TENANT_ID, "2")) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void retainsAnAdvancedAccountIssuanceFenceWithoutInventingUpstreamEvents() { + var snapshot = snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", completeTuple(), "7", STREAM_KEY); + + assertThat(snapshot.issuanceFence()).isEqualTo("7"); + assertThat(snapshot.outboxCheckpoints()) + .allMatch(checkpoint -> checkpoint.outboxSequence().equals("0")); + assertThat(snapshot.outboxSourceEvidence()).isEmpty(); } @Test @@ -46,14 +69,14 @@ void rejectsNonCanonicalIdsAndNonPositiveCounters() { "1", "1", completeTuple(), - "9", + "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( - () -> snapshot(ACCOUNT_ID, TENANT_ID, "0", "1", completeTuple(), "9", STREAM_KEY)) + () -> snapshot(ACCOUNT_ID, TENANT_ID, "0", "1", completeTuple(), "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( - () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "0", completeTuple(), "9", STREAM_KEY)) + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "0", completeTuple(), "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", completeTuple(), "0", STREAM_KEY)) @@ -82,12 +105,12 @@ void rejectsTupleWithWrongTenantOrMembershipGeneration() { Optional.empty()); assertThatThrownBy( - () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", wrongTenant, "9", STREAM_KEY)) + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", wrongTenant, "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> snapshot( - ACCOUNT_ID, TENANT_ID, "1", "1", wrongMembershipGeneration, "9", STREAM_KEY)) + ACCOUNT_ID, TENANT_ID, "1", "1", wrongMembershipGeneration, "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); } @@ -139,17 +162,17 @@ void rejectsInvalidTupleCountersAndSequenceZeroAuthorityData() { Optional.of(new AccountSecurityCutoff("6", "account-stream", "1")), Optional.empty()); - assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", zeroIssuer, "9", STREAM_KEY)) + assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", zeroIssuer, "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( - () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", nonCanonicalAccount, "9", STREAM_KEY)) + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", nonCanonicalAccount, "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", zeroTenant, "9", STREAM_KEY)) + assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", zeroTenant, "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", extraGrant, "9", STREAM_KEY)) + assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", extraGrant, "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( - () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", presentCutoff, "9", STREAM_KEY)) + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", presentCutoff, "1", STREAM_KEY)) .isInstanceOf(IllegalArgumentException.class); } @@ -163,11 +186,72 @@ void rejectsNonCanonicalMembershipStreamKey() { "1", "1", completeTuple(), - "9", + "1", STREAM_KEY + "/unexpected")) .isInstanceOf(IllegalArgumentException.class); } + @Test + void rejectsUpstreamGenerationThatCannotProveSequenceZero() { + AuthorityTuple changedIssuerGeneration = + new AuthorityTuple( + "2", + "1", + Map.of(TENANT_ID, "1"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + + assertThatThrownBy( + () -> + snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", changedIssuerGeneration, "1", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsSequenceZeroSnapshotWithMissingCheckpointOrSourceEvent() { + var valid = snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", completeTuple(), "1", STREAM_KEY); + var withoutTenantCheckpoint = + valid.outboxCheckpoints().subList(0, valid.outboxCheckpoints().size() - 1); + var positiveSourceEvidence = + List.of( + new OutboxSourceEvidence( + STREAM_KEY, + "1", + "04ef66b4-c0ad-3d5b-b3b2-0e8510e72002", + "sha256:" + "a".repeat(64))); + + assertThatThrownBy( + () -> + new AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot( + valid.accountId(), + valid.tenantId(), + valid.membershipVersion(), + valid.membershipAuthorityGeneration(), + valid.authorityTuple(), + valid.issuanceFence(), + valid.evaluatedAt(), + valid.outboxStreamKey(), + withoutTenantCheckpoint, + List.of())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot( + valid.accountId(), + valid.tenantId(), + valid.membershipVersion(), + valid.membershipAuthorityGeneration(), + valid.authorityTuple(), + valid.issuanceFence(), + valid.evaluatedAt(), + valid.outboxStreamKey(), + valid.outboxCheckpoints(), + positiveSourceEvidence)) + .isInstanceOf(IllegalArgumentException.class); + } + private static AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot snapshot( String accountId, String tenantId, @@ -179,19 +263,26 @@ private static AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnap return new AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot( accountId, tenantId, - membershipVersion, + Map.of(tenantId, membershipVersion), membershipAuthorityGeneration, authorityTuple, issuanceFence, Instant.parse("2026-09-27T00:00:00Z"), - streamKey); + streamKey, + List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + accountId, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, "0"), + new OutboxCheckpointEntry(streamKey, "0"), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + tenantId, "0")), + List.of()); } private static AuthorityTuple completeTuple() { return new AuthorityTuple( - "4", - "6", - Map.of(TENANT_ID, "8"), + "1", + "1", + Map.of(TENANT_ID, "1"), Map.of(TENANT_ID, "1"), List.of(), Optional.empty(), From 1fac6dd2712519b5a1b86136ef791ea68cc83423 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 13:48:12 +1300 Subject: [PATCH 03/46] Align negative snapshot proof with earliest authority rejection --- .../player-access-and-session.md | 2 +- .../AccountJoinPostgresIntegrationTest.java | 23 +++++++++++++------ 2 files changed, 17 insertions(+), 8 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 4863d687e0..029453f04e 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 unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's exact one-tenant `membershipVersion` map in the producer, strict shared codec, canonical digest vectors, immutable evidence, and Account exact retry/readback comparisons. The Account producer may extract a local numeric value only after validating the map; it does not persist or transmit a scalar event field. Shared codec and Account/Game Session vector tests execute locally; PostgreSQL JOIN/reconciliation tests compile but skip without Docker, and the runtime membership RPC remains denied until its complete same-snapshot producer and consumer proof is ready. The unactivated Account ring materializer also binds a dedicated service-account username in the protected source record and checks the server-reported identity before Secret access, but sole-writer RBAC, protected custody, authenticated receipt, deployment readback, and live readiness remain unproved, so no Account ring mount is published. -The staged Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. This is a local producer boundary, not a wire response or Game Session consumer: the runtime RPC remains denied. The exact local Account check executed 377 unit tests, while all 78 PostgreSQL integration tests were skipped without Docker, including the new advanced-upstream negative case. +Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. This is a local producer boundary, not a wire response or Game Session consumer: the runtime RPC remains denied. The exact local Account check executed 377 unit tests, while all 78 PostgreSQL integration tests were skipped without Docker. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one new negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The test now asserts that exact rejection and absence of an event; this correction still needs a database-backed rerun. 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 durable post-logout episode fencing 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. 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 3fd04dd2d1..6dac9894c7 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 @@ -1082,19 +1082,28 @@ void neverJoinedSnapshotRejectsMissingPairAndAbsentMembershipWithRetainedHistory } @Test - void neverJoinedSnapshotRejectsPairBaselineContradictingV31Authority() { - JoinFixture mismatchedBaseline = fixture("active"); - preparePairAuthorityBaseline(mismatchedBaseline); + void neverJoinedSnapshotRejectsAdvancedMembershipGenerationWithoutSourceEvent() { + JoinFixture advancedMembership = fixture("active"); + preparePairAuthorityBaseline(advancedMembership); dsl.execute( "UPDATE account_authority_generations SET generation = generation + 1, " + "source_version = source_version + 1 WHERE scope_kind = 'MEMBERSHIP' " + "AND account_uuid = ? AND tenant_uuid = ?", - mismatchedBaseline.accountUuid(), - mismatchedBaseline.tenantUuid()); + advancedMembership.accountUuid(), + advancedMembership.tenantUuid()); - assertThatThrownBy(() -> readNeverJoinedMembershipSnapshot(mismatchedBaseline)) + assertThat( + countAuthorityStreamEvents( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + advancedMembership.accountUuid() + + "/" + + advancedMembership.tenantUuid())) + .isZero(); + assertThatThrownBy(() -> readNeverJoinedMembershipSnapshot(advancedMembership)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("differs from its positive pair baseline"); + .hasMessageContaining( + "membership authority generation cannot prove its sequence-zero baseline"); } @Test From d04d2187abe36bc50ce8a6bad5fe2525edeb1939 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:10:52 +1300 Subject: [PATCH 04/46] Record exact snapshot database proof and carrier gap --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 029453f04e..643ce1f025 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 unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's exact one-tenant `membershipVersion` map in the producer, strict shared codec, canonical digest vectors, immutable evidence, and Account exact retry/readback comparisons. The Account producer may extract a local numeric value only after validating the map; it does not persist or transmit a scalar event field. Shared codec and Account/Game Session vector tests execute locally; PostgreSQL JOIN/reconciliation tests compile but skip without Docker, and the runtime membership RPC remains denied until its complete same-snapshot producer and consumer proof is ready. The unactivated Account ring materializer also binds a dedicated service-account username in the protected source record and checks the server-reported identity before Secret access, but sole-writer RBAC, protected custody, authenticated receipt, deployment readback, and live readiness remain unproved, so no Account ring mount is published. -Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. This is a local producer boundary, not a wire response or Game Session consumer: the runtime RPC remains denied. The exact local Account check executed 377 unit tests, while all 78 PostgreSQL integration tests were skipped without Docker. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one new negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The test now asserts that exact rejection and absence of an event; this correction still needs a database-backed rerun. +Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. This is a local producer boundary, not a wire response or Game Session consumer: the runtime RPC remains denied. The exact local Account check executed 377 unit tests, while all 78 PostgreSQL integration tests were skipped without Docker. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one new negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both aggregate gates remain red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's unique snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; the ADR correction is in #2876, while that runtime carrier and consumer remain open. 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 durable post-logout episode fencing 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. From ce9a9fea79f879025bc9fc4a8fd347d9927b7a4d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:44:34 +1300 Subject: [PATCH 05/46] feat(account): stage atomic bare-login exchange storage --- .../account-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 4 +- .../AccountBareLoginExchangeIdentity.java | 72 ++ .../AccountBareLoginExchangeOperation.java | 208 +++++ .../AccountBareLoginExchangeRepository.java | 827 ++++++++++++++++++ .../AccountBareLoginResponseEnvelope.java | 23 + ...7__account_bare_login_exchange_storage.sql | 328 +++++++ ...oginExchangeRepositoryIntegrationTest.java | 756 ++++++++++++++++ 9 files changed, 2223 insertions(+), 2 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginResponseEnvelope.java create mode 100644 services/account-service/src/main/resources/db/migration/V37__account_bare_login_exchange_storage.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 4c8e646aa7..9866a13c31 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -150,7 +150,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current Account REST runtime requires existing caller-bound membership for character discovery and connect-token issuance and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. The separate Game Session text `PLAY` path is currently blocked earlier by Account runtime membership/grant/entitlement gRPC methods returning `FAILED_PRECONDITION` before reads, producing `AUTH_UNAVAILABLE`; its downstream membership outcomes require successful mocked Account responses. For a publicly visible public-production target whose joining policy permits entry, the Account connect-token issuance branch may return `JOIN_REQUIRED` without creating or restoring membership; the latter existing-membership case is not lifecycle-aware while explicit `JOIN` is a separate local action. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. -- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish that proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. +- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The V37 storage candidate binds an exchange to a committed V35 connect operation and stores an immutable purpose-bound terminal envelope, but neither operation is wired to credential issuance or recovery. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish the complete proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. - It is backed by one `session:auth:token:` record so per-token logout and account-level revocation semantics remain consistent. - `POST /auth/logout` and `POST /auth/logout-all` must accept this profile so first-party gameplay UIs can explicitly revoke bootstrap capability on sign-out rather than waiting for expiry. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 7bf56695ba..c906b0b844 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -127,3 +127,8 @@ Entry format: - Context: the Account response-envelope Secret materializer emitted canonical UTC timestamps with trailing fractional zeroes removed. A broad developer-tool run intermittently failed its CLI readback although focused tests using whole-second timestamps passed. - Observation: this runner's Python `datetime.fromisoformat` rejected a valid five-digit fractional-second timestamp such as `.00101Z` after offset normalization. A timestamp round-trip sweep reproduced the defect, and the parser was changed to accept the contract's one-to-six fractional digits explicitly; the full 112-test developer-tool suite then passed. - Expected pattern: test exact writer-to-reader timestamp round trips across fractional precisions, including live-clock output, before treating a source-generation/freshness readback as reliable. + +- `2026-09-27`: Hosted database task success may lack per-case proof artifacts + - Context: Unit 1B Account integration tests skipped locally without Docker. Hosted runs executed the integration task and passed on corrected code, but the uploaded artifact contained JaCoCo output without JUnit XML for the named PostgreSQL case. + - Observation: task-level execution and success are useful composed evidence, but they do not independently identify which newly corrected database methods ran or whether any were skipped. + - Expected pattern: retain and upload the exact integration JUnit XML alongside coverage artifacts when individual database regressions are needed as proof; until then report task-level success separately from per-case execution. 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 643ce1f025..bea60a0025 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,8 @@ The unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. This is a local producer boundary, not a wire response or Game Session consumer: the runtime RPC remains denied. The exact local Account check executed 377 unit tests, while all 78 PostgreSQL integration tests were skipped without Docker. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one new negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both aggregate gates remain red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's unique snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; the ADR correction is in #2876, while that runtime carrier and consumer remain open. +V37's deferred database guard rejects an exchange transaction that would commit `PENDING` without its terminal envelope: a pre-commit crash rolls back the claim, while a post-commit exact retry reads the original operation and envelope. This is still storage-only until PostgreSQL executes the new cases and the caller proves that source validation, current authority, credential creation, and envelope completion use that same transaction. Deletion is denied until Account adds a proven receipt/envelope retention and safe-cleanup path; no fixed TTL, timeout, or absent row is interpreted as a terminal result. Lost-response producer/consumer proof remains an activation gate. + 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 durable post-logout episode fencing 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. @@ -28,7 +30,7 @@ The in-progress #2873 tenant bridge now has a signed Game Design migration-manif The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. -The approved first-party bare-`LOGIN` private-delegation exchange is not implemented. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance, key-ring deployment, or exact-result recovery. An Account-owned one-use/idempotent exchange must establish those producer facts and exact Game Session caller binding before Game Session can receive a private delegation JWT; a forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. +The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases compile but skipped without Docker; database execution, caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. The #2876 candidate also adds a local AES-256-GCM response-envelope primitive backed by one Account-only versioned mounted-file ring, with separate connect-token and bare-`LOGIN` purpose keys, key IDs, current-write/older-decrypt rotation, and length-framed exact-operation evidence. Local unit tests execute both-purpose round trips, old-key recovery/removal, wrong-purpose and wrong-operation rejection, and missing/malformed-ring denial. V35 adds an unwired connect-token issuance operation/envelope table with exact identity, digest, pending/terminal state and encrypted-envelope readback; its six PostgreSQL cases reached execution in a prior hosted run, four passed and two failed on a timestamp bind. The corrected-head Account integration task passed, but its success artifact lacks per-test XML. An operator bootstrap candidate creates a protected initial source record once in an owner-only directory and provides an explicit separate rotation action that retains every old purpose key, adds new distinct write keys, and binds a new generation to the previous one without overwriting either source. A separate materializer candidate consumes exact manifest bytes, environment, namespace, generation/predecessor, immutable source-created freshness anchor, and expiry; it verifies retry-stable Secret readback and preserves old decrypt-only keys. The 28 focused materializer tests and combined 139-test developer-tool suite, Ruff, and syntax checks pass locally. Exact-head CI run `36254410583` passed Account Build/Test; its integration task ran and its coverage artifact lists 20 integration classes, but the absent per-case XML prevents an exact executed/skipped count. The aggregate CI gate is red from unchanged Game Session Friends assertions, hosted smoke-tool lint, and an EA-3.1 proof-link check outside #2876's unique diff. Actual protected durable custody, source backup and writer RBAC, deployment/readiness wiring, a live mounted Secret, executed rotation, and proven safe decrypt-only key retirement are still absent. There is no corresponding bare-`LOGIN` operation, wired producer/consumer, or lost-response/live rollout proof. Neither credential path is enabled by the primitive, tool candidates, or V35, and an unavailable key may never authorize reminting. The separately specified credential-bearing `Authenticate` exact-retry envelope is also unimplemented; this two-purpose primitive does not supply its key or enable that operation. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java new file mode 100644 index 0000000000..ff09941d56 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; + +/** Exact identity for one Account-owned bare first-party LOGIN exchange attempt. */ +public record AccountBareLoginExchangeIdentity( + UUID sourceConnectOperationId, + long accountId, + long tenantId, + String connectScopeId, + String requestId) { + + public static final int MAX_CONNECT_SCOPE_ID_UTF8_BYTES = 2048; + public static final int MAX_REQUEST_ID_LENGTH = 128; + + public AccountBareLoginExchangeIdentity { + Objects.requireNonNull(sourceConnectOperationId, "sourceConnectOperationId"); + if (accountId <= 0 || tenantId <= 0) { + throw new IllegalArgumentException("Bare LOGIN account and tenant IDs must be positive"); + } + connectScopeId = requireText(connectScopeId, "connectScopeId"); + requestId = requireText(requestId, "requestId"); + if (connectScopeId.getBytes(StandardCharsets.UTF_8).length > MAX_CONNECT_SCOPE_ID_UTF8_BYTES) { + throw new IllegalArgumentException("Bare LOGIN scope ID exceeds its storage bound"); + } + if (requestId.length() > MAX_REQUEST_ID_LENGTH) { + throw new IllegalArgumentException("Bare LOGIN request ID exceeds its storage bound"); + } + } + + String connectScopeHash() { + return net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId); + } + + @Override + public String toString() { + return "AccountBareLoginExchangeIdentity{sourceConnectOperationId=" + + sourceConnectOperationId + + ", accountId=" + + accountId + + ", tenantId=" + + tenantId + + ", connectScopeId=, requestId='" + + requestId + + "'}"; + } + + private static String requireText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.isBlank() || value.indexOf('\0') >= 0 || hasUnpairedSurrogate(value)) { + throw new IllegalArgumentException("Invalid " + fieldName); + } + return value; + } + + private static boolean hasUnpairedSurrogate(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java new file mode 100644 index 0000000000..4aec299355 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Readback-only view of one durable bare first-party LOGIN exchange operation. */ +public record AccountBareLoginExchangeOperation( + UUID operationId, + UUID sourceConnectOperationId, + long accountId, + long tenantId, + String connectScopeHash, + String requestId, + int requestDigestVersion, + byte[] requestDigest, + Lifecycle lifecycle, + String outcomeCode, + String tokenIdentity, + byte[] tokenHash, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest, + Instant createdAt, + Instant updatedAt) { + + private static final Pattern SCOPE_HASH_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final int DIGEST_LENGTH_BYTES = 32; + private static final int MAX_TOKEN_IDENTITY_LENGTH = 128; + + public enum Lifecycle { + PENDING, + COMMITTED; + + static Lifecycle fromDatabase(String value) { + try { + return Lifecycle.valueOf(value); + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored bare LOGIN exchange lifecycle is invalid"); + } + } + } + + public AccountBareLoginExchangeOperation { + if (operationId == null + || sourceConnectOperationId == null + || accountId <= 0 + || tenantId <= 0 + || connectScopeHash == null + || !SCOPE_HASH_PATTERN.matcher(connectScopeHash).matches() + || requestId == null + || requestId.isBlank() + || requestId.length() > AccountBareLoginExchangeIdentity.MAX_REQUEST_ID_LENGTH + || requestDigestVersion != 1 + || lifecycle == null + || createdAt == null + || updatedAt == null) { + throw new IllegalArgumentException("Stored bare LOGIN exchange operation is malformed"); + } + requestDigest = copyDigest(requestDigest, "request digest", false); + tokenHash = copyDigest(tokenHash, "token hash", true); + contextEvidenceDigest = copyDigest(contextEvidenceDigest, "context digest", true); + authorityTupleDigest = copyDigest(authorityTupleDigest, "authority tuple digest", true); + issuanceFenceDigest = copyDigest(issuanceFenceDigest, "issuance-fence digest", true); + postconditionDigest = copyDigest(postconditionDigest, "postcondition digest", true); + if ((tokenIdentity == null) != (tokenHash == null)) { + throw new IllegalArgumentException("Bare LOGIN token identity and hash evidence must pair"); + } + if (tokenIdentity != null + && (tokenIdentity.isBlank() + || tokenIdentity.length() > MAX_TOKEN_IDENTITY_LENGTH + || tokenIdentity.indexOf('\0') >= 0)) { + throw new IllegalArgumentException("Stored bare LOGIN token identity is malformed"); + } + if (lifecycle == Lifecycle.PENDING) { + if (outcomeCode != null) { + throw new IllegalArgumentException("Pending bare LOGIN exchange cannot have an outcome"); + } + } else if (!"SUCCESS".equals(outcomeCode) + || tokenIdentity == null + || contextEvidenceDigest == null + || authorityTupleDigest == null + || issuanceFenceDigest == null + || postconditionDigest == null) { + throw new IllegalArgumentException("Committed bare LOGIN exchange evidence is incomplete"); + } + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] tokenHash() { + return copyNullable(tokenHash); + } + + @Override + public byte[] contextEvidenceDigest() { + return copyNullable(contextEvidenceDigest); + } + + @Override + public byte[] authorityTupleDigest() { + return copyNullable(authorityTupleDigest); + } + + @Override + public byte[] issuanceFenceDigest() { + return copyNullable(issuanceFenceDigest); + } + + @Override + public byte[] postconditionDigest() { + return copyNullable(postconditionDigest); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AccountBareLoginExchangeOperation that)) { + return false; + } + return accountId == that.accountId + && tenantId == that.tenantId + && requestDigestVersion == that.requestDigestVersion + && operationId.equals(that.operationId) + && sourceConnectOperationId.equals(that.sourceConnectOperationId) + && connectScopeHash.equals(that.connectScopeHash) + && requestId.equals(that.requestId) + && Arrays.equals(requestDigest, that.requestDigest) + && lifecycle == that.lifecycle + && Objects.equals(outcomeCode, that.outcomeCode) + && Objects.equals(tokenIdentity, that.tokenIdentity) + && Arrays.equals(tokenHash, that.tokenHash) + && Arrays.equals(contextEvidenceDigest, that.contextEvidenceDigest) + && Arrays.equals(authorityTupleDigest, that.authorityTupleDigest) + && Arrays.equals(issuanceFenceDigest, that.issuanceFenceDigest) + && Arrays.equals(postconditionDigest, that.postconditionDigest) + && Objects.equals(createdAt, that.createdAt) + && Objects.equals(updatedAt, that.updatedAt); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + operationId, + sourceConnectOperationId, + accountId, + tenantId, + connectScopeHash, + requestId, + requestDigestVersion, + lifecycle, + outcomeCode, + tokenIdentity, + createdAt, + updatedAt); + result = 31 * result + Arrays.hashCode(requestDigest); + result = 31 * result + Arrays.hashCode(tokenHash); + result = 31 * result + Arrays.hashCode(contextEvidenceDigest); + result = 31 * result + Arrays.hashCode(authorityTupleDigest); + result = 31 * result + Arrays.hashCode(issuanceFenceDigest); + result = 31 * result + Arrays.hashCode(postconditionDigest); + return result; + } + + @Override + public String toString() { + return "AccountBareLoginExchangeOperation{operationId=" + + operationId + + ", sourceConnectOperationId=" + + sourceConnectOperationId + + ", accountId=" + + accountId + + ", tenantId=" + + tenantId + + ", requestId='" + + requestId + + "', lifecycle=" + + lifecycle + + ", secretEvidence=}"; + } + + private static byte[] copyDigest(byte[] value, String fieldName, boolean nullable) { + if (value == null) { + if (nullable) { + return null; + } + throw new IllegalArgumentException(fieldName + " is required"); + } + if (value.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return Arrays.copyOf(value, value.length); + } + + private static byte[] copyNullable(byte[] value) { + return value == null ? null : value.clone(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java new file mode 100644 index 0000000000..522c0c23bb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java @@ -0,0 +1,827 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeOperation.Lifecycle; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Account-owned first-writer storage and exact readback for bare first-party LOGIN exchange. Claim, + * pending evidence, terminal success, and its exact envelope must share one Account transaction; + * V37 permits {@code PENDING} only as an in-transaction intermediate and rejects a still-pending + * exchange at transaction commit. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountBareLoginExchangeRepository { + private static final String OPERATION_TABLE = "account_bare_login_exchange_operations"; + private static final String SOURCE_OPERATION_TABLE = "account_connect_token_issuance_operations"; + private static final String ENVELOPE_TABLE = "account_bare_login_response_envelopes"; + private static final int REQUEST_DIGEST_VERSION = 1; + private static final int DIGEST_LENGTH_BYTES = 32; + private static final int MAX_TOKEN_IDENTITY_LENGTH = 128; + + private final DSLContext dsl; + + public AccountBareLoginExchangeRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * Claims one source connect-operation identity without replacing a prior writer's request + * identity or digest. A source connect operation must already be a committed V35 issuance; a + * pending or absent source is not Account authentication and cannot start an exchange. The caller + * must keep this claim in the same Account transaction as pending evidence and terminal envelope + * completion; committing the claim alone is rejected. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ClaimResult claim(AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + requireCommittedSource(identity); + + Optional existing = readOperationBySource(identity); + if (existing.isEmpty()) { + existing = readOperationByRequest(identity); + } + if (existing.isPresent()) { + AccountBareLoginExchangeOperation operation = existing.orElseThrow(); + assertIdentityMatches(operation, identity); + requireDigestMatch(operation, digest); + return new ClaimResult(ClaimDisposition.REPLAYED, identity, operation); + } + + UUID proposedOperationId = UUID.randomUUID(); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, source_connect_operation_id, account_id, tenant_id, " + + "connect_scope_hash, request_id, request_digest_version, request_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'PENDING') " + + "ON CONFLICT DO NOTHING", + proposedOperationId, + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Bare LOGIN exchange claim result was ambiguous"); + } + + Optional winner = readOperationBySource(identity); + if (winner.isEmpty()) { + winner = readOperationByRequest(identity); + } + AccountBareLoginExchangeOperation operation = + winner.orElseThrow( + () -> + new IllegalStateException( + "Bare LOGIN exchange claim has no exact durable readback")); + assertIdentityMatches(operation, identity); + requireDigestMatch(operation, digest); + if (inserted == 1 && !proposedOperationId.equals(operation.operationId())) { + throw new IllegalStateException("Bare LOGIN exchange claim returned another operation"); + } + return new ClaimResult( + inserted == 1 ? ClaimDisposition.CLAIMED : ClaimDisposition.REPLAYED, identity, operation); + } + + /** Reads one exact source/request identity and rejects a changed request digest. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional find( + AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + requireCommittedSource(identity); + Optional operation = readOperationBySource(identity); + if (operation.isEmpty()) { + operation = readOperationByRequest(identity); + } + if (operation.isPresent()) { + assertIdentityMatches(operation.orElseThrow(), identity); + requireDigestMatch(operation.orElseThrow(), digest); + } + return operation; + } + + /** + * Adds write-once source/token/authority evidence to a still-pending exchange. It never marks a + * transient or ambiguous result terminal; the claim, this evidence binding, and the later + * terminal call must share one transaction, which must store the exact purpose-bound envelope + * before commit. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountBareLoginExchangeOperation recordPendingEvidence( + ClaimResult claim, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest) { + AccountBareLoginExchangeIdentity identity = requireClaimIdentity(claim); + byte[] digest = requireDigest(requestDigest, "request digest"); + byte[] checkedTokenHash = optionalDigest(tokenHash, "token hash"); + byte[] checkedContextDigest = optionalDigest(contextEvidenceDigest, "context digest"); + byte[] checkedAuthorityDigest = optionalDigest(authorityTupleDigest, "authority tuple digest"); + byte[] checkedFenceDigest = optionalDigest(issuanceFenceDigest, "issuance-fence digest"); + byte[] checkedPostconditionDigest = optionalDigest(postconditionDigest, "postcondition digest"); + validateTokenEvidence(tokenIdentity, checkedTokenHash); + if (tokenIdentity == null + && checkedContextDigest == null + && checkedAuthorityDigest == null + && checkedFenceDigest == null + && checkedPostconditionDigest == null) { + throw new IllegalArgumentException( + "At least one pending bare LOGIN exchange evidence field is required"); + } + + AccountBareLoginExchangeOperation operation = requireClaimedOperation(claim, digest); + if (operation.lifecycle() != Lifecycle.PENDING) { + throw new IllegalStateException("Only a pending bare LOGIN exchange can add evidence"); + } + requireEvidenceCompatible( + operation, + tokenIdentity, + checkedTokenHash, + checkedContextDigest, + checkedAuthorityDigest, + checkedFenceDigest, + checkedPostconditionDigest); + + Record changed = + dsl.fetchOne( + "UPDATE " + + OPERATION_TABLE + + " SET token_identity = COALESCE(?, token_identity), " + + "token_hash = COALESCE(?, token_hash), " + + "context_evidence_digest = COALESCE(?, context_evidence_digest), " + + "authority_tuple_digest = COALESCE(?, authority_tuple_digest), " + + "issuance_fence_digest = COALESCE(?, issuance_fence_digest), " + + "postcondition_digest = COALESCE(?, postcondition_digest) " + + "WHERE operation_id = ? AND source_connect_operation_id = ? " + + "AND account_id = ? AND tenant_id = ? AND connect_scope_hash = ? " + + "AND request_id = ? AND request_digest_version = ? AND request_digest = ? " + + "AND status = 'PENDING' " + + "AND (?::VARCHAR IS NULL OR token_identity IS NULL OR token_identity = ?) " + + "AND (?::BYTEA IS NULL OR token_hash IS NULL OR token_hash = ?) " + + "AND (?::BYTEA IS NULL OR context_evidence_digest IS NULL " + + "OR context_evidence_digest = ?) " + + "AND (?::BYTEA IS NULL OR authority_tuple_digest IS NULL " + + "OR authority_tuple_digest = ?) " + + "AND (?::BYTEA IS NULL OR issuance_fence_digest IS NULL " + + "OR issuance_fence_digest = ?) " + + "AND (?::BYTEA IS NULL OR postcondition_digest IS NULL " + + "OR postcondition_digest = ?) RETURNING operation_id", + tokenIdentity, + checkedTokenHash, + checkedContextDigest, + checkedAuthorityDigest, + checkedFenceDigest, + checkedPostconditionDigest, + operation.operationId(), + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + tokenIdentity, + tokenIdentity, + checkedTokenHash, + checkedTokenHash, + checkedContextDigest, + checkedContextDigest, + checkedAuthorityDigest, + checkedAuthorityDigest, + checkedFenceDigest, + checkedFenceDigest, + checkedPostconditionDigest, + checkedPostconditionDigest); + if (changed == null) { + throw new EvidenceMismatchException( + "Pending bare LOGIN exchange already contains different evidence"); + } + AccountBareLoginExchangeOperation updated = + readOperationBySource(identity) + .filter(read -> read.operationId().equals(operation.operationId())) + .orElseThrow( + () -> + new IllegalStateException( + "Pending bare LOGIN exchange evidence has no exact operation readback")); + return updated; + } + + /** + * Stores one terminal successful result and its authenticated ciphertext in the caller's + * transaction. The claim and any pending evidence must have occurred in this same transaction; + * this repository never creates or decrypts the delegation JWT. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountBareLoginResponseEnvelope completeWithEnvelope( + ClaimResult claim, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + AccountBareLoginExchangeIdentity identity = requireClaimIdentity(claim); + byte[] digest = requireDigest(requestDigest, "request digest"); + validateTerminalResult(tokenIdentity, tokenHash); + Objects.requireNonNull(binding, "binding"); + validateBareLoginEnvelope(envelope); + + AccountBareLoginExchangeOperation operation = requireClaimedOperation(claim, digest); + if (operation.lifecycle() != Lifecycle.PENDING) { + throw new IllegalStateException( + "Bare LOGIN exchange operation is not pending and cannot be replaced"); + } + validateBinding(operation, identity, digest, binding); + requireEvidenceCompatible( + operation, + tokenIdentity, + copyNullable(tokenHash), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + + Record changed = + dsl.fetchOne( + "UPDATE " + + OPERATION_TABLE + + " SET status = 'COMMITTED', outcome_code = 'SUCCESS', token_identity = ?, " + + "token_hash = ?, context_evidence_digest = ?, authority_tuple_digest = ?, " + + "issuance_fence_digest = ?, postcondition_digest = ? " + + "WHERE operation_id = ? AND source_connect_operation_id = ? " + + "AND account_id = ? AND tenant_id = ? AND connect_scope_hash = ? " + + "AND request_id = ? AND request_digest_version = ? AND request_digest = ? " + + "AND status = 'PENDING' " + + "AND token_identity IS NOT DISTINCT FROM CAST(? AS VARCHAR) " + + "AND token_hash IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "AND context_evidence_digest IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "AND authority_tuple_digest IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "AND issuance_fence_digest IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "AND postcondition_digest IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "RETURNING operation_id", + tokenIdentity, + copyNullable(tokenHash), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest(), + operation.operationId(), + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + operation.tokenIdentity(), + operation.tokenHash(), + operation.contextEvidenceDigest(), + operation.authorityTupleDigest(), + operation.issuanceFenceDigest(), + operation.postconditionDigest()); + if (changed == null + || !operation.operationId().equals(changed.get("operation_id", UUID.class))) { + throw new EvidenceMismatchException("Bare LOGIN exchange evidence changed before completion"); + } + + AccountBareLoginExchangeOperation committed = + readOperationBySource(identity) + .filter(read -> read.operationId().equals(operation.operationId())) + .orElseThrow( + () -> + new IllegalStateException( + "Committed bare LOGIN exchange has no exact operation readback")); + if (committed.lifecycle() != Lifecycle.COMMITTED + || !"SUCCESS".equals(committed.outcomeCode()) + || !Objects.equals(committed.tokenIdentity(), tokenIdentity) + || !sameDigest(committed.tokenHash(), tokenHash) + || !sameDigest(committed.contextEvidenceDigest(), binding.contextEvidenceDigest()) + || !sameDigest(committed.authorityTupleDigest(), binding.authorityTupleDigest()) + || !sameDigest(committed.issuanceFenceDigest(), binding.issuanceFenceDigest()) + || !sameDigest(committed.postconditionDigest(), binding.postconditionDigest())) { + throw new IllegalStateException( + "Committed bare LOGIN exchange readback differs from requested evidence"); + } + return insertEnvelopeAndReadBack(committed, identity, digest, binding, envelope); + } + + /** + * Reads the exact terminal operation and its only response envelope. A pending operation without + * an envelope remains pending; a terminal operation without its exact envelope fails closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readResponseEnvelope( + AccountBareLoginExchangeIdentity identity, + byte[] requestDigest, + AccountEnvelopeBinding binding) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + Objects.requireNonNull(binding, "binding"); + requireCommittedSource(identity); + AccountBareLoginExchangeOperation operation = + readOperationBySource(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Bare LOGIN exchange operation is missing during envelope readback")); + assertIdentityMatches(operation, identity); + requireDigestMatch(operation, digest); + validateBinding(operation, identity, digest, binding); + + Record row = + dsl.fetchOne( + "SELECT operation_id, operation_kind, source_connect_operation_id, account_id, " + + "tenant_id, connect_scope_hash, request_id, request_digest_version, " + + "request_digest, format_version, key_id, purpose, nonce, ciphertext, " + + "context_evidence_digest, authority_tuple_digest, issuance_fence_digest, " + + "postcondition_digest FROM " + + ENVELOPE_TABLE + + " WHERE operation_id = ?", + operation.operationId()); + if (operation.lifecycle() == Lifecycle.PENDING) { + if (row != null) { + throw new IllegalStateException( + "Pending bare LOGIN exchange unexpectedly owns a response envelope"); + } + return Optional.empty(); + } + if (row == null) { + throw new IllegalStateException( + "Committed bare LOGIN exchange result has no response envelope"); + } + + requireEnvelopeIdentity(row, operation, identity, digest, binding); + AccountEnvelopePurpose purpose; + try { + purpose = AccountEnvelopePurpose.valueOf(requiredText(row, "purpose")); + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored bare LOGIN response purpose is invalid"); + } + if (purpose != AccountEnvelopePurpose.BARE_LOGIN_RESPONSE) { + throw new IllegalStateException("Stored bare LOGIN response envelope has the wrong purpose"); + } + AccountEncryptedEnvelope encrypted = + new AccountEncryptedEnvelope( + requiredInt(row, "format_version"), + requiredText(row, "key_id"), + purpose, + requiredBytes(row, "nonce"), + requiredBytes(row, "ciphertext")); + return Optional.of( + new AccountBareLoginResponseEnvelope(operation.operationId(), binding, encrypted)); + } + + private AccountBareLoginResponseEnvelope insertEnvelopeAndReadBack( + AccountBareLoginExchangeOperation operation, + AccountBareLoginExchangeIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + int inserted = + dsl.execute( + "INSERT INTO " + + ENVELOPE_TABLE + + " (operation_id, operation_kind, source_connect_operation_id, account_id, " + + "tenant_id, connect_scope_hash, request_id, request_digest_version, " + + "request_digest, format_version, key_id, purpose, nonce, ciphertext, " + + "context_evidence_digest, authority_tuple_digest, issuance_fence_digest, " + + "postcondition_digest) VALUES (?, 'BARE_LOGIN_EXCHANGE', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operation.operationId(), + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose().name(), + envelope.nonce(), + envelope.ciphertext(), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + if (inserted != 1) { + throw new IllegalStateException("Bare LOGIN response envelope was not stored exactly once"); + } + + AccountBareLoginResponseEnvelope stored = + readResponseEnvelope(identity, digest, binding) + .orElseThrow( + () -> + new IllegalStateException( + "Bare LOGIN response envelope has no exact durable readback")); + if (!stored.operationId().equals(operation.operationId()) + || !stored.binding().equals(binding) + || !stored.envelope().equals(envelope)) { + throw new IllegalStateException( + "Bare LOGIN response envelope readback differs from requested envelope"); + } + return stored; + } + + private Optional readOperationBySource( + AccountBareLoginExchangeIdentity identity) { + Record row = + dsl.fetchOne( + "SELECT operation_id, source_connect_operation_id, account_id, tenant_id, " + + "connect_scope_hash, request_id, request_digest_version, request_digest, status, " + + "outcome_code, token_identity, token_hash, context_evidence_digest, " + + "authority_tuple_digest, issuance_fence_digest, postcondition_digest, " + + "created_at, updated_at FROM " + + OPERATION_TABLE + + " WHERE source_connect_operation_id = ?", + identity.sourceConnectOperationId()); + return row == null ? Optional.empty() : Optional.of(toOperation(row)); + } + + private Optional readOperationByRequest( + AccountBareLoginExchangeIdentity identity) { + Record row = + dsl.fetchOne( + "SELECT operation_id, source_connect_operation_id, account_id, tenant_id, " + + "connect_scope_hash, request_id, request_digest_version, request_digest, status, " + + "outcome_code, token_identity, token_hash, context_evidence_digest, " + + "authority_tuple_digest, issuance_fence_digest, postcondition_digest, " + + "created_at, updated_at FROM " + + OPERATION_TABLE + + " WHERE account_id = ? AND tenant_id = ? AND connect_scope_hash = ? " + + "AND request_id = ?", + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId()); + return row == null ? Optional.empty() : Optional.of(toOperation(row)); + } + + private void requireCommittedSource(AccountBareLoginExchangeIdentity identity) { + Record source = + dsl.fetchOne( + "SELECT operation_id, account_id, tenant_id, connect_scope_hash, status FROM " + + SOURCE_OPERATION_TABLE + + " WHERE operation_id = ?", + identity.sourceConnectOperationId()); + if (source == null) { + throw new IllegalStateException( + "Bare LOGIN exchange source connect operation is missing or untrusted"); + } + String status = requiredText(source, "status"); + if (!"COMMITTED".equals(status)) { + throw new IllegalStateException( + "Bare LOGIN exchange source connect operation is not committed"); + } + if (requiredLong(source, "account_id") != identity.accountId() + || requiredLong(source, "tenant_id") != identity.tenantId() + || !identity.connectScopeHash().equals(requiredText(source, "connect_scope_hash"))) { + throw new IdentityConflictException( + "Bare LOGIN exchange source connect operation identity does not match"); + } + } + + private static AccountBareLoginExchangeOperation toOperation(Record row) { + return new AccountBareLoginExchangeOperation( + requiredUuid(row, "operation_id"), + requiredUuid(row, "source_connect_operation_id"), + requiredLong(row, "account_id"), + requiredLong(row, "tenant_id"), + requiredText(row, "connect_scope_hash"), + requiredText(row, "request_id"), + requiredInt(row, "request_digest_version"), + requiredBytes(row, "request_digest"), + Lifecycle.fromDatabase(requiredText(row, "status")), + row.get("outcome_code", String.class), + row.get("token_identity", String.class), + row.get("token_hash", byte[].class), + row.get("context_evidence_digest", byte[].class), + row.get("authority_tuple_digest", byte[].class), + row.get("issuance_fence_digest", byte[].class), + row.get("postcondition_digest", byte[].class), + toInstant(row.get("created_at", OffsetDateTime.class)), + toInstant(row.get("updated_at", OffsetDateTime.class))); + } + + private static void requireEnvelopeIdentity( + Record row, + AccountBareLoginExchangeOperation operation, + AccountBareLoginExchangeIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding) { + if (!operation.operationId().equals(requiredUuid(row, "operation_id")) + || !"BARE_LOGIN_EXCHANGE".equals(requiredText(row, "operation_kind")) + || !operation + .sourceConnectOperationId() + .equals(requiredUuid(row, "source_connect_operation_id")) + || requiredLong(row, "account_id") != identity.accountId() + || requiredLong(row, "tenant_id") != identity.tenantId() + || !identity.connectScopeHash().equals(requiredText(row, "connect_scope_hash")) + || !identity.requestId().equals(requiredText(row, "request_id")) + || requiredInt(row, "request_digest_version") != REQUEST_DIGEST_VERSION + || !MessageDigest.isEqual(digest, requiredBytes(row, "request_digest")) + || !MessageDigest.isEqual( + operation.contextEvidenceDigest(), requiredBytes(row, "context_evidence_digest")) + || !MessageDigest.isEqual( + operation.authorityTupleDigest(), requiredBytes(row, "authority_tuple_digest")) + || !MessageDigest.isEqual( + operation.issuanceFenceDigest(), requiredBytes(row, "issuance_fence_digest")) + || !MessageDigest.isEqual( + operation.postconditionDigest(), requiredBytes(row, "postcondition_digest"))) { + throw new IllegalStateException( + "Bare LOGIN response envelope identity or evidence readback does not match"); + } + validateBinding(operation, identity, digest, binding); + } + + private static void validateBinding( + AccountBareLoginExchangeOperation operation, + AccountBareLoginExchangeIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding) { + if (binding.operationKind() != AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE + || !operation.operationId().toString().equals(binding.operationId()) + || !identity.requestId().equals(binding.requestId()) + || !Long.toString(identity.accountId()).equals(binding.accountId()) + || !Long.toString(identity.tenantId()).equals(binding.tenantId()) + || !identity.connectScopeId().equals(binding.connectScopeId()) + || !identity + .sourceConnectOperationId() + .toString() + .equals(binding.sourceConnectOperationId()) + || !MessageDigest.isEqual(digest, binding.requestDigest())) { + throw new EvidenceMismatchException( + "Bare LOGIN response binding does not name the exact operation identity and digest"); + } + if (operation.lifecycle() == Lifecycle.COMMITTED) { + requireOperationEvidence(operation, binding); + } else { + requireEvidenceCompatible( + operation, + null, + null, + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + } + } + + private static void requireOperationEvidence( + AccountBareLoginExchangeOperation operation, AccountEnvelopeBinding binding) { + if (!sameDigest(operation.contextEvidenceDigest(), binding.contextEvidenceDigest()) + || !sameDigest(operation.authorityTupleDigest(), binding.authorityTupleDigest()) + || !sameDigest(operation.issuanceFenceDigest(), binding.issuanceFenceDigest()) + || !sameDigest(operation.postconditionDigest(), binding.postconditionDigest())) { + throw new EvidenceMismatchException( + "Bare LOGIN response binding differs from committed operation evidence"); + } + } + + private static void validateTerminalResult(String tokenIdentity, byte[] tokenHash) { + if (tokenIdentity == null + || tokenIdentity.isBlank() + || tokenIdentity.length() > MAX_TOKEN_IDENTITY_LENGTH + || tokenIdentity.indexOf('\0') >= 0 + || tokenHash == null + || tokenHash.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException("Committed bare LOGIN result evidence is invalid"); + } + } + + private static void validateTokenEvidence(String tokenIdentity, byte[] tokenHash) { + if ((tokenIdentity == null) != (tokenHash == null)) { + throw new IllegalArgumentException("Bare LOGIN token identity and hash evidence must pair"); + } + if (tokenIdentity != null + && (tokenIdentity.isBlank() + || tokenIdentity.length() > MAX_TOKEN_IDENTITY_LENGTH + || tokenIdentity.indexOf('\0') >= 0)) { + throw new IllegalArgumentException("Bare LOGIN token identity evidence is invalid"); + } + } + + private AccountBareLoginExchangeIdentity requireClaimIdentity(ClaimResult claim) { + Objects.requireNonNull(claim, "claim"); + if (claim.disposition() != ClaimDisposition.CLAIMED) { + throw new IllegalStateException( + "Only the first bare LOGIN exchange claimant may record evidence or an outcome"); + } + return claim.identity(); + } + + private AccountBareLoginExchangeOperation requireClaimedOperation( + ClaimResult claim, byte[] digest) { + AccountBareLoginExchangeIdentity identity = requireClaimIdentity(claim); + requireCommittedSource(identity); + AccountBareLoginExchangeOperation operation = + readOperationBySource(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Bare LOGIN exchange operation is missing during owner update")); + if (!claim.operation().operationId().equals(operation.operationId())) { + throw new IllegalStateException("Bare LOGIN claim no longer owns the durable operation"); + } + assertIdentityMatches(operation, identity); + requireDigestMatch(operation, digest); + return operation; + } + + private static void assertIdentityMatches( + AccountBareLoginExchangeOperation operation, AccountBareLoginExchangeIdentity identity) { + if (!identity.sourceConnectOperationId().equals(operation.sourceConnectOperationId()) + || identity.accountId() != operation.accountId() + || identity.tenantId() != operation.tenantId() + || !identity.connectScopeHash().equals(operation.connectScopeHash()) + || !identity.requestId().equals(operation.requestId())) { + throw new IdentityConflictException( + "Bare LOGIN exchange identity was reused with different source or binding"); + } + } + + private static void requireEvidenceCompatible( + AccountBareLoginExchangeOperation operation, + String tokenIdentity, + byte[] tokenHash, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest) { + if ((operation.tokenIdentity() != null + && tokenIdentity != null + && !operation.tokenIdentity().equals(tokenIdentity)) + || differsWhenProvided(operation.tokenHash(), tokenHash) + || differsWhenProvided(operation.contextEvidenceDigest(), contextEvidenceDigest) + || differsWhenProvided(operation.authorityTupleDigest(), authorityTupleDigest) + || differsWhenProvided(operation.issuanceFenceDigest(), issuanceFenceDigest) + || differsWhenProvided(operation.postconditionDigest(), postconditionDigest)) { + throw new EvidenceMismatchException( + "Bare LOGIN exchange evidence is already bound to different values"); + } + } + + private static boolean differsWhenProvided(byte[] stored, byte[] candidate) { + return stored != null && candidate != null && !MessageDigest.isEqual(stored, candidate); + } + + private static boolean sameDigest(byte[] left, byte[] right) { + return left == null ? right == null : right != null && MessageDigest.isEqual(left, right); + } + + private static void validateBareLoginEnvelope(AccountEncryptedEnvelope envelope) { + Objects.requireNonNull(envelope, "envelope"); + if (envelope.purpose() != AccountEnvelopePurpose.BARE_LOGIN_RESPONSE) { + throw new EvidenceMismatchException( + "Bare LOGIN exchange cannot store an envelope for another purpose"); + } + } + + private static void requireDigestMatch( + AccountBareLoginExchangeOperation operation, byte[] expectedDigest) { + if (!MessageDigest.isEqual(operation.requestDigest(), expectedDigest)) { + throw new IdempotencyConflictException( + "Bare LOGIN exchange request identity was reused with a different digest"); + } + } + + private static void validateIdentity(AccountBareLoginExchangeIdentity identity) { + Objects.requireNonNull(identity, "identity"); + } + + private static byte[] requireDigest(byte[] value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return Arrays.copyOf(value, value.length); + } + + private static byte[] optionalDigest(byte[] value, String fieldName) { + return value == null ? null : requireDigest(value, fieldName); + } + + private static byte[] copyNullable(byte[] value) { + return value == null ? null : value.clone(); + } + + private static Instant toInstant(OffsetDateTime value) { + return value == null ? null : JooqPersistenceSupport.toInstant(value); + } + + private static long requiredLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) { + throw new IllegalStateException("Stored bare LOGIN exchange field is missing: " + field); + } + return value; + } + + private static int requiredInt(Record row, String field) { + Integer value = row.get(field, Integer.class); + if (value == null) { + throw new IllegalStateException("Stored bare LOGIN exchange field is missing: " + field); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) { + throw new IllegalStateException("Stored bare LOGIN exchange field is missing: " + field); + } + return value; + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw new IllegalStateException("Stored bare LOGIN exchange field is missing: " + field); + } + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) { + throw new IllegalStateException("Stored bare LOGIN exchange field is missing: " + field); + } + return value; + } + + public enum ClaimDisposition { + CLAIMED, + REPLAYED + } + + public static class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static final class IdentityConflictException extends IdempotencyConflictException { + public IdentityConflictException(String message) { + super(message); + } + } + + public static final class EvidenceMismatchException extends IllegalStateException { + public EvidenceMismatchException(String message) { + super(message); + } + } + + public static final class ClaimResult { + private final ClaimDisposition disposition; + private final AccountBareLoginExchangeIdentity identity; + private final AccountBareLoginExchangeOperation operation; + + private ClaimResult( + ClaimDisposition disposition, + AccountBareLoginExchangeIdentity identity, + AccountBareLoginExchangeOperation operation) { + this.disposition = Objects.requireNonNull(disposition, "disposition"); + this.identity = Objects.requireNonNull(identity, "identity"); + this.operation = Objects.requireNonNull(operation, "operation"); + } + + public ClaimDisposition disposition() { + return disposition; + } + + public AccountBareLoginExchangeIdentity identity() { + return identity; + } + + public AccountBareLoginExchangeOperation operation() { + return operation; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginResponseEnvelope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginResponseEnvelope.java new file mode 100644 index 0000000000..1b7fa043f9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginResponseEnvelope.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; + +/** Exact persisted ciphertext plus the binding required for authenticated bare-LOGIN recovery. */ +public record AccountBareLoginResponseEnvelope( + UUID operationId, AccountEnvelopeBinding binding, AccountEncryptedEnvelope envelope) { + + public AccountBareLoginResponseEnvelope { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(envelope, "envelope"); + if (binding.operationKind() != AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE + || !operationId.toString().equals(binding.operationId()) + || envelope.purpose() != AccountEnvelopePurpose.BARE_LOGIN_RESPONSE) { + throw new IllegalArgumentException("Bare LOGIN response envelope binding is invalid"); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V37__account_bare_login_exchange_storage.sql b/services/account-service/src/main/resources/db/migration/V37__account_bare_login_exchange_storage.sql new file mode 100644 index 0000000000..0ba9c3f90c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V37__account_bare_login_exchange_storage.sql @@ -0,0 +1,328 @@ +-- Durable first-writer-wins storage for the Account-owned bare first-party LOGIN exchange. +-- The source connect-operation identity is consumed at most once. The response envelope is a +-- separate purpose-tagged encrypted record; neither table stores a raw delegation JWT. +CREATE TABLE account_bare_login_exchange_operations ( + operation_id UUID PRIMARY KEY, + source_connect_operation_id UUID NOT NULL + REFERENCES account_connect_token_issuance_operations(operation_id) ON DELETE RESTRICT, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + tenant_id BIGINT NOT NULL, + connect_scope_hash VARCHAR(71) NOT NULL, + request_id VARCHAR(128) NOT NULL, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + status VARCHAR(16) NOT NULL, + outcome_code VARCHAR(64), + token_identity VARCHAR(128), + token_hash BYTEA, + context_evidence_digest BYTEA, + authority_tuple_digest BYTEA, + issuance_fence_digest BYTEA, + postcondition_digest BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_bare_login_exchange_source_uq + UNIQUE (source_connect_operation_id), + CONSTRAINT account_bare_login_exchange_request_uq + UNIQUE (account_id, tenant_id, connect_scope_hash, request_id), + CONSTRAINT account_bare_login_exchange_identity_check + CHECK (account_id > 0 + AND tenant_id > 0 + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND request_digest_version = 1 + AND octet_length(request_digest) = 32), + CONSTRAINT account_bare_login_exchange_status_check + CHECK (status IN ('PENDING', 'COMMITTED')), + CONSTRAINT account_bare_login_exchange_evidence_check + CHECK (((token_identity IS NULL AND token_hash IS NULL) + OR (token_identity IS NOT NULL + AND length(btrim(token_identity)) BETWEEN 1 AND 128 + AND token_hash IS NOT NULL + AND octet_length(token_hash) = 32)) + AND (context_evidence_digest IS NULL OR octet_length(context_evidence_digest) = 32) + AND (authority_tuple_digest IS NULL OR octet_length(authority_tuple_digest) = 32) + AND (issuance_fence_digest IS NULL OR octet_length(issuance_fence_digest) = 32) + AND (postcondition_digest IS NULL OR octet_length(postcondition_digest) = 32)), + CONSTRAINT account_bare_login_exchange_outcome_check + CHECK ((status = 'PENDING' AND outcome_code IS NULL) + OR (status = 'COMMITTED' + AND outcome_code = 'SUCCESS' + AND token_identity IS NOT NULL + AND token_hash IS NOT NULL + AND context_evidence_digest IS NOT NULL + AND authority_tuple_digest IS NOT NULL + AND issuance_fence_digest IS NOT NULL + AND postcondition_digest IS NOT NULL)) +); + +CREATE TABLE account_bare_login_response_envelopes ( + operation_id UUID PRIMARY KEY, + operation_kind VARCHAR(32) NOT NULL, + source_connect_operation_id UUID NOT NULL + REFERENCES account_connect_token_issuance_operations(operation_id) ON DELETE RESTRICT, + account_id BIGINT NOT NULL, + tenant_id BIGINT NOT NULL, + connect_scope_hash VARCHAR(71) NOT NULL, + request_id VARCHAR(128) NOT NULL, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + format_version INTEGER NOT NULL, + key_id VARCHAR(64) NOT NULL, + purpose VARCHAR(32) NOT NULL, + nonce BYTEA NOT NULL, + ciphertext BYTEA NOT NULL, + context_evidence_digest BYTEA NOT NULL, + authority_tuple_digest BYTEA NOT NULL, + issuance_fence_digest BYTEA NOT NULL, + postcondition_digest BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_bare_login_response_envelope_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_bare_login_exchange_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_bare_login_response_envelope_identity_check + CHECK (operation_kind = 'BARE_LOGIN_EXCHANGE' + AND source_connect_operation_id IS NOT NULL + AND account_id > 0 + AND tenant_id > 0 + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND request_digest_version = 1 + AND octet_length(request_digest) = 32), + CONSTRAINT account_bare_login_response_envelope_crypto_check + CHECK (format_version = 1 + AND length(btrim(key_id)) BETWEEN 1 AND 64 + AND key_id ~ '^[A-Za-z0-9_-]+$' + AND purpose = 'BARE_LOGIN_RESPONSE' + AND octet_length(nonce) = 12 + AND octet_length(ciphertext) BETWEEN 16 AND 65552 + AND octet_length(context_evidence_digest) = 32 + AND octet_length(authority_tuple_digest) = 32 + AND octet_length(issuance_fence_digest) = 32 + AND octet_length(postcondition_digest) = 32) +); + +-- A request's first writer owns the source operation, exchange request ID, and digest. Only the +-- still-pending row may acquire evidence and reach the one immutable terminal success outcome. +-- This migration rejects deletion and deliberately defines no expiry or cleanup behavior. +-- [jooq ignore start] +CREATE FUNCTION account_bare_login_exchange_source_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_operation account_connect_token_issuance_operations%ROWTYPE; +BEGIN + SELECT * INTO source_operation + FROM account_connect_token_issuance_operations + WHERE operation_id = NEW.source_connect_operation_id; + IF NOT FOUND + OR source_operation.status <> 'COMMITTED' + OR source_operation.account_id IS DISTINCT FROM NEW.account_id + OR source_operation.tenant_id IS DISTINCT FROM NEW.tenant_id + OR source_operation.connect_scope_hash IS DISTINCT FROM NEW.connect_scope_hash THEN + RAISE EXCEPTION 'Bare LOGIN exchange source must be committed and match its identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_source_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_bare_login_exchange_source_insert_guard_trigger + BEFORE INSERT ON account_bare_login_exchange_operations + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_exchange_source_insert_guard(); + +CREATE FUNCTION account_bare_login_exchange_operation_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.source_connect_operation_id IS DISTINCT FROM OLD.source_connect_operation_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.connect_scope_hash IS DISTINCT FROM OLD.connect_scope_hash + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Bare LOGIN exchange identity and request digest are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_identity_immutable'; + END IF; + IF (OLD.token_identity IS NOT NULL AND NEW.token_identity IS DISTINCT FROM OLD.token_identity) + OR (OLD.token_hash IS NOT NULL AND NEW.token_hash IS DISTINCT FROM OLD.token_hash) + OR (OLD.context_evidence_digest IS NOT NULL + AND NEW.context_evidence_digest IS DISTINCT FROM OLD.context_evidence_digest) + OR (OLD.authority_tuple_digest IS NOT NULL + AND NEW.authority_tuple_digest IS DISTINCT FROM OLD.authority_tuple_digest) + OR (OLD.issuance_fence_digest IS NOT NULL + AND NEW.issuance_fence_digest IS DISTINCT FROM OLD.issuance_fence_digest) + OR (OLD.postcondition_digest IS NOT NULL + AND NEW.postcondition_digest IS DISTINCT FROM OLD.postcondition_digest) THEN + RAISE EXCEPTION 'Bare LOGIN exchange evidence cannot be replaced' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_evidence_immutable'; + END IF; + IF OLD.status = 'COMMITTED' THEN + RAISE EXCEPTION 'Terminal bare LOGIN exchange outcome is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_terminal_immutable'; + END IF; + IF NEW.status IS DISTINCT FROM OLD.status + AND NOT (OLD.status = 'PENDING' AND NEW.status = 'COMMITTED') THEN + RAISE EXCEPTION 'Bare LOGIN exchange lifecycle transition is invalid' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_lifecycle_transition'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_bare_login_exchange_operation_update_guard_trigger + BEFORE UPDATE ON account_bare_login_exchange_operations + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_exchange_operation_update_guard(); + +CREATE FUNCTION account_bare_login_exchange_operation_delete_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Bare LOGIN exchange operation is immutable and cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_operation_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_bare_login_exchange_operation_delete_guard_trigger + BEFORE DELETE ON account_bare_login_exchange_operations + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_exchange_operation_delete_guard(); + +CREATE FUNCTION account_bare_login_response_envelope_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Bare LOGIN response envelope is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_response_envelope_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_bare_login_response_envelope_update_guard_trigger + BEFORE UPDATE ON account_bare_login_response_envelopes + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_response_envelope_update_guard(); + +CREATE FUNCTION account_bare_login_response_envelope_delete_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Bare LOGIN response envelope is immutable and cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_response_envelope_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_bare_login_response_envelope_delete_guard_trigger + BEFORE DELETE ON account_bare_login_response_envelopes + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_response_envelope_delete_guard(); + +CREATE FUNCTION account_bare_login_pending_commit_check() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + final_status VARCHAR(16); +BEGIN + SELECT status INTO final_status + FROM account_bare_login_exchange_operations + WHERE operation_id = NEW.operation_id; + IF final_status = 'PENDING' THEN + RAISE EXCEPTION 'Bare LOGIN exchange cannot commit while still pending' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_pending_commit_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_bare_login_pending_commit_check_trigger + AFTER INSERT OR UPDATE ON account_bare_login_exchange_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_pending_commit_check(); + +CREATE FUNCTION account_bare_login_response_envelope_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation account_bare_login_exchange_operations%ROWTYPE; +BEGIN + SELECT * INTO operation + FROM account_bare_login_exchange_operations + WHERE operation_id = NEW.operation_id; + IF NOT FOUND + OR operation.status <> 'COMMITTED' + OR operation.source_connect_operation_id IS DISTINCT FROM NEW.source_connect_operation_id + OR operation.account_id IS DISTINCT FROM NEW.account_id + OR operation.tenant_id IS DISTINCT FROM NEW.tenant_id + OR operation.connect_scope_hash IS DISTINCT FROM NEW.connect_scope_hash + OR operation.request_id IS DISTINCT FROM NEW.request_id + OR operation.request_digest_version IS DISTINCT FROM NEW.request_digest_version + OR operation.request_digest IS DISTINCT FROM NEW.request_digest + OR operation.context_evidence_digest IS DISTINCT FROM NEW.context_evidence_digest + OR operation.authority_tuple_digest IS DISTINCT FROM NEW.authority_tuple_digest + OR operation.issuance_fence_digest IS DISTINCT FROM NEW.issuance_fence_digest + OR operation.postcondition_digest IS DISTINCT FROM NEW.postcondition_digest THEN + RAISE EXCEPTION 'Bare LOGIN response envelope does not match its terminal operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_response_envelope_operation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_bare_login_response_envelope_insert_guard_trigger + BEFORE INSERT ON account_bare_login_response_envelopes + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_response_envelope_insert_guard(); + +CREATE FUNCTION account_bare_login_terminal_envelope_check() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.status = 'COMMITTED' AND NOT EXISTS ( + SELECT 1 + FROM account_bare_login_response_envelopes envelope + WHERE envelope.operation_id = NEW.operation_id + AND envelope.source_connect_operation_id = NEW.source_connect_operation_id + AND envelope.account_id = NEW.account_id + AND envelope.tenant_id = NEW.tenant_id + AND envelope.connect_scope_hash = NEW.connect_scope_hash + AND envelope.request_id = NEW.request_id + AND envelope.request_digest_version = NEW.request_digest_version + AND envelope.request_digest = NEW.request_digest + AND envelope.context_evidence_digest = NEW.context_evidence_digest + AND envelope.authority_tuple_digest = NEW.authority_tuple_digest + AND envelope.issuance_fence_digest = NEW.issuance_fence_digest + AND envelope.postcondition_digest = NEW.postcondition_digest + ) THEN + RAISE EXCEPTION 'Terminal bare LOGIN exchange requires its exact response envelope' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_terminal_envelope_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_bare_login_terminal_envelope_check_trigger + AFTER INSERT OR UPDATE ON account_bare_login_exchange_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_terminal_envelope_check(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java new file mode 100644 index 0000000000..de1852f5d8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java @@ -0,0 +1,756 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeOperation.Lifecycle; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginResponseEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountBareLoginExchangeRepositoryIntegrationTest { + private static final String SCHEMA = "account_bare_login_exchange_proof"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void claimOnlyTransactionRollsBackPendingExchange() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(0); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(identity, requestDigest))) + .isInstanceOf(TransactionSystemException.class); + assertThat( + inTransaction( + context.transaction(), () -> context.repository().find(identity, requestDigest))) + .isEmpty(); + } + + @Test + void sourceMustBeCommittedAndFirstWriterOwnsTheExchangeIdentity() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] digest = digest(1); + + ExchangeResult firstResult = + inTransaction( + context.transaction(), + () -> { + var claimed = context.repository().claim(identity, digest); + AccountEnvelopeBinding binding = + binding(claimed.operation().operationId(), identity, digest, 2); + context + .repository() + .recordPendingEvidence( + claimed, + digest, + "delegation-jti-source", + digest(80), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + claimed, + digest, + "delegation-jti-source", + digest(80), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(claimed, binding, stored); + }); + var claimed = firstResult.claim(); + var exactRetry = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + + assertThat(claimed.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.CLAIMED); + assertThat(exactRetry.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + assertThat(exactRetry.operation().operationId()).isEqualTo(claimed.operation().operationId()); + assertThat(exactRetry.operation().lifecycle()).isEqualTo(Lifecycle.COMMITTED); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, digest, firstResult.binding()))) + .contains(firstResult.envelope()); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().claim(identity, digest(2)))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdempotencyConflictException.class); + + AccountBareLoginExchangeIdentity competingIdentity = + new AccountBareLoginExchangeIdentity( + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + "different-exchange-request"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(competingIdentity, digest))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdentityConflictException.class); + + Source pendingSource = pendingSource(context, identity.accountId(), identity.connectScopeId()); + AccountBareLoginExchangeIdentity pendingIdentity = pendingSource.exchangeIdentity(); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(pendingIdentity, digest))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not committed"); + } + + @Test + void pendingEvidenceThenTerminalSuccessReadBacksExactPurposeBoundEnvelope() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(10); + ExchangeResult result = + inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + AccountEnvelopeBinding binding = + binding(claim.operation().operationId(), identity, requestDigest, 21); + var pending = + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-1", + digest(80), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + assertThat(pending.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(pending.tokenIdentity()).isEqualTo("delegation-jti-1"); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-1", + digest(80), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(claim, binding, stored); + }); + var claim = result.claim(); + AccountEnvelopeBinding binding = result.binding(); + var stored = result.envelope(); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .contains(stored); + var exactReadback = + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, requestDigest, binding) + .orElseThrow()); + + assertThat(stored.operationId()).isEqualTo(claim.operation().operationId()); + assertThat(exactReadback).isEqualTo(stored); + assertThat(exactReadback.binding()).isEqualTo(binding); + assertThat(exactReadback.envelope()).isEqualTo(stored.envelope()); + var exactRetry = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + assertThat(exactRetry.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + assertThat(exactRetry.operation().operationId()).isEqualTo(claim.operation().operationId()); + var committed = + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()); + assertThat(committed.lifecycle()).isEqualTo(Lifecycle.COMMITTED); + assertThat(committed.outcomeCode()).isEqualTo("SUCCESS"); + assertThat(committed.tokenHash()).containsExactly(digest(80)); + assertThat(committed.contextEvidenceDigest()).containsExactly(binding.contextEvidenceDigest()); + assertThat(committed.toString()) + .isEqualTo( + "AccountBareLoginExchangeOperation{operationId=" + + committed.operationId() + + ", sourceConnectOperationId=" + + committed.sourceConnectOperationId() + + ", accountId=" + + committed.accountId() + + ", tenantId=" + + committed.tenantId() + + ", requestId='" + + committed.requestId() + + "', lifecycle=COMMITTED, secretEvidence=}"); + assertThat(committed.toString()).doesNotContain("delegation-jti-1"); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().find(identity, digest(11)))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdempotencyConflictException.class); + } + + @Test + void wrongIdentityBindingOrPurposeCannotTerminalizeThePendingExchange() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(20); + ExchangeResult result = + inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + AccountEnvelopeBinding binding = + binding(claim.operation().operationId(), identity, requestDigest, 31); + assertThatThrownBy( + () -> + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-2", + digest(81), + binding(UUID.randomUUID(), identity, requestDigest, 31), + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE))) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + assertThatThrownBy( + () -> + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-2", + digest(81), + binding, + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE))) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-2", + digest(81), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(claim, binding, stored); + }); + assertThat(result.envelope().operationId()).isEqualTo(result.claim().operation().operationId()); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, requestDigest, result.binding()))) + .contains(result.envelope()); + } + + @Test + void conflictingPendingEvidenceCannotReplaceWriteOnceTerminalEvidence() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(30); + ExchangeResult result = + inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + AccountEnvelopeBinding originalBinding = + binding(claim.operation().operationId(), identity, requestDigest, 41); + var pending = + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-original", + digest(90), + originalBinding.contextEvidenceDigest(), + originalBinding.authorityTupleDigest(), + originalBinding.issuanceFenceDigest(), + originalBinding.postconditionDigest()); + assertThat(pending.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(pending.tokenIdentity()).isEqualTo("delegation-jti-original"); + + AccountEnvelopeBinding conflictingBinding = + binding(claim.operation().operationId(), identity, requestDigest, 42); + assertThatThrownBy( + () -> + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-conflict", + digest(91), + conflictingBinding.contextEvidenceDigest(), + conflictingBinding.authorityTupleDigest(), + conflictingBinding.issuanceFenceDigest(), + conflictingBinding.postconditionDigest())) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + assertThatThrownBy( + () -> + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-conflict", + digest(91), + conflictingBinding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE))) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-original", + digest(90), + originalBinding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(claim, originalBinding, stored); + }); + assertThat(result.envelope().operationId()).isEqualTo(result.claim().operation().operationId()); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, requestDigest, result.binding()))) + .contains(result.envelope()); + } + + @Test + void directSqlExchangeInsertRequiresCommittedMatchingSourceIdentity() { + TestContext context = newTestContext(); + long pendingAccountId = insertAccount(context.dsl()); + Source pendingSource = + pendingSource(context, pendingAccountId, "pending-source-" + UUID.randomUUID()); + AccountBareLoginExchangeIdentity pendingIdentity = pendingSource.exchangeIdentity(); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + insertBareOperationDirect( + context, UUID.randomUUID(), pendingIdentity, digest(70)))) + .isInstanceOf(DataAccessException.class); + + Source committedSource = committedSource(context); + AccountBareLoginExchangeIdentity committedIdentity = committedSource.exchangeIdentity(); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + insertBareOperationDirect( + context, + UUID.randomUUID(), + committedIdentity.sourceConnectOperationId(), + committedIdentity.accountId(), + committedIdentity.tenantId() + 1, + committedIdentity.connectScopeId(), + "wrong-tenant-" + UUID.randomUUID(), + digest(71)))) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + insertBareOperationDirect( + context, + UUID.randomUUID(), + committedIdentity.sourceConnectOperationId(), + committedIdentity.accountId(), + committedIdentity.tenantId(), + committedIdentity.connectScopeId() + "-wrong", + "wrong-scope-" + UUID.randomUUID(), + digest(72)))) + .isInstanceOf(DataAccessException.class); + + long otherAccountId = insertAccount(context.dsl()); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + insertBareOperationDirect( + context, + UUID.randomUUID(), + committedIdentity.sourceConnectOperationId(), + otherAccountId, + committedIdentity.tenantId(), + committedIdentity.connectScopeId(), + "wrong-account-" + UUID.randomUUID(), + digest(73)))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void directSqlCannotDeletePendingOrTerminalExchangeRows() { + TestContext context = newTestContext(); + Source pendingSource = committedSource(context); + AccountBareLoginExchangeIdentity pendingIdentity = pendingSource.exchangeIdentity(); + byte[] pendingDigest = digest(74); + UUID pendingOperationId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + deletePendingOperationDirect( + context, pendingOperationId, pendingIdentity, pendingDigest))) + .isInstanceOf(DataAccessException.class); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().find(pendingIdentity, pendingDigest))) + .isEmpty(); + + Source terminalSource = committedSource(context); + AccountBareLoginExchangeIdentity terminalIdentity = terminalSource.exchangeIdentity(); + byte[] terminalDigest = digest(75); + ExchangeResult terminalResult = + inTransaction( + context.transaction(), + () -> { + var terminalClaim = context.repository().claim(terminalIdentity, terminalDigest); + AccountEnvelopeBinding terminalBinding = + binding( + terminalClaim.operation().operationId(), + terminalIdentity, + terminalDigest, + 76); + context + .repository() + .recordPendingEvidence( + terminalClaim, + terminalDigest, + "delegation-jti-delete-guard", + digest(92), + terminalBinding.contextEvidenceDigest(), + terminalBinding.authorityTupleDigest(), + terminalBinding.issuanceFenceDigest(), + terminalBinding.postconditionDigest()); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + terminalClaim, + terminalDigest, + "delegation-jti-delete-guard", + digest(92), + terminalBinding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(terminalClaim, terminalBinding, stored); + }); + AccountBareLoginResponseEnvelope stored = terminalResult.envelope(); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "DELETE FROM account_bare_login_response_envelopes " + + "WHERE operation_id = ?", + stored.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "DELETE FROM account_bare_login_exchange_operations " + + "WHERE operation_id = ?", + stored.operationId()))) + .isInstanceOf(DataAccessException.class); + var terminalReadback = + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope( + terminalIdentity, terminalDigest, terminalResult.binding())); + assertThat(terminalReadback).contains(stored); + } + + private TestContext newTestContext() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + SCHEMA); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + dsl, + new AccountBareLoginExchangeRepository(dsl), + new AccountConnectTokenIssuanceRepository(dsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + } + + private Source committedSource(TestContext context) { + long accountId = insertAccount(context.dsl()); + return createSource(context, accountId, "connect-scope-" + UUID.randomUUID(), true); + } + + private Source pendingSource(TestContext context, long accountId, String connectScopeId) { + return createSource(context, accountId, connectScopeId, false); + } + + private Source createSource( + TestContext context, long accountId, String connectScopeId, boolean commitSource) { + AccountConnectTokenIssuanceIdentity sourceIdentity = + new AccountConnectTokenIssuanceIdentity( + accountId, 77L, connectScopeId, "connect-request-" + UUID.randomUUID()); + byte[] sourceDigest = digest(commitSource ? 60 : 61); + var sourceClaim = + inTransaction( + context.transaction(), + () -> context.sourceRepository().claim(sourceIdentity, sourceDigest)); + if (commitSource) { + AccountEnvelopeBinding sourceBinding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + sourceClaim.operation().operationId().toString(), + sourceIdentity.requestId(), + Long.toString(sourceIdentity.accountId()), + Long.toString(sourceIdentity.tenantId()), + sourceIdentity.connectScopeId(), + null, + sourceDigest, + digest(62), + digest(63), + digest(64), + digest(65)); + inTransaction( + context.transaction(), + () -> + context + .sourceRepository() + .completeWithEnvelope( + sourceClaim, + sourceDigest, + net.firedevops.firemud.accountservice.repository + .AccountConnectTokenIssuanceOperation.Lifecycle.COMMITTED, + "SUCCESS", + "connect-jti-" + UUID.randomUUID(), + digest(66), + sourceBinding, + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE))); + } + return new Source( + sourceClaim.operation().operationId(), + new AccountBareLoginExchangeIdentity( + sourceClaim.operation().operationId(), + sourceClaim.operation().accountId(), + sourceClaim.operation().tenantId(), + connectScopeId, + "exchange-request-" + UUID.randomUUID())); + } + + private long insertAccount(DSLContext dsl) { + String unique = UUID.randomUUID().toString().replace("-", ""); + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "bare_login_" + unique.substring(0, 12), + unique + "@example.test", + "test-hash") + .fetchOne(0, Long.class); + if (accountId == null) { + throw new IllegalStateException("Bare LOGIN repository test account was not inserted"); + } + return accountId; + } + + private int insertBareOperationDirect( + TestContext context, + UUID operationId, + AccountBareLoginExchangeIdentity identity, + byte[] requestDigest) { + return insertBareOperationDirect( + context, + operationId, + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + identity.requestId(), + requestDigest); + } + + private int insertBareOperationDirect( + TestContext context, + UUID operationId, + UUID sourceOperationId, + long accountId, + long tenantId, + String connectScopeId, + String requestId, + byte[] requestDigest) { + return context + .dsl() + .execute( + "INSERT INTO account_bare_login_exchange_operations " + + "(operation_id, source_connect_operation_id, account_id, tenant_id, " + + "connect_scope_hash, request_id, request_digest_version, request_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, 1, ?, 'PENDING')", + operationId, + sourceOperationId, + accountId, + tenantId, + AccountJoinDigest.tokenHash(connectScopeId), + requestId, + requestDigest); + } + + private int deletePendingOperationDirect( + TestContext context, + UUID operationId, + AccountBareLoginExchangeIdentity identity, + byte[] requestDigest) { + insertBareOperationDirect(context, operationId, identity, requestDigest); + return context + .dsl() + .execute( + "DELETE FROM account_bare_login_exchange_operations WHERE operation_id = ?", + operationId); + } + + private AccountEnvelopeBinding binding( + UUID operationId, AccountBareLoginExchangeIdentity identity, byte[] requestDigest, int seed) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operationId.toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + identity.sourceConnectOperationId().toString(), + requestDigest, + digest(seed), + digest(seed + 1), + digest(seed + 2), + digest(seed + 3)); + } + + private AccountEncryptedEnvelope encryptedEnvelope(AccountEnvelopePurpose purpose) { + return new AccountEncryptedEnvelope( + AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, + "key_1", + purpose, + new byte[AccountEncryptedEnvelope.NONCE_LENGTH_BYTES], + new byte[AccountEncryptedEnvelope.AUTHENTICATION_TAG_LENGTH_BYTES]); + } + + private byte[] digest(int seed) { + byte[] value = new byte[32]; + for (int index = 0; index < value.length; index++) { + value[index] = (byte) (seed + index); + } + return value; + } + + private T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record ExchangeResult( + AccountBareLoginExchangeRepository.ClaimResult claim, + AccountEnvelopeBinding binding, + AccountBareLoginResponseEnvelope envelope) {} + + private record Source(UUID sourceOperationId, AccountBareLoginExchangeIdentity exchangeIdentity) { + private Source { + if (!sourceOperationId.equals(exchangeIdentity.sourceConnectOperationId())) { + throw new IllegalArgumentException("Source operation identity must be bound exactly"); + } + } + } + + private record TestContext( + DSLContext dsl, + AccountBareLoginExchangeRepository repository, + AccountConnectTokenIssuanceRepository sourceRepository, + TransactionTemplate transaction) {} +} From 9d53fc37d5b5603cd860f1d05dc4f287b689265b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 15:03:20 +1300 Subject: [PATCH 06/46] test(account): isolate membership version map rejection proof --- .../accountservice/AccountJoinPostgresIntegrationTest.java | 3 +++ 1 file changed, 3 insertions(+) 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 6dac9894c7..963af8063c 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 @@ -1677,6 +1677,9 @@ private void assertStoredMembershipVersionFailsClosed( payload.replace( exactMembershipVersionJson, "\"membershipVersion\":" + malformedMembershipVersionJson); assertThat(malformedPayload).isNotEqualTo(payload); + assertThatThrownBy(() -> MembershipAuthorityEventV1Codec.verify(malformedPayload)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("event.membershipVersion "); // V33 events are immutable; append a malformed newer event through the opaque storage boundary. String malformedRequestId = "malformed-version-" + UUID.randomUUID(); var malformedEvent = From a3f93197137068571399145722ed2f5bf2a24300 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 15:23:39 +1300 Subject: [PATCH 07/46] Fail closed bare first-party login and require Account database proof --- .github/workflows/ci.yml | 17 +- .../game-session-service/protocols.md | 2 + .../system-architecture-authentication.md | 1 + .../player-access-and-session.md | 2 + dev-tools/README.md | 2 +- .../tests/gradle-proof-tooling-contract.sh | 164 +++++++++++ dev-tools/validation/inspect-test-results.sh | 267 +++++++++++++++++- .../command/text/LoginCommandHandler.java | 49 +--- .../command/text/LoginCommandHandlerTest.java | 52 ++-- 9 files changed, 485 insertions(+), 71 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12ea985a33..5f5fda367f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -941,9 +941,24 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - ./gradlew :${{ matrix.module }}:check -PfullCheck + if [[ "${{ matrix.module }}" == "account-service" ]]; then + ./gradlew :${{ matrix.module }}:check -PfullCheck --no-build-cache + else + ./gradlew :${{ matrix.module }}:check -PfullCheck + fi echo "::endgroup::" + - name: 🔎 Verify Account PostgreSQL proof cases + if: ${{ matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ + account-service + - name: 📦 Build Runtime JAR if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) }} run: ./gradlew :${{ matrix.module }}:bootJar -PfullCheck diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index c2e970b5d8..492eda06b7 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -14,6 +14,8 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat 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 target 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 Account gRPC membership, grant, and entitlement reads used by Game Session fail with `FAILED_PRECONDITION` before data access, including for the Game Session workload. Accordingly, a valid-route text `PLAY` reaching runtime admission returns `AUTH_UNAVAILABLE` before membership, grant, or roster evaluation, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity is called; neither is currently an actionable JOIN, roster, or PLAY path. The status and target admission contract are canonical in [Authentication](../../system-architecture-authentication.md#implementation-status). The local JOIN operation does not alter the target `JOIN` -> `CHARS`/character creation -> `PLAY` sequence. +The #2881 candidate now fails an otherwise valid first-party bare `LOGIN` with retryable `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion because Game Session cannot yet obtain the required one-use Account delegation exchange. Existing invalid-context and mismatched-pointer checks retain their own denials; the unauthenticated bootstrap shell is not consumed merely by this unavailable result. Credential-bearing and email-code `LOGIN` keep their existing paths. This is containment, not proof that the current context verifier meets the complete target or that first-party login works end to end. + 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). The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback and performs account-scoped persisted Entity roster selection only after Account admission checks. That narrower roster is not yet namespace- and policy-qualified, and Account's current gRPC membership, grant, and entitlement reads fail with `FAILED_PRECONDITION` before data access even for the Game Session workload. Current text `PLAY` therefore fails closed with `AUTH_UNAVAILABLE` before Entity roster selection; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity is called. These statuses do not establish whether a membership, grant, or character exists. Fresh first-party `PLAY` no longer treats a connect-context token alone as retained-context replay authority, and focused post-`LOGOUT` replay suppression is present; it still requests a fresh `LOOK`. Durable logout episode/generation fencing, delayed-race proof, effective resume-window enforcement, and namespace-scoped controller takeover remain open. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index bb7a93fdb4..51afe6d4eb 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -22,6 +22,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - **Current gameplay authentication and transport boundary:** Current gameplay authentication supports `LOGIN ` / `LOGON ` to request a verified-email login code and `LOGIN ` / `LOGON ` for an immediate password-or-code attempt on raw Telnet and other non-WebSocket text clients. Bare raw-text `LOGIN`/`LOGON` prompt exchange is target-only and currently returns `PROMPT_LOGIN_UNSUPPORTED`. Control-plane clients use `/auth/login`. First-party gameplay uses `POST /auth/player-bootstrap` to establish the `player-bootstrap` identity, then uses `/auth/bootstrap/*` discovery/action routes and `/auth/connect-token` before the gameplay socket. Clients are stateless; current Account-owned legacy authentication session records persist `tokenHash` and session metadata under the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key, while gameplay bindings remain in Redis. These records never persist the raw delegation JWT; their runtime/data ownership is defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#session-and-token-model). Target issued-token registry issuance, storage, and consumer enforcement in Coordination Redis are unimplemented. The Game Session Service restores gameplay session state from Redis, while the Account Service validates the supplied login secret and issues the exact `control-ui`, `player-bootstrap`, or receiver-specific private player-delegation JWT profile required by the destination. Raw Telnet gameplay command streams never carry JWT authorization. Target browser and mobile-browser gameplay uses a `player-bootstrap` JWT for HTTPS bootstrap calls and a cookie-carried one-use connect token for the `/ws/game/**` handshake; target first-party native-mobile clients that use a cookie jar remain cookie-only. Public non-browser issuance and the dedicated handshake-header carrier are target-only and unavailable until a dedicated route is fully registered and its issuance, registry, profile, and carrier proof is complete; the target design uses protected secure storage plus `X-Firemud-Connect-Token`. First-party admin/creator UIs and backend services use their own permitted token profiles. Provider-specific HTTPS sign-in remains unavailable until the provider-specific verification, collision, recovery, and end-to-end proof required by [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md) is complete. - **Current first-party endpoint and runtime boundary:** The current first-party browser/mobile runtime includes dedicated `POST /auth/player-bootstrap` and `POST /auth/connect-token` surfaces, Gateway rejection for missing, expired, replayed, or scope-mismatched connect tokens, and Game Session validation of the signed connect context before bare `LOGIN`, but these remain partial implementation surfaces rather than proof of the complete target flow. Current `PLAY` resolves the admissible `gameInstanceId` from realm routing and binds the legacy `{tenantId, gameInstanceId, characterId}` identity; that per-instance binding is implementation drift. Target `PLAY` binds the controller identity `{tenantId, playableStateNamespaceId, characterId}`, carries server-derived `playableStateScope`, and retains `{gameInstanceId, sessionId, bindingGeneration}` as runtime/value evidence. Current behavior does not claim authoritative `regionId`, `regionEpoch`, lease-owner, or lease-fence resolution. Public non-browser issuance and the dedicated handshake-header carrier remain unavailable. +- **Current bare first-party `LOGIN` containment:** The #2881 candidate retains malformed-context and pointer-mismatch rejection, then returns retryable `AUTH_UNAVAILABLE` for an otherwise valid bare `LOGIN` before command enqueue or authenticated Game Session state is saved. The unauthenticated bootstrap shell remains available for a later explicit retry. Gateway context or a connect-token `jti` alone does not authenticate Account; the Account-owned one-use exchange, committed issuance, private delegation, and recovery proof remain unimplemented. Credential-bearing `LOGIN` is unchanged. - **Current realm-identity gap:** Current discovery, admission-pointer mutation/read models, gameplay-connect claims, and the Gateway signed context do not carry and prove durable `realmId` end to end; several runtime surfaces still key or resolve routes directly from `worldSlug`/`realmSlug`. The target resolves those selectors to `{tenantId, realmId}` before pointer lookup and carries `realmId` in the exact selected-target snapshot and signed context. - **Current provider-specific sign-in boundary:** Optional provider-specific HTTPS sign-in is permitted only after complete provider proof; password and verified-email code remain the Account-owned baseline and fallback, and Telnet never carries provider credentials. See [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md). - **Current raw-text challenge semantics:** The current raw-text email-code challenge is two commands: `LOGIN ` (or `LOGON `) requests an Account-owned, server-side verified-email challenge bound to the normalized account/email and its configured expiry without authenticating the session, then `LOGIN ` (or `LOGON `) submits that code. The separate immediate-auth form is `LOGIN ` (or `LOGON `) with one secret. Account selects the `EMAIL_OTP` validator first when the supplied secret matches the live challenge; otherwise it verifies `PASSWORD` when that account mode is enabled. The client does not select the validator, and a code is not valid outside its server-side challenge and expiry. 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 1bd3ecba71..3ea646dda6 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,6 +32,8 @@ The current Unit 1B draft's conditional Game Session `PLAY` branch now distingui The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases compile but skipped without Docker; database execution, caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. +The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. + The #2876 candidate also adds a local AES-256-GCM response-envelope primitive backed by one Account-only versioned mounted-file ring, with separate connect-token and bare-`LOGIN` purpose keys, key IDs, current-write/older-decrypt rotation, and length-framed exact-operation evidence. Local unit tests execute both-purpose round trips, old-key recovery/removal, wrong-purpose and wrong-operation rejection, and missing/malformed-ring denial. V35 adds an unwired connect-token issuance operation/envelope table with exact identity, digest, pending/terminal state and encrypted-envelope readback; its six PostgreSQL cases reached execution in a prior hosted run, four passed and two failed on a timestamp bind. The corrected-head Account integration task passed, but its success artifact lacks per-test XML. An operator bootstrap candidate creates a protected initial source record once in an owner-only directory and provides an explicit separate rotation action that retains every old purpose key, adds new distinct write keys, and binds a new generation to the previous one without overwriting either source. A separate materializer candidate consumes exact manifest bytes, environment, namespace, generation/predecessor, immutable source-created freshness anchor, and expiry; it verifies retry-stable Secret readback and preserves old decrypt-only keys. The 28 focused materializer tests and combined 139-test developer-tool suite, Ruff, and syntax checks pass locally. Exact-head CI run `36254410583` passed Account Build/Test; its integration task ran and its coverage artifact lists 20 integration classes, but the absent per-case XML prevents an exact executed/skipped count. The aggregate CI gate is red from unchanged Game Session Friends assertions, hosted smoke-tool lint, and an EA-3.1 proof-link check outside #2876's unique diff. Actual protected durable custody, source backup and writer RBAC, deployment/readiness wiring, a live mounted Secret, executed rotation, and proven safe decrypt-only key retirement are still absent. There is no corresponding bare-`LOGIN` operation, wired producer/consumer, or lost-response/live rollout proof. Neither credential path is enabled by the primitive, tool candidates, or V35, and an unavailable key may never authorize reminting. The separately specified credential-bearing `Authenticate` exact-retry envelope is also unimplemented; this two-purpose primitive does not supply its key or enable that operation. At published #2876 head `774356d5a66846a535726f680aa54ce85669160b`, manual CI run `36257232596` passed Account Build/Test, but `:account-service:integrationTest` was `FROM-CACHE`; it does not demonstrate fresh PostgreSQL execution. The gate failed on seven of 39 Game Session Friends/WebSocket cross-service cases, ten hosted smoke-tool Ruff errors, and the EA-3.1 executable-proof-link check. The failing paths are outside #2876's unique diff, but CI alone does not establish the Game Session root cause or merge readiness. The proposed required Account Secret mount remains unpublished: its rendered-manifest contract passes locally, but no environment source, trusted-writer receipt, or readiness proof exists, and deployment cannot safely require the absent Secret. A Game Session sequence-only event-consumer draft was discarded because the accepted contract requires authenticated same-snapshot tuple, fence, membership baseline, complete checkpoints, and source evidence; the current wire does not provide those fields. Runtime RPCs remain denied. diff --git a/dev-tools/README.md b/dev-tools/README.md index 2a4bee6ed9..965872c7ce 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -15,7 +15,7 @@ Keep the root of `dev-tools/` small. Only canonical human-facing entrypoints and - `build-local-smoke-images.sh` – builds the pinned local base and service images for a 40-character commit tag after rebuilding the service boot jars. - `verify-compose-health.sh` – shared health gate used by the smoke entrypoints. - `validation/run-locked-gradle.sh` – canonical local verification wrapper that prevents overlapping service-level Gradle runs from writing the same test-result trees at once. For example: `bash dev-tools/validation/run-locked-gradle.sh :account-service:test`. -- `validation/inspect-test-results.sh` – read-only JUnit XML summary helper for diagnosing quiet post-suite Gradle tails without guessing at process state. For example: `bash dev-tools/validation/inspect-test-results.sh account-service`. This is diagnostic evidence only and does not prove that the Gradle invocation completed cleanly. +- `validation/inspect-test-results.sh` – read-only JUnit XML helper for diagnosing quiet post-suite Gradle tails without guessing at process state. For example: `bash dev-tools/validation/inspect-test-results.sh account-service`. Its default mode is diagnostic only and does not prove that the Gradle invocation completed cleanly. CI may use `--strict` with repeated `--require-suite ` and `--require-case ` arguments to fail closed on missing, duplicate, malformed, empty, skipped, or failing JUnit proof; strict output contains only counts, requested names, and outcomes. - `pr-review` – the sole review controller. Use `dev-tools/pr-review stack set ...` and `stack show` for the repository review stack, `status [--pr ]` for fail-closed live state, `run hosted|cli [--expect-pr ]` for a complete checkpoint, `evidence []` for anchored evidence, and `decide ...` for explicit judgments. The complete review, status, checkpoint, and disposition policy is owned by [PR lifecycle: Review and Status](../design/developer-workflows/pr-lifecycle.md#review-and-status). The controller stores only stack configuration, exact policy overrides, explicit judgments (including summary-only finding dispositions), and reconciliation decisions in a locked private common-directory state file; live PR, CI, checkpoint, and review evidence is derived when requested. For hands-on acceptance, pass the paired global options `--acceptance-fixture ` and `--state-path `; these use synthetic fixture adapters in a dedicated private directory and never contact GitHub or consume review quota. The implementation and focused contracts live in `pr_review/` and `tests/pr-review-controller-contract.sh`. An acceptance fixture is a JSON object containing `repository`, `default_base_ref`, `default_base_tip`, `branch_heads`, `pull_requests`, `ancestors`, `merge_bases`, `patch_ids`, and optional `ordered_prs` and `evidence`. Pull requests provide exact `base_ref`, `base_tip`, `head`, and `head_repository` identities; `head_repository` must explicitly match the fixture's `repository`. They may also provide `head_ref`, state, mergeability, and merge flags; Git relationships and patch identities are explicit so missing or stale facts fail closed. Create a dedicated private directory with `review_acceptance_dir=$(mktemp -d)`, place the fixture there, then run `dev-tools/pr-review --acceptance-fixture "$review_acceptance_dir/fixture.json" --state-path "$review_acceptance_dir/state.json" status --json`. The state directory must already exist, be owned by the caller, and have mode `0700`; the canonical state directory is forbidden. diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 6f7b487f35..35b4ae8b3e 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -77,6 +77,170 @@ grep -q "Most recent XML on disk:" <<<"$inspection_output" grep -q "Failing XML files:" <<<"$inspection_output" grep -q "Diagnostic only:" <<<"$inspection_output" +JOIN_SUITE="net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest" +EXCHANGE_SUITE="integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest" +JOIN_CASE="$JOIN_SUITE#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()" +EXCHANGE_CASE="$EXCHANGE_SUITE#claimOnlyTransactionRollsBackPendingExchange()" + +inspect_strict() { + bash "$INSPECTOR" --root "$1" --strict \ + --require-suite "$JOIN_SUITE" \ + --require-suite "$EXCHANGE_SUITE" \ + --require-case "$JOIN_CASE" \ + --require-case "$EXCHANGE_CASE" \ + account-service +} + +new_strict_fixture() { + mkdir -p "$1/services/account-service/build/test-results/integrationTest" +} + +STRICT_GREEN_ROOT="$TMP_DIR/strict-green" +new_strict_fixture "$STRICT_GREEN_ROOT" +cat >"$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + + STRICT_OUTPUT_SENTINEL + +XML +cat >"$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" < + + +XML +strict_green_output="$(inspect_strict "$STRICT_GREEN_ROOT")" +grep -q '^Strict JUnit proof: passed$' <<<"$strict_green_output" +grep -Fq "Suite $JOIN_SUITE: tests=2 skipped=0 failures=0 errors=0 outcome=passed" <<<"$strict_green_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=passed" <<<"$strict_green_output" +grep -Fq "Case $EXCHANGE_CASE: executions=1 outcome=passed" <<<"$strict_green_output" +! grep -q "STRICT_OUTPUT_SENTINEL" <<<"$strict_green_output" + +STRICT_MISSING_SUITE_ROOT="$TMP_DIR/strict-missing-suite" +new_strict_fixture "$STRICT_MISSING_SUITE_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_MISSING_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +if missing_suite_output="$(inspect_strict "$STRICT_MISSING_SUITE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a missing suite." >&2 + exit 1 +fi +grep -Fq "Missing required suite: $EXCHANGE_SUITE" <<<"$missing_suite_output" + +STRICT_NO_REPORTS_ROOT="$TMP_DIR/strict-no-reports" +new_strict_fixture "$STRICT_NO_REPORTS_ROOT" +if no_reports_output="$(inspect_strict "$STRICT_NO_REPORTS_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted an empty report directory." >&2 + exit 1 +fi +grep -Fq "No JUnit XML reports were found." <<<"$no_reports_output" + +STRICT_MISSING_CASE_ROOT="$TMP_DIR/strict-missing-case" +new_strict_fixture "$STRICT_MISSING_CASE_ROOT" +cat >"$STRICT_MISSING_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_MISSING_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if missing_case_output="$(inspect_strict "$STRICT_MISSING_CASE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a missing case." >&2 + exit 1 +fi +grep -Fq "Missing required case: $JOIN_CASE" <<<"$missing_case_output" + +STRICT_ZERO_TESTS_ROOT="$TMP_DIR/strict-zero-tests" +new_strict_fixture "$STRICT_ZERO_TESTS_ROOT" +cat >"$STRICT_ZERO_TESTS_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_ZERO_TESTS_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if zero_tests_output="$(inspect_strict "$STRICT_ZERO_TESTS_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted an empty required suite." >&2 + exit 1 +fi +grep -Fq "Required suite has zero tests: $JOIN_SUITE" <<<"$zero_tests_output" + +STRICT_SKIPPED_ROOT="$TMP_DIR/strict-skipped" +new_strict_fixture "$STRICT_SKIPPED_ROOT" +cat >"$STRICT_SKIPPED_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_SKIPPED_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if skipped_output="$(inspect_strict "$STRICT_SKIPPED_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a skipped suite." >&2 + exit 1 +fi +grep -Fq "Required suite is failing, errored, or skipped: $JOIN_SUITE" <<<"$skipped_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=skipped" <<<"$skipped_output" + +STRICT_FAILING_ROOT="$TMP_DIR/strict-failing" +new_strict_fixture "$STRICT_FAILING_ROOT" +cat >"$STRICT_FAILING_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + SENSITIVE_FAILURE_SENTINEL + + SENSITIVE_STDOUT_SENTINEL + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_FAILING_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if failing_output="$(inspect_strict "$STRICT_FAILING_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a failing suite." >&2 + exit 1 +fi +grep -Fq "Required suite is failing, errored, or skipped: $JOIN_SUITE" <<<"$failing_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=failure" <<<"$failing_output" +! grep -q "SENSITIVE_" <<<"$failing_output" + +STRICT_DUPLICATE_SUITE_ROOT="$TMP_DIR/strict-duplicate-suite" +new_strict_fixture "$STRICT_DUPLICATE_SUITE_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join-copy.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if duplicate_suite_output="$(inspect_strict "$STRICT_DUPLICATE_SUITE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a duplicate suite report." >&2 + exit 1 +fi +grep -Fq "Duplicate required suite: $JOIN_SUITE (2 report(s))" <<<"$duplicate_suite_output" + +STRICT_DUPLICATE_CASE_ROOT="$TMP_DIR/strict-duplicate-case" +new_strict_fixture "$STRICT_DUPLICATE_CASE_ROOT" +cat >"$STRICT_DUPLICATE_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_DUPLICATE_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if duplicate_case_output="$(inspect_strict "$STRICT_DUPLICATE_CASE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted duplicate requested case execution." >&2 + exit 1 +fi +grep -Fq "Duplicate required case: $JOIN_CASE (2 execution(s))" <<<"$duplicate_case_output" + +STRICT_MALFORMED_ROOT="$TMP_DIR/strict-malformed" +new_strict_fixture "$STRICT_MALFORMED_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +printf '"$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-malformed.xml" +if malformed_output="$(inspect_strict "$STRICT_MALFORMED_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted malformed JUnit XML." >&2 + exit 1 +fi +grep -Fq "malformed reports: 1" <<<"$malformed_output" + bootstrap_validation_output="$( FIREMUD_SMOKE_COMPOSE_SERVICES=$'gateway\ngame-session-service\n' \ FIREMUD_SMOKE_NO_CACHE_SERVICES='gateway game-session-service' \ diff --git a/dev-tools/validation/inspect-test-results.sh b/dev-tools/validation/inspect-test-results.sh index 4cd95c4cce..94d11af3e3 100644 --- a/dev-tools/validation/inspect-test-results.sh +++ b/dev-tools/validation/inspect-test-results.sh @@ -5,15 +5,27 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" usage() { cat <<'EOF' >&2 -Usage: inspect-test-results.sh [--root ] +Usage: + inspect-test-results.sh [--root ] + inspect-test-results.sh --strict [--root ] \ + --require-suite ... \ + --require-case ... Summarize parsed JUnit XML currently on disk under services//build/test-results. This is diagnostic only; it helps explain quiet Gradle tails but does not prove the original Gradle invocation completed cleanly. + +Strict mode fails closed unless every named suite has exactly one non-empty, +green report and every named test case executed exactly once without a skip, +failure, or error. EOF exit 1 } +STRICT_MODE=0 +REQUIRED_SUITES=() +REQUIRED_CASES=() + while (($# > 0)); do case "$1" in --root) @@ -21,6 +33,20 @@ while (($# > 0)); do ROOT_DIR="$2" shift 2 ;; + --strict) + STRICT_MODE=1 + shift + ;; + --require-suite) + [[ $# -ge 2 ]] || usage + REQUIRED_SUITES+=("$2") + shift 2 + ;; + --require-case) + [[ $# -ge 2 ]] || usage + REQUIRED_CASES+=("$2") + shift 2 + ;; --help|-h) usage ;; @@ -32,6 +58,39 @@ done [[ $# -eq 1 ]] || usage +if [[ "$STRICT_MODE" == "1" ]]; then + ((${#REQUIRED_SUITES[@]} > 0 && ${#REQUIRED_CASES[@]} > 0)) || usage + + for ((i = 0; i < ${#REQUIRED_SUITES[@]}; i++)); do + suite_name="${REQUIRED_SUITES[$i]}" + [[ -n "$suite_name" && ! "$suite_name" =~ [[:cntrl:]] && "$suite_name" != *'#'* ]] || usage + for ((j = 0; j < i; j++)); do + [[ "$suite_name" != "${REQUIRED_SUITES[$j]}" ]] || usage + done + done + + for ((i = 0; i < ${#REQUIRED_CASES[@]}; i++)); do + case_name="${REQUIRED_CASES[$i]}" + [[ "$case_name" == *'#'* && "${case_name#*#}" != *'#'* && ! "$case_name" =~ [[:cntrl:]] ]] || usage + case_suite="${case_name%%#*}" + case_test="${case_name#*#}" + [[ -n "$case_test" ]] || usage + suite_is_required=0 + for required_suite in "${REQUIRED_SUITES[@]}"; do + if [[ "$case_suite" == "$required_suite" ]]; then + suite_is_required=1 + break + fi + done + [[ "$suite_is_required" == "1" ]] || usage + for ((j = 0; j < i; j++)); do + [[ "$case_name" != "${REQUIRED_CASES[$j]}" ]] || usage + done + done +elif ((${#REQUIRED_SUITES[@]} > 0 || ${#REQUIRED_CASES[@]} > 0)); then + usage +fi + SERVICE_NAME="$1" SERVICE_DIR="$ROOT_DIR/services/$SERVICE_NAME" @@ -40,7 +99,7 @@ if [[ ! -d "$SERVICE_DIR" ]]; then exit 1 fi -python3 - "$SERVICE_DIR" <<'PY' +python3 - "$SERVICE_DIR" "$STRICT_MODE" "${REQUIRED_SUITES[@]}" --required-cases "${REQUIRED_CASES[@]}" <<'PY' from __future__ import annotations import datetime as dt @@ -50,9 +109,213 @@ from collections import defaultdict from pathlib import Path service_dir = Path(sys.argv[1]) +strict_mode = sys.argv[2] == "1" +case_separator = sys.argv.index("--required-cases", 3) +required_suites = sys.argv[3:case_separator] +required_cases = sys.argv[case_separator + 1 :] service_name = service_dir.name result_root = service_dir / "build" / "test-results" + +def strict_inspection() -> None: + xml_files = sorted(result_root.glob("**/TEST-*.xml")) if result_root.exists() else [] + malformed_reports = 0 + parsed_suite_count = 0 + parsed_test_count = 0 + suite_reports: dict[str, list[dict[str, object]]] = defaultdict(list) + required_suite_set = set(required_suites) + + def non_negative_count(value: str | None) -> int | None: + if value is None or not value.isascii() or not value.isdecimal(): + return None + try: + count = int(value) + except ValueError: + return None + return count if count >= 0 else None + + for xml_file in xml_files: + try: + root = ET.parse(xml_file).getroot() + except (ET.ParseError, OSError, ValueError): + malformed_reports += 1 + continue + + if root.tag == "testsuite": + suites = [root] + elif root.tag == "testsuites": + suites = list(root.findall(".//testsuite")) + else: + malformed_reports += 1 + continue + + if not suites: + malformed_reports += 1 + continue + + file_is_malformed = False + file_suites: list[dict[str, object]] = [] + for suite in suites: + suite_name = suite.attrib.get("name") + tests = non_negative_count(suite.attrib.get("tests")) + failures = non_negative_count(suite.attrib.get("failures")) + errors = non_negative_count(suite.attrib.get("errors")) + skipped = non_negative_count(suite.attrib.get("skipped")) + disabled = non_negative_count(suite.attrib.get("disabled", "0")) + testcases = list(suite.findall("./testcase")) + + if ( + not suite_name + or tests is None + or failures is None + or errors is None + or skipped is None + or disabled is None + or tests != len(testcases) + ): + file_is_malformed = True + + parsed_cases: list[dict[str, object]] = [] + for testcase in testcases: + classname = testcase.attrib.get("classname") + name = testcase.attrib.get("name") + if not classname or not name: + file_is_malformed = True + continue + parsed_cases.append( + { + "identity": f"{classname}#{name}", + "failed": bool(testcase.findall("./failure")), + "errored": bool(testcase.findall("./error")), + "skipped": bool(testcase.findall("./skipped")), + } + ) + + suite_info: dict[str, object] = { + "name": suite_name, + "tests": tests, + "failures": failures, + "errors": errors, + "skipped": skipped, + "disabled": disabled, + "cases": parsed_cases, + } + file_suites.append(suite_info) + + if file_is_malformed: + malformed_reports += 1 + continue + + parsed_suite_count += len(file_suites) + parsed_test_count += sum(int(suite["tests"]) for suite in file_suites) + for suite in file_suites: + suite_name = str(suite["name"]) + if suite_name in required_suite_set: + suite_reports[suite_name].append(suite) + + problems: list[str] = [] + suite_status: dict[str, tuple[str, dict[str, object] | None]] = {} + for suite_name in required_suites: + matches = suite_reports.get(suite_name, []) + if not matches: + suite_status[suite_name] = ("missing", None) + problems.append(f"Missing required suite: {suite_name}") + continue + if len(matches) != 1: + suite_status[suite_name] = ("duplicate", None) + problems.append(f"Duplicate required suite: {suite_name} ({len(matches)} report(s))") + continue + + suite = matches[0] + suite_status[suite_name] = ("passed", suite) + if int(suite["tests"]) == 0: + suite_status[suite_name] = ("zero tests", suite) + problems.append(f"Required suite has zero tests: {suite_name}") + elif ( + int(suite["failures"]) > 0 + or int(suite["errors"]) > 0 + or int(suite["skipped"]) > 0 + or int(suite["disabled"]) > 0 + or any( + bool(case["failed"]) or bool(case["errored"]) or bool(case["skipped"]) + for case in suite["cases"] + ) + ): + suite_status[suite_name] = ("failed or skipped", suite) + problems.append(f"Required suite is failing, errored, or skipped: {suite_name}") + + for case_spec in required_cases: + case_suite, _ = case_spec.split("#", 1) + suite = suite_status[case_suite][1] + matching_cases = ( + [case for case in suite["cases"] if case["identity"] == case_spec] + if suite is not None + else [] + ) + if not matching_cases: + problems.append(f"Missing required case: {case_spec}") + continue + if len(matching_cases) != 1: + problems.append(f"Duplicate required case: {case_spec} ({len(matching_cases)} execution(s))") + continue + case = matching_cases[0] + if bool(case["failed"]) or bool(case["errored"]) or bool(case["skipped"]): + problems.append(f"Required case did not pass: {case_spec}") + + print("Strict JUnit proof: passed" if not problems and malformed_reports == 0 else "Strict JUnit proof: failed") + print( + f"Reports: {len(xml_files)}; suites: {parsed_suite_count}; tests: {parsed_test_count}; " + f"malformed reports: {malformed_reports}" + ) + + for suite_name in required_suites: + status, suite = suite_status[suite_name] + if suite is None: + print(f"Suite {suite_name}: outcome={status}") + else: + print( + f"Suite {suite_name}: tests={suite['tests']} skipped={int(suite['skipped']) + int(suite['disabled'])} " + f"failures={suite['failures']} errors={suite['errors']} outcome={status}" + ) + + for case_spec in required_cases: + case_suite, _ = case_spec.split("#", 1) + suite = suite_status[case_suite][1] + matching_cases = ( + [case for case in suite["cases"] if case["identity"] == case_spec] + if suite is not None + else [] + ) + if not matching_cases: + outcome = "missing" + elif len(matching_cases) != 1: + outcome = "duplicate" + elif bool(matching_cases[0]["failed"]): + outcome = "failure" + elif bool(matching_cases[0]["errored"]): + outcome = "error" + elif bool(matching_cases[0]["skipped"]): + outcome = "skipped" + else: + outcome = "passed" + print(f"Case {case_spec}: executions={len(matching_cases)} outcome={outcome}") + + if malformed_reports > 0: + problems.append(f"Malformed report(s): {malformed_reports}") + for problem in problems: + print(f"- {problem}") + + if not xml_files: + print("No JUnit XML reports were found.") + raise SystemExit(1) + if problems: + raise SystemExit(1) + + +if strict_mode: + strict_inspection() + raise SystemExit(0) + if not result_root.exists(): print(f"Service: {service_name}") print("No build/test-results directory exists yet.") diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 49ffa7c7b1..581eaf06e7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -16,7 +16,6 @@ import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.CommandService; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -39,6 +38,7 @@ public final class LoginCommandHandler { private static final Logger logger = LoggerFactory.getLogger(LoginCommandHandler.class); private static final String AUTHENTICATION_UNAVAILABLE_CODE = "UNAVAILABLE"; + private static final String AUTH_UNAVAILABLE_CODE = "AUTH_UNAVAILABLE"; private static final String RETRY_LATER_CODE = "RETRY_LATER"; private static final String ABUSE_CONTROL_UNAVAILABLE_CODE = "ABUSE_CONTROL_UNAVAILABLE"; private static final String RETRY_LATER_MESSAGE = "Too many failed attempts; try again later."; @@ -107,7 +107,7 @@ public LoginCommandHandlingResult handle( LoginCommandConstants.INVALID_ARGUMENTS_CODE, LoginCommandConstants.INVALID_ARGUMENTS_MESSAGE); } - return handleVerifiedFirstPartyLogin(sessionId, command, requiresSoloTick); + return handleVerifiedFirstPartyLogin(sessionId); } TextCommandPayload.Credentials credentials = maybeCredentials.orElseThrow(); String canonicalLoginName = EmailCanonicalization.normalize(credentials.loginName()); @@ -198,8 +198,7 @@ private LoginCommandHandlingResult handleEmailLoginChallenge( LoginCommandConstants.EMAIL_LOGIN_CODE_MESSAGE, "message.login.code-sent"))); } - private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( - String sessionId, TextCommand command, boolean requiresSoloTick) { + private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionId) { SessionIdParsing.ParsedSessionId parsedSessionId = parseSessionId(sessionId); if (!parsedSessionId.valid()) { return invalidSessionFailure(parsedSessionId.errorMessage()); @@ -264,26 +263,7 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( return failure("CONNECT_SCOPE_MISMATCH", "Connect scope invalid"); } - CommandEnqueueResult enqueueResult = - commandService.enqueue(sessionId, command.rawLine(), requiresSoloTick); - if (!enqueueResult.accepted()) { - return fromCommandResult(enqueueResult); - } - persistSessionContext( - numericSessionId, - verifiedContext.tenantId(), - verifiedContext.accountId(), - "first-party:" + verifiedContext.accountId(), - null, - verifiedContext.gameInstanceId(), - verifiedContext); - return new LoginCommandHandlingResult( - enqueueResult, - List.of( - PlayerOutput.message( - "Logged in as first-party account " + verifiedContext.accountId(), - "message.login.first-party-success", - Map.of("accountId", Long.toString(verifiedContext.accountId()))))); + return failure(AUTH_UNAVAILABLE_CODE, "Authentication service unavailable"); } private void persistSessionContext( @@ -293,18 +273,6 @@ private void persistSessionContext( String loginName, String jwt, long bootstrapGameInstanceId) { - persistSessionContext( - sessionId, tenantId, accountId, loginName, jwt, bootstrapGameInstanceId, null); - } - - private void persistSessionContext( - long sessionId, - long tenantId, - long accountId, - String loginName, - String jwt, - long bootstrapGameInstanceId, - FirstPartyConnectContext verifiedBootstrapContext) { if (sessionContextService == null) { return; } @@ -333,14 +301,6 @@ private void persistSessionContext( retainedPointerVersion = existing.pointerVersion(); retainedPlayableStateScope = existing.playableStateScope(); } - if (verifiedBootstrapContext != null) { - retainedBootstrapGameInstanceId = verifiedBootstrapContext.gameInstanceId(); - retainedWorldSlug = verifiedBootstrapContext.worldSlug(); - retainedRealmSlug = verifiedBootstrapContext.realmSlug(); - retainedPointerVersion = verifiedBootstrapContext.pointerVersion(); - retainedConnectScopeId = verifiedBootstrapContext.connectScopeId(); - retainedConnectRequestId = verifiedBootstrapContext.connectRequestId(); - } // LOGIN promotes an unauthenticated shell while keeping only its server-derived bootstrap // context. Reauthentication under a different account clears that context with old gameplay // identity; only a same-account login may preserve a candidate gameplay binding for PLAY. @@ -575,6 +535,7 @@ private String loginErrorMessageKey(String code) { case "ACCOUNT_LOCKED" -> "error.login.account-locked"; case RETRY_LATER_CODE -> "error.login.retry-later"; case ABUSE_CONTROL_UNAVAILABLE_CODE -> "error.login.abuse-control-unavailable"; + case AUTH_UNAVAILABLE_CODE -> "error.login.unavailable"; case AUTHENTICATION_UNAVAILABLE_CODE -> "error.login.unavailable"; default -> null; }; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index c70a727985..d312f6615b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -379,10 +379,10 @@ void missingCredentialsReturnsPromptError() { } @Test - void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { + void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); GameInstance instance = buildInstance(1L, 22L, 77L); - stubSessionContext( + SessionContext shell = new SessionContext( 1L, 22L, @@ -400,7 +400,8 @@ void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { 7L, "SHARED", "shell-scope", - "shell-request")); + "shell-request"); + stubSessionContext(shell); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( @@ -419,23 +420,26 @@ void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { LoginCommandHandlingResult result = handler.handle("1", command, false); - assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 99", joinedOutputText(result.outputs())); + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + assertEquals("Authentication service unavailable", result.commandResult().errorMessage()); + assertEquals( + "ERROR AUTH_UNAVAILABLE Authentication service unavailable", + joinedOutputText(result.outputs())); + assertEquals( + "error.login.unavailable", ((ErrorOutput) result.outputs().get(0).payload()).messageKey()); verify(accountClient, never()).authenticate(anyString(), anyString()); - verify(commandService).enqueue("1", "LOGIN", false); - ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService).save(captor.capture()); - SessionContext saved = captor.getValue(); - assertEquals(99L, saved.accountId()); - assertEquals(1L, saved.bootstrapGameInstanceId()); - assertEquals("demo", saved.worldSlug()); - assertEquals("production", saved.realmSlug()); - assertEquals(1L, saved.pointerVersion()); - assertEquals("SHARED", saved.playableStateScope()); - assertEquals("scope-1", saved.connectScopeId()); - assertEquals("req-1", saved.connectRequestId()); - assertEquals(0L, saved.characterId()); - assertEquals(0L, saved.gameInstanceId()); + verify(accountClient, never()).requestEmailLoginOtp(anyString()); + verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + assertEquals(0L, shell.accountId()); + assertNull(shell.jwt()); + assertEquals(1L, shell.bootstrapGameInstanceId()); + assertEquals("shell-world", shell.worldSlug()); + assertEquals("shell-realm", shell.realmSlug()); + assertEquals("shell-scope", shell.connectScopeId()); + assertEquals("shell-request", shell.connectRequestId()); assertEquals(77L, instance.getOwnerAccountId()); } @@ -490,7 +494,7 @@ void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { } @Test - void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() { + void bareLoginFailsUnavailableForPersistedFirstPartyContextFallback() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); GameInstance instance = buildInstance(1L, 22L, 77L); SessionContext persisted = @@ -519,9 +523,11 @@ void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() LoginCommandHandlingResult result = handler.handle("1", command, false); - assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 77", joinedOutputText(result.outputs())); - verify(commandService).enqueue("1", "LOGIN", false); + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + verify(accountClient, never()).authenticate(anyString(), anyString()); + verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); + verify(sessionContextService, never()).save(any(SessionContext.class)); } @Test From 25626210ca95a3b81d1116aab271608160c8a053 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 15:36:39 +1300 Subject: [PATCH 08/46] Make strict JUnit contract leak assertions ShellCheck-safe --- dev-tools/tests/gradle-proof-tooling-contract.sh | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 35b4ae8b3e..040134df7b 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -114,7 +114,10 @@ grep -q '^Strict JUnit proof: passed$' <<<"$strict_green_output" grep -Fq "Suite $JOIN_SUITE: tests=2 skipped=0 failures=0 errors=0 outcome=passed" <<<"$strict_green_output" grep -Fq "Case $JOIN_CASE: executions=1 outcome=passed" <<<"$strict_green_output" grep -Fq "Case $EXCHANGE_CASE: executions=1 outcome=passed" <<<"$strict_green_output" -! grep -q "STRICT_OUTPUT_SENTINEL" <<<"$strict_green_output" +if grep -q "STRICT_OUTPUT_SENTINEL" <<<"$strict_green_output"; then + echo "Strict inspection leaked test output." >&2 + exit 1 +fi STRICT_MISSING_SUITE_ROOT="$TMP_DIR/strict-missing-suite" new_strict_fixture "$STRICT_MISSING_SUITE_ROOT" @@ -196,7 +199,10 @@ if failing_output="$(inspect_strict "$STRICT_FAILING_ROOT" 2>&1)"; then fi grep -Fq "Required suite is failing, errored, or skipped: $JOIN_SUITE" <<<"$failing_output" grep -Fq "Case $JOIN_CASE: executions=1 outcome=failure" <<<"$failing_output" -! grep -q "SENSITIVE_" <<<"$failing_output" +if grep -q "SENSITIVE_" <<<"$failing_output"; then + echo "Strict inspection leaked failure details." >&2 + exit 1 +fi STRICT_DUPLICATE_SUITE_ROOT="$TMP_DIR/strict-duplicate-suite" new_strict_fixture "$STRICT_DUPLICATE_SUITE_ROOT" From e21a9290f7ef0051947531e174f36f7e8a8ec2b7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 16:26:27 +1300 Subject: [PATCH 09/46] Stage exact Account membership carrier while runtime read stays denied --- protos/account/v1/account_service.proto | 77 ++++- .../dto/RuntimeMembershipSnapshotDto.java | 91 +++++ ...countMembershipAuthorityEventProducer.java | 59 ++++ .../service/impl/AccountGrpcService.java | 283 ++++++++++++++++ .../service/impl/AccountGrpcServiceTest.java | 186 +++++++++- .../test/AccountRuntimeStubServerTest.java | 8 +- .../test/AccountRuntimeStubServer.java | 116 ++++++- .../gamesession/client/AccountClient.java | 6 +- .../command/text/PlayCommandHandler.java | 194 ++++++++++- ...essionWebSocketHandlerIntegrationTest.java | 29 +- .../gamesession/client/AccountClientTest.java | 49 ++- .../command/text/PlayCommandHandlerTest.java | 317 +++++++++--------- .../text/SessionResumptionFlowTest.java | 40 +-- .../text/TextCommandInterpreterTest.java | 20 +- .../RuntimeMembershipTestFixtures.java | 146 ++++++++ 15 files changed, 1353 insertions(+), 268 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java create mode 100644 services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 3ade2a26c0..0cf30dd22e 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -137,21 +137,88 @@ message VerifyEmailLoginOtpRequest { } message GetTenantMembershipForRuntimeRequest { - string account_id = 1; - string tenant_id = 2; - string request_id = 3; + reserved 1, 2, 3; + reserved "account_id", "tenant_id", "request_id"; + shared.v1.PlayerExecutionContext player_context = 4; } message GetTenantMembershipForRuntimeResponse { string account_id = 1; string tenant_id = 2; bool gameplay_admission_allowed = 3; - uint64 membership_version = 4; + map membership_version = 4; string evaluated_at = 5; shared.v1.ErrorDetail error = 6; bool membership_exists = 7; string membership_lifecycle_state = 8; - uint64 membership_authority_generation = 9; + string membership_authority_generation = 9; + RuntimeAuthorityTuple authority_tuple = 11; + string issuance_fence = 12; + repeated RuntimeOutboxCheckpoint outbox_checkpoints = 13; + repeated RuntimeOutboxSourceEvidence outbox_source_evidence = 14; + repeated string roles = 15; + RuntimeMembershipBaseline membership_baseline = 17; + string request_account_id = 18; + string request_tenant_id = 19; + string request_id = 20; +} + +message RuntimeMembershipBaseline { + string membership_lifecycle_state = 1; + map membership_version = 2; + string membership_authority_generation = 3; +} + +message RuntimeAuthorityTuple { + string issuer_auth_generation = 1; + string account_authority_generation = 2; + map tenant_authority_generation = 3; + map membership_authority_generation = 4; + repeated RuntimePrivateRealmGrantVersion private_realm_grant_versions = 5; + RuntimeAccountSecurityCutoff account_security_cutoff = 6; + RuntimeTenantBillingCutoffMap tenant_billing_cutoff = 7; +} + +message RuntimePrivateRealmGrantVersion { + string tenant_id = 1; + string world_slug = 2; + string realm_slug = 3; + string playtest_lifecycle_id = 4; + string grant_version = 5; +} + +message RuntimeAccountSecurityCutoff { + string account_authority_generation = 1; + string outbox_stream_key = 2; + string outbox_sequence = 3; +} + +message RuntimeTenantBillingCutoffMap { + repeated RuntimeTenantBillingCutoffEntry entries = 1; +} + +message RuntimeTenantBillingCutoffEntry { + string tenant_id = 1; + RuntimeTenantBillingCutoff cutoff = 2; +} + +message RuntimeTenantBillingCutoff { + string tenant_authority_generation = 1; + string tenant_billing_sequence = 2; + string outbox_stream_key = 3; + string outbox_sequence = 4; +} + +message RuntimeOutboxCheckpoint { + string outbox_stream_key = 1; + string outbox_sequence = 2; +} + +message RuntimeOutboxSourceEvidence { + string outbox_stream_key = 1; + string outbox_sequence = 2; + string event_id = 3; + string event_digest = 4; } message GetRealmAccessGrantForRuntimeRequest { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java new file mode 100644 index 0000000000..de0c59b0b7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; + +/** Same-fence Account snapshot candidate for the denied runtime membership RPC. */ +public record RuntimeMembershipSnapshotDto( + Long requestAccountId, + Long requestTenantId, + String accountUuid, + String tenantUuid, + boolean membershipExists, + boolean gameplayAdmissionAllowed, + MembershipBaseline membershipBaseline, + List roles, + AuthorityTuple authorityTuple, + String issuanceFence, + Instant evaluatedAt, + List outboxCheckpoints, + List outboxSourceEvidence) { + public RuntimeMembershipSnapshotDto { + if (requestAccountId == null + || requestAccountId <= 0L + || requestTenantId == null + || requestTenantId <= 0L) { + throw new IllegalArgumentException( + "Runtime membership account and tenant IDs must be positive"); + } + accountUuid = requireCanonicalUuid(accountUuid, "Account UUID"); + tenantUuid = requireCanonicalUuid(tenantUuid, "tenant UUID"); + Objects.requireNonNull(membershipBaseline, "unchanged membership baseline is required"); + roles = List.copyOf(roles); + Objects.requireNonNull(authorityTuple, "complete membership authority tuple is required"); + Objects.requireNonNull(issuanceFence, "Account issuance fence is required"); + Objects.requireNonNull(evaluatedAt, "membership evaluation time is required"); + outboxCheckpoints = List.copyOf(outboxCheckpoints); + outboxSourceEvidence = List.copyOf(outboxSourceEvidence); + String version = membershipBaseline.membershipVersion().get(tenantUuid); + if (membershipBaseline.membershipVersion().size() != 1 + || version == null + || !membershipBaseline + .membershipAuthorityGeneration() + .equals(authorityTuple.membershipAuthorityGeneration().get(tenantUuid))) { + throw new IllegalArgumentException( + "Runtime membership baseline differs from its tenant tuple"); + } + if (membershipExists != "ACTIVE".equals(membershipBaseline.membershipLifecycleState()) + || gameplayAdmissionAllowed != membershipExists + || membershipExists != roles.contains("player")) { + throw new IllegalArgumentException("Runtime membership state is not a supported snapshot"); + } + } + + private static String requireCanonicalUuid(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + try { + if (!java.util.UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID"); + } + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID", exception); + } + return value; + } + + public record MembershipBaseline( + String membershipLifecycleState, + Map membershipVersion, + String membershipAuthorityGeneration) { + public MembershipBaseline { + Objects.requireNonNull(membershipLifecycleState, "membership lifecycle state is required"); + membershipVersion = Map.copyOf(membershipVersion); + Objects.requireNonNull( + membershipAuthorityGeneration, "membership authority generation is required"); + if (membershipVersion.size() != 1 + || membershipVersion.values().stream().anyMatch(value -> !value.matches("[1-9][0-9]*")) + || !membershipAuthorityGeneration.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Runtime membership baseline is not canonical"); + } + if (!"ACTIVE".equals(membershipLifecycleState) + && !"MISSING".equals(membershipLifecycleState)) { + throw new IllegalArgumentException("Runtime membership baseline lifecycle is unsupported"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 7f51db151c..a213739e3c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -14,6 +14,7 @@ import java.util.UUID; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -301,6 +302,64 @@ public PositiveMembershipSnapshot readCurrentPairBoundPositiveMembershipSnapshot return positive; } + /** + * Reads one same-fence runtime membership result from the proved active-positive or never-joined + * sequence-zero path. + * + *

This deliberately has no inactive, unpaired, or synthesized fallback. The caller owns the + * Account transaction and the RPC remains unavailable until its consumer validates this whole + * evidence bundle. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( + long accountId, long legacyTenantId) { + if (accountId <= 0L || legacyTenantId <= 0L) { + throw new IllegalArgumentException("Account and retained tenant identities must be positive"); + } + joinOperationRepository.lockAccount(accountId); + if (membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId).isPresent()) { + PositiveMembershipSnapshot positive = + readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId); + return new RuntimeMembershipSnapshotDto( + accountId, + legacyTenantId, + positive.accountId(), + positive.tenantId(), + positive.membershipExists(), + positive.gameplayAdmissionAllowed(), + new RuntimeMembershipSnapshotDto.MembershipBaseline( + positive.membershipLifecycleState(), + positive.membershipVersion(), + positive.membershipAuthorityGeneration()), + positive.roles(), + positive.authorityTuple(), + positive.issuanceFence(), + positive.evaluatedAt(), + positive.outboxCheckpoints(), + positive.outboxSourceEvidence()); + } + + NeverJoinedMembershipSnapshot absent = + readNeverJoinedMembershipSnapshot(accountId, legacyTenantId); + return new RuntimeMembershipSnapshotDto( + accountId, + legacyTenantId, + absent.accountId(), + absent.tenantId(), + absent.membershipExists(), + absent.gameplayAdmissionAllowed(), + new RuntimeMembershipSnapshotDto.MembershipBaseline( + absent.membershipLifecycleState(), + absent.membershipVersion(), + absent.membershipAuthorityGeneration()), + absent.roles(), + absent.authorityTuple(), + absent.issuanceFence(), + absent.evaluatedAt(), + absent.outboxCheckpoints(), + absent.outboxSourceEvidence()); + } + /** * Reads an explicit sequence-zero checkpoint only from a durable verified pair baseline, after * the no-membership and no-committed-history proof under one Account-row fence. It never admits 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..9e81c7d754 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,11 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -33,6 +38,15 @@ import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; +import net.firedevops.firemud.account.v1.RuntimeAccountSecurityCutoff; +import net.firedevops.firemud.account.v1.RuntimeAuthorityTuple; +import net.firedevops.firemud.account.v1.RuntimeMembershipBaseline; +import net.firedevops.firemud.account.v1.RuntimeOutboxCheckpoint; +import net.firedevops.firemud.account.v1.RuntimeOutboxSourceEvidence; +import net.firedevops.firemud.account.v1.RuntimePrivateRealmGrantVersion; +import net.firedevops.firemud.account.v1.RuntimeTenantBillingCutoff; +import net.firedevops.firemud.account.v1.RuntimeTenantBillingCutoffEntry; +import net.firedevops.firemud.account.v1.RuntimeTenantBillingCutoffMap; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; @@ -41,11 +55,17 @@ 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.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto.MembershipBaseline; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; 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.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; @@ -432,6 +452,269 @@ public void getTenantMembershipForRuntime( responseObserver.onCompleted(); } + /** Encodes the held-back typed producer candidate; the RPC handler above intentionally denies. */ + static GetTenantMembershipForRuntimeResponse encodeRuntimeMembershipCandidate( + net.firedevops.firemud.shared.v1.PlayerExecutionContext playerContext, + RuntimeMembershipSnapshotDto snapshot) { + requireCompleteRuntimePlayerContext(playerContext); + long requestAccountId = parseCanonicalPositiveId(playerContext.getAccountId(), "account ID"); + long requestTenantId = parseCanonicalPositiveId(playerContext.getTenantId(), "tenant ID"); + if (requestAccountId != snapshot.requestAccountId() + || requestTenantId != snapshot.requestTenantId()) { + throw new IllegalArgumentException( + "Runtime membership producer result differs from its caller target"); + } + requireRuntimeMembershipEvidence(snapshot); + + MembershipBaseline baseline = snapshot.membershipBaseline(); + GetTenantMembershipForRuntimeResponse.Builder response = + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(snapshot.accountUuid()) + .setTenantId(snapshot.tenantUuid()) + .setRequestAccountId(playerContext.getAccountId()) + .setRequestTenantId(playerContext.getTenantId()) + .setRequestId(playerContext.getRequestId()) + .setGameplayAdmissionAllowed(snapshot.gameplayAdmissionAllowed()) + .setMembershipExists(snapshot.membershipExists()) + .setMembershipLifecycleState(baseline.membershipLifecycleState()) + .putAllMembershipVersion(baseline.membershipVersion()) + .setMembershipAuthorityGeneration(baseline.membershipAuthorityGeneration()) + .setMembershipBaseline( + RuntimeMembershipBaseline.newBuilder() + .setMembershipLifecycleState(baseline.membershipLifecycleState()) + .putAllMembershipVersion(baseline.membershipVersion()) + .setMembershipAuthorityGeneration(baseline.membershipAuthorityGeneration())) + .setAuthorityTuple(toRuntimeAuthorityTuple(snapshot.authorityTuple())) + .setIssuanceFence(snapshot.issuanceFence()) + .setEvaluatedAt(snapshot.evaluatedAt().toString()) + .addAllRoles(snapshot.roles()); + for (OutboxCheckpointEntry checkpoint : snapshot.outboxCheckpoints()) { + response.addOutboxCheckpoints( + RuntimeOutboxCheckpoint.newBuilder() + .setOutboxStreamKey(checkpoint.outboxStreamKey()) + .setOutboxSequence(checkpoint.outboxSequence())); + } + for (OutboxSourceEvidence evidence : snapshot.outboxSourceEvidence()) { + response.addOutboxSourceEvidence( + RuntimeOutboxSourceEvidence.newBuilder() + .setOutboxStreamKey(evidence.outboxStreamKey()) + .setOutboxSequence(evidence.outboxSequence()) + .setEventId(evidence.eventId()) + .setEventDigest(evidence.eventDigest())); + } + return response.build(); + } + + private static void requireCompleteRuntimePlayerContext( + net.firedevops.firemud.shared.v1.PlayerExecutionContext playerContext) { + if (playerContext == null + || !hasText(playerContext.getAccountId()) + || !hasText(playerContext.getTenantId()) + || !hasText(playerContext.getRealmId()) + || !hasText(playerContext.getPlayableStateNamespaceId()) + || !hasText(playerContext.getPlayableStateScope()) + || !hasText(playerContext.getGameInstanceId()) + || !hasText(playerContext.getSessionId()) + || !hasText(playerContext.getRequestId())) { + throw new IllegalArgumentException( + "Runtime membership caller and target context is incomplete"); + } + requireCanonicalUuid(playerContext.getRealmId(), "realm ID"); + if (!"SHARED".equals(playerContext.getPlayableStateScope()) + && !"ISOLATED".equals(playerContext.getPlayableStateScope())) { + throw new IllegalArgumentException("Runtime membership target scope is invalid"); + } + parseCanonicalPositiveId(playerContext.getAccountId(), "account ID"); + parseCanonicalPositiveId(playerContext.getTenantId(), "tenant ID"); + parseCanonicalPositiveId(playerContext.getGameInstanceId(), "game instance ID"); + parseCanonicalPositiveId(playerContext.getSessionId(), "session ID"); + } + + private static void requireRuntimeMembershipEvidence(RuntimeMembershipSnapshotDto snapshot) { + String tenantUuid = snapshot.tenantUuid(); + Map version = snapshot.membershipBaseline().membershipVersion(); + AuthorityTuple tuple = snapshot.authorityTuple(); + if (version.size() != 1 + || !version.containsKey(tenantUuid) + || !tuple.tenantAuthorityGeneration().keySet().equals(java.util.Set.of(tenantUuid)) + || !tuple.membershipAuthorityGeneration().keySet().equals(java.util.Set.of(tenantUuid)) + || !snapshot + .membershipBaseline() + .membershipAuthorityGeneration() + .equals(tuple.membershipAuthorityGeneration().get(tenantUuid)) + || !snapshot.issuanceFence().matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Runtime membership authority evidence is incomplete"); + } + ArrayList ordered = new ArrayList<>(snapshot.outboxCheckpoints()); + ordered.sort( + Comparator.comparing( + OutboxCheckpointEntry::outboxStreamKey, AccountGrpcService::compareUnsignedUtf8)); + if (!ordered.equals(snapshot.outboxCheckpoints()) || ordered.size() != 4) { + throw new IllegalArgumentException( + "Runtime membership checkpoints are not complete and ordered"); + } + + String membershipStreamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + snapshot.accountUuid() + + "/" + + tenantUuid; + String accountStreamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + snapshot.accountUuid(); + String issuerStreamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "issuer/" + + AccountServiceImpl.ACCOUNT_JWT_ISSUER; + String tenantStreamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid; + List expectedZeroCheckpoints = + orderedCheckpoints( + List.of( + new OutboxCheckpointEntry(accountStreamKey, "0"), + new OutboxCheckpointEntry(issuerStreamKey, "0"), + new OutboxCheckpointEntry(membershipStreamKey, "0"), + new OutboxCheckpointEntry(tenantStreamKey, "0"))); + if (!snapshot.membershipExists()) { + if (!"MISSING".equals(snapshot.membershipBaseline().membershipLifecycleState()) + || snapshot.gameplayAdmissionAllowed() + || !snapshot.roles().isEmpty() + || !snapshot.outboxCheckpoints().equals(expectedZeroCheckpoints) + || !snapshot.outboxSourceEvidence().isEmpty()) { + throw new IllegalArgumentException("Sequence-zero membership snapshot is not nonadmitting"); + } + return; + } + + List expectedPositiveCheckpoints = + orderedCheckpoints( + List.of( + new OutboxCheckpointEntry(accountStreamKey, "0"), + new OutboxCheckpointEntry(issuerStreamKey, "0"), + new OutboxCheckpointEntry( + membershipStreamKey, + snapshot.outboxCheckpoints().stream() + .filter(item -> item.outboxStreamKey().equals(membershipStreamKey)) + .map(OutboxCheckpointEntry::outboxSequence) + .findFirst() + .orElse("0")), + new OutboxCheckpointEntry(tenantStreamKey, "0"))); + if (!"ACTIVE".equals(snapshot.membershipBaseline().membershipLifecycleState()) + || !snapshot.gameplayAdmissionAllowed() + || !snapshot.roles().contains("player") + || !snapshot.outboxCheckpoints().equals(expectedPositiveCheckpoints) + || snapshot.outboxSourceEvidence().size() != 1) { + throw new IllegalArgumentException("Positive runtime membership snapshot is incomplete"); + } + OutboxSourceEvidence source = snapshot.outboxSourceEvidence().getFirst(); + OutboxCheckpointEntry membershipCheckpoint = + expectedPositiveCheckpoints.stream() + .filter(item -> item.outboxStreamKey().equals(membershipStreamKey)) + .findFirst() + .orElseThrow(); + if (!membershipStreamKey.equals(source.outboxStreamKey()) + || !membershipCheckpoint.outboxSequence().equals(source.outboxSequence()) + || !source.eventId().matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + || !source.eventDigest().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "Runtime membership event source differs from its checkpoint"); + } + } + + private static RuntimeAuthorityTuple toRuntimeAuthorityTuple(AuthorityTuple tuple) { + RuntimeAuthorityTuple.Builder result = + RuntimeAuthorityTuple.newBuilder() + .setIssuerAuthGeneration(tuple.issuerAuthGeneration()) + .setAccountAuthorityGeneration(tuple.accountAuthorityGeneration()) + .putAllTenantAuthorityGeneration(tuple.tenantAuthorityGeneration()) + .putAllMembershipAuthorityGeneration(tuple.membershipAuthorityGeneration()); + tuple.privateRealmGrantVersions().stream() + .map( + grant -> + RuntimePrivateRealmGrantVersion.newBuilder() + .setTenantId(grant.tenantId()) + .setWorldSlug(grant.worldSlug()) + .setRealmSlug(grant.realmSlug()) + .setPlaytestLifecycleId(grant.playtestLifecycleId()) + .setGrantVersion(grant.grantVersion())) + .forEach(result::addPrivateRealmGrantVersions); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> + result.setAccountSecurityCutoff( + RuntimeAccountSecurityCutoff.newBuilder() + .setAccountAuthorityGeneration(cutoff.accountAuthorityGeneration()) + .setOutboxStreamKey(cutoff.outboxStreamKey()) + .setOutboxSequence(cutoff.outboxSequence()))); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + RuntimeTenantBillingCutoffMap.Builder billing = + RuntimeTenantBillingCutoffMap.newBuilder(); + new TreeMap<>(cutoffs) + .forEach( + (tenantId, cutoff) -> + billing.addEntries( + RuntimeTenantBillingCutoffEntry.newBuilder() + .setTenantId(tenantId) + .setCutoff( + RuntimeTenantBillingCutoff.newBuilder() + .setTenantAuthorityGeneration( + cutoff.tenantAuthorityGeneration()) + .setTenantBillingSequence(cutoff.tenantBillingSequence()) + .setOutboxStreamKey(cutoff.outboxStreamKey()) + .setOutboxSequence(cutoff.outboxSequence())))); + result.setTenantBillingCutoff(billing); + }); + return result.build(); + } + + private static List orderedCheckpoints( + List checkpoints) { + return checkpoints.stream() + .sorted( + Comparator.comparing( + OutboxCheckpointEntry::outboxStreamKey, AccountGrpcService::compareUnsignedUtf8)) + .toList(); + } + + private static int compareUnsignedUtf8(String first, String second) { + byte[] left = first.getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] right = second.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int length = Math.min(left.length, right.length); + for (int index = 0; index < length; index++) { + int comparison = + Integer.compare(Byte.toUnsignedInt(left[index]), Byte.toUnsignedInt(right[index])); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(left.length, right.length); + } + + private static long parseCanonicalPositiveId(String value, String field) { + if (!hasText(value) || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Runtime membership " + field + " is invalid"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("Runtime membership " + field + " is invalid", exception); + } + } + + private static void requireCanonicalUuid(String value, String field) { + if (!hasText(value) || !UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException("Runtime membership " + field + " is invalid"); + } + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + @Override @Timed(value = "accountGrpc.getRealmAccessGrantForRuntime") public void getRealmAccessGrantForRuntime( 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..388b6dcab8 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 @@ -3,10 +3,12 @@ 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.Context; import io.grpc.stub.StreamObserver; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; @@ -49,11 +51,16 @@ 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.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto.MembershipBaseline; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; 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.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; @@ -67,6 +74,8 @@ 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 String ACCOUNT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72001"; + private static final String TENANT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72002"; private static final GrpcPeerIdentity GAME_SESSION_PEER = new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/game-session-service", @@ -91,6 +100,69 @@ private static PlayerExecutionContext validPlayerContext() { .build(); } + private static PlayerExecutionContext validRuntimeMembershipContext() { + return PlayerExecutionContext.newBuilder() + .setAccountId("10") + .setTenantId("20") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateScope("SHARED") + .setGameInstanceId("40") + .setSessionId("50") + .setRequestId("membership-read-1") + .build(); + } + + private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( + long requestAccountId, + boolean membershipExists, + List checkpoints, + List sourceEvidence) { + return new RuntimeMembershipSnapshotDto( + requestAccountId, + 20L, + ACCOUNT_UUID, + TENANT_UUID, + membershipExists, + membershipExists, + new MembershipBaseline( + membershipExists ? "ACTIVE" : "MISSING", + Map.of(TENANT_UUID, membershipExists ? "2" : "1"), + "1"), + membershipExists ? List.of("player") : List.of(), + new AuthorityTuple( + "1", + "1", + Map.of(TENANT_UUID, "1"), + Map.of(TENANT_UUID, "1"), + List.of(), + java.util.Optional.empty(), + java.util.Optional.empty()), + "7", + Instant.parse("2026-09-27T00:00:00Z"), + checkpoints, + sourceEvidence); + } + + private static List runtimeMembershipCheckpoints(String sequence) { + return List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + ACCOUNT_UUID, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID, sequence), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + TENANT_UUID, "0")); + } + + private static List runtimeMembershipSourceEvidence() { + return List.of( + new OutboxSourceEvidence( + "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID, + "1", + "04ef66b4-c0ad-3d5b-b3b2-0e8510e72003", + "sha256:" + "a".repeat(64))); + } + private static IssueDirectTextConnectScopeRequest validScopeRequest() { return IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(validPlayerContext()) @@ -973,9 +1045,7 @@ void getTenantMembershipForRuntimeRejectsMissingPeerBeforeLookup() { () -> service.getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") + .setPlayerContext(validPlayerContext()) .build(), observer)); @@ -998,9 +1068,7 @@ void getTenantMembershipForRuntimeFailsClosedWithExactPeerBecauseCallerContextIs () -> service.getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") + .setPlayerContext(validPlayerContext()) .build(), observer)); @@ -1023,9 +1091,7 @@ void getTenantMembershipForRuntimeRejectsWrongPeerBeforeLookup() { () -> service.getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("0") - .setRequestId("req-1") + .setPlayerContext(validPlayerContext()) .build(), observer)); @@ -1043,14 +1109,14 @@ void getTenantMembershipForRuntimeFailsClosedForCrossAccountOrTenantIds() { List crossTargetRequests = List.of( GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("3") - .setTenantId("1") - .setRequestId("cross-account") + .setPlayerContext( + validPlayerContext().toBuilder() + .setAccountId("3") + .setRequestId("cross-account")) .build(), GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("9") - .setRequestId("cross-tenant") + .setPlayerContext( + validPlayerContext().toBuilder().setTenantId("9").setRequestId("cross-tenant")) .build()); for (GetTenantMembershipForRuntimeRequest request : crossTargetRequests) { @@ -1670,6 +1736,96 @@ public void onCompleted() {} assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); } + @Test + void encodeRuntimeMembershipCandidateEncodesCompleteActivePositiveSnapshot() { + RuntimeMembershipSnapshotDto snapshot = + runtimeMembershipSnapshot( + 10L, true, runtimeMembershipCheckpoints("1"), runtimeMembershipSourceEvidence()); + + GetTenantMembershipForRuntimeResponse response = + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(), snapshot); + + assertEquals(ACCOUNT_UUID, response.getAccountId()); + assertEquals(TENANT_UUID, response.getTenantId()); + assertEquals("10", response.getRequestAccountId()); + assertEquals("20", response.getRequestTenantId()); + assertEquals("membership-read-1", response.getRequestId()); + assertTrue(response.getMembershipExists()); + assertTrue(response.getGameplayAdmissionAllowed()); + assertEquals("ACTIVE", response.getMembershipLifecycleState()); + assertEquals(Map.of(TENANT_UUID, "2"), response.getMembershipVersionMap()); + assertEquals("1", response.getMembershipAuthorityGeneration()); + assertEquals("7", response.getIssuanceFence()); + assertEquals(4, response.getOutboxCheckpointsCount()); + assertEquals("1", response.getOutboxCheckpoints(2).getOutboxSequence()); + assertEquals(1, response.getOutboxSourceEvidenceCount()); + assertEquals( + "04ef66b4-c0ad-3d5b-b3b2-0e8510e72003", response.getOutboxSourceEvidence(0).getEventId()); + assertEquals("sha256:" + "a".repeat(64), response.getOutboxSourceEvidence(0).getEventDigest()); + } + + @Test + void encodeRuntimeMembershipCandidateEncodesNeverJoinedSequenceZeroSnapshot() { + RuntimeMembershipSnapshotDto snapshot = + runtimeMembershipSnapshot(10L, false, runtimeMembershipCheckpoints("0"), List.of()); + + GetTenantMembershipForRuntimeResponse response = + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(), snapshot); + + assertEquals(ACCOUNT_UUID, response.getAccountId()); + assertEquals(TENANT_UUID, response.getTenantId()); + assertEquals("membership-read-1", response.getRequestId()); + assertFalse(response.getMembershipExists()); + assertFalse(response.getGameplayAdmissionAllowed()); + assertEquals("MISSING", response.getMembershipLifecycleState()); + assertEquals(Map.of(TENANT_UUID, "1"), response.getMembershipVersionMap()); + assertEquals("1", response.getMembershipAuthorityGeneration()); + assertEquals(4, response.getOutboxCheckpointsCount()); + assertTrue( + response.getOutboxCheckpointsList().stream() + .allMatch(checkpoint -> "0".equals(checkpoint.getOutboxSequence()))); + assertEquals(0, response.getOutboxSourceEvidenceCount()); + } + + @Test + void encodeRuntimeMembershipCandidateRejectsWrongCallerTarget() { + RuntimeMembershipSnapshotDto snapshot = + runtimeMembershipSnapshot( + 11L, true, runtimeMembershipCheckpoints("1"), runtimeMembershipSourceEvidence()); + + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(), snapshot)); + } + + @Test + void encodeRuntimeMembershipCandidateRejectsIncompleteCheckpointOrSourceEvidence() { + List completeCheckpoints = runtimeMembershipCheckpoints("1"); + RuntimeMembershipSnapshotDto missingCheckpoint = + runtimeMembershipSnapshot( + 10L, + true, + completeCheckpoints.subList(0, completeCheckpoints.size() - 1), + runtimeMembershipSourceEvidence()); + RuntimeMembershipSnapshotDto missingSourceEvidence = + runtimeMembershipSnapshot(10L, true, completeCheckpoints, List.of()); + + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(), missingCheckpoint)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(), missingSourceEvidence)); + } + private static final class RecordingObserver implements StreamObserver { private T response; private boolean receivedTransportError; diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index b6485d69f6..a1226cbace 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -35,9 +35,11 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio var request = GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("7") - .setTenantId("1") - .setRequestId("request-1") + .setPlayerContext( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setRequestId("request-1")) .build(); assertThat(stub.getTenantMembershipForRuntime(request).getMembershipLifecycleState()) .isEqualTo("ACTIVE"); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 0bc0f4bf81..763942d040 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 @@ -5,7 +5,9 @@ import io.grpc.stub.StreamObserver; import java.io.IOException; import java.time.Instant; +import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -30,6 +32,10 @@ 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.RuntimeAuthorityTuple; +import net.firedevops.firemud.account.v1.RuntimeMembershipBaseline; +import net.firedevops.firemud.account.v1.RuntimeOutboxCheckpoint; +import net.firedevops.firemud.account.v1.RuntimeOutboxSourceEvidence; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.common.EmailCanonicalization; @@ -41,6 +47,8 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase implements AutoCloseable { private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; + private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; private static final Set IMPLEMENTED_RUNTIME_METHODS = Set.of( "Ping", @@ -169,17 +177,107 @@ public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { boolean exists = membershipExists.get(); - responseObserver.onNext( + String accountSelector = request.getPlayerContext().getAccountId(); + String tenantSelector = request.getPlayerContext().getTenantId(); + String lifecycle = membershipLifecycleState.get(); + boolean admitted = gameplayAdmissionAllowed.get(); + GetTenantMembershipForRuntimeResponse response; + if (exists && admitted && "ACTIVE".equals(lifecycle)) { + response = + completeMembershipSnapshot( + accountSelector, tenantSelector, request.getPlayerContext().getRequestId(), true); + } else if (!exists && !admitted && "MISSING".equals(lifecycle)) { + response = + completeMembershipSnapshot( + accountSelector, tenantSelector, request.getPlayerContext().getRequestId(), false); + } else { + response = + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(canonicalUuid(accountSelector)) + .setTenantId(canonicalUuid(tenantSelector)) + .setRequestAccountId(accountSelector) + .setRequestTenantId(tenantSelector) + .setRequestId(request.getPlayerContext().getRequestId()) + .setMembershipExists(exists) + .setMembershipLifecycleState(lifecycle) + .setGameplayAdmissionAllowed(admitted) + .setEvaluatedAt(EVALUATED_AT) + .build(); + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( + String accountSelector, String tenantSelector, String requestId, boolean exists) { + String accountUuid = canonicalUuid(accountSelector); + String tenantUuid = canonicalUuid(tenantSelector); + String membershipStream = + AUTHORITY_STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; + List checkpoints = + new ArrayList<>( + List.of( + checkpoint(AUTHORITY_STREAM_PREFIX + "account/" + accountUuid, "0"), + checkpoint(AUTHORITY_STREAM_PREFIX + "issuer/" + ACCOUNT_ISSUER, "0"), + checkpoint(membershipStream, exists ? "1" : "0"), + checkpoint(AUTHORITY_STREAM_PREFIX + "tenant/" + tenantUuid, "0"))); + checkpoints.sort( + (first, second) -> first.getOutboxStreamKey().compareTo(second.getOutboxStreamKey())); + RuntimeAuthorityTuple tuple = + RuntimeAuthorityTuple.newBuilder() + .setIssuerAuthGeneration("1") + .setAccountAuthorityGeneration("1") + .putTenantAuthorityGeneration(tenantUuid, "1") + .putMembershipAuthorityGeneration(tenantUuid, "1") + .build(); + RuntimeMembershipBaseline baseline = + RuntimeMembershipBaseline.newBuilder() + .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") + .putMembershipVersion(tenantUuid, "1") + .setMembershipAuthorityGeneration("1") + .build(); + GetTenantMembershipForRuntimeResponse.Builder response = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(request.getAccountId()) - .setTenantId(request.getTenantId()) + .setAccountId(accountUuid) + .setTenantId(tenantUuid) + .setRequestAccountId(accountSelector) + .setRequestTenantId(tenantSelector) + .setRequestId(requestId) .setMembershipExists(exists) - .setMembershipLifecycleState(membershipLifecycleState.get()) - .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) - .setMembershipVersion(exists ? 1L : 0L) - .setEvaluatedAt(EVALUATED_AT) - .build()); - responseObserver.onCompleted(); + .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") + .setGameplayAdmissionAllowed(exists) + .putMembershipVersion(tenantUuid, "1") + .setMembershipAuthorityGeneration("1") + .setMembershipBaseline(baseline) + .setAuthorityTuple(tuple) + .setIssuanceFence("1") + .addAllOutboxCheckpoints(checkpoints) + .setEvaluatedAt(EVALUATED_AT); + if (exists) { + response.addRoles("player"); + response.addOutboxSourceEvidence( + RuntimeOutboxSourceEvidence.newBuilder() + .setOutboxStreamKey(membershipStream) + .setOutboxSequence("1") + .setEventId("00000000-0000-0000-0000-000000000099") + .setEventDigest("sha256:" + "0".repeat(64))); + } + return response.build(); + } + + private static RuntimeOutboxCheckpoint checkpoint(String streamKey, String sequence) { + return RuntimeOutboxCheckpoint.newBuilder() + .setOutboxStreamKey(streamKey) + .setOutboxSequence(sequence) + .build(); + } + + private static String canonicalUuid(String selector) { + long value = Long.parseLong(selector); + if (value <= 0L || !Long.toString(value).equals(selector)) { + throw new IllegalArgumentException("runtime membership fixture selector must be canonical"); + } + return "00000000-0000-0000-0000-" + String.format(Locale.ROOT, "%012d", value); } @Override 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 10bb5ebc71..b70eb08eda 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 @@ -291,15 +291,13 @@ private JoinPublicProductionMembershipResponse joinError(String code, String mes } public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( - String accountId, String tenantId, String requestId) { + PlayerExecutionContext playerContext) { if (stub() == null) { return membershipAuthorityUnavailable(); } GetTenantMembershipForRuntimeRequest request = GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId(accountId) - .setTenantId(tenantId) - .setRequestId(requestId == null ? "" : requestId) + .setPlayerContext(Objects.requireNonNull(playerContext, "playerContext is required")) .build(); try { return callStub().getTenantMembershipForRuntime(request); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index b4e70732ea..8a088c5edc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -5,6 +5,7 @@ import io.micrometer.core.instrument.MeterRegistry; import java.time.Instant; import java.time.format.DateTimeParseException; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; @@ -36,6 +37,7 @@ import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -56,6 +58,8 @@ public class PlayCommandHandler { private static final String RESUME_DENIED_METRIC = "gamesession.session.resume_denied"; private static final String FRESH_ENTRY_FALLBACK_METRIC = "gamesession.session.fresh_entry_fallback"; + private static final String ACCOUNT_AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final String ACCOUNT_AUTHORITY_ISSUER = "firemud-account-service"; private final SessionAuthenticationService sessionAuthenticationService; private final SessionContextService sessionContextService; @@ -650,7 +654,7 @@ private Optional validateRuntimeAdmission( GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( - Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); + membershipPlayerContext(context, selectedRealm, requestedCharacterId, requestId)); return validateMembershipResponse( membershipResponse, context, @@ -709,7 +713,7 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (!isSafeMembershipAuthorityResponse(response, context, selectedRealm)) { + if (!isSafeMembershipAuthorityResponse(response, context, selectedRealm, requestId)) { return Optional.of( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); @@ -781,17 +785,177 @@ private Optional validateMembershipResponse( private boolean isValidMembershipLifecycleEvidence( GetTenantMembershipForRuntimeResponse response) { + if (!hasCompleteMembershipAuthorityCarrier(response)) { + return false; + } return switch (response.getMembershipLifecycleState()) { - case "MISSING" -> !response.getMembershipExists() && !response.getGameplayAdmissionAllowed(); - case "INACTIVE" -> + case "MISSING" -> + !response.getMembershipExists() + && !response.getGameplayAdmissionAllowed() + && response.getRolesCount() == 0; + case "ACTIVE" -> response.getMembershipExists() - && response.getMembershipVersion() > 0L - && !response.getGameplayAdmissionAllowed(); - case "ACTIVE" -> response.getMembershipExists() && response.getMembershipVersion() > 0L; + && response.getGameplayAdmissionAllowed() + && response.getRolesList().contains("player") + && hasPositiveMembershipVersion(response); default -> false; }; } + private static boolean hasPositiveMembershipVersion( + GetTenantMembershipForRuntimeResponse response) { + if (response.getMembershipVersionCount() != 1) { + return false; + } + Map.Entry version = + response.getMembershipVersionMap().entrySet().iterator().next(); + return isCanonicalUuid(response.getTenantId()) + && version.getKey().equals(response.getTenantId()) + && isPositiveCanonicalDecimal(version.getValue()); + } + + private static boolean hasCompleteMembershipAuthorityCarrier( + GetTenantMembershipForRuntimeResponse response) { + if (!response.hasMembershipBaseline() || !response.hasAuthorityTuple()) { + return false; + } + if (!isCanonicalUuid(response.getAccountId()) || !isCanonicalUuid(response.getTenantId())) { + return false; + } + if (!response + .getMembershipBaseline() + .equals( + net.firedevops.firemud.account.v1.RuntimeMembershipBaseline.newBuilder() + .setMembershipLifecycleState(response.getMembershipLifecycleState()) + .putAllMembershipVersion(response.getMembershipVersionMap()) + .setMembershipAuthorityGeneration(response.getMembershipAuthorityGeneration()) + .build())) { + return false; + } + if (!isPositiveCanonicalDecimal(response.getIssuanceFence())) { + return false; + } + + var tuple = response.getAuthorityTuple(); + String tenantId = response.getTenantId(); + if (!"1".equals(tuple.getIssuerAuthGeneration()) + || !"1".equals(tuple.getAccountAuthorityGeneration()) + || !tuple.getTenantAuthorityGenerationMap().keySet().equals(java.util.Set.of(tenantId)) + || !tuple.getMembershipAuthorityGenerationMap().keySet().equals(java.util.Set.of(tenantId)) + || !"1".equals(tuple.getTenantAuthorityGenerationMap().get(tenantId)) + || !isPositiveCanonicalDecimal(tuple.getMembershipAuthorityGenerationMap().get(tenantId)) + || !tuple + .getMembershipAuthorityGenerationMap() + .get(tenantId) + .equals(response.getMembershipAuthorityGeneration()) + || tuple.getPrivateRealmGrantVersionsCount() != 0 + || tuple.hasAccountSecurityCutoff() + || tuple.hasTenantBillingCutoff()) { + return false; + } + + String membershipStream = + ACCOUNT_AUTHORITY_STREAM_PREFIX + "membership/" + response.getAccountId() + "/" + tenantId; + String accountStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "account/" + response.getAccountId(); + String issuerStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "issuer/" + ACCOUNT_AUTHORITY_ISSUER; + String tenantStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "tenant/" + tenantId; + List expectedStreamKeys = + new ArrayList<>(List.of(accountStream, issuerStream, membershipStream, tenantStream)); + expectedStreamKeys.sort(String::compareTo); + if (response.getOutboxCheckpointsCount() != expectedStreamKeys.size()) { + return false; + } + List actualStreamKeys = new ArrayList<>(); + Map checkpointSequences = new java.util.HashMap<>(); + for (var checkpoint : response.getOutboxCheckpointsList()) { + if (!checkpoint.getUnknownFields().asMap().isEmpty() + || !isCanonicalNonNegativeDecimal(checkpoint.getOutboxSequence()) + || checkpointSequences.putIfAbsent( + checkpoint.getOutboxStreamKey(), checkpoint.getOutboxSequence()) + != null) { + return false; + } + actualStreamKeys.add(checkpoint.getOutboxStreamKey()); + } + if (!actualStreamKeys.equals(expectedStreamKeys)) { + return false; + } + boolean positive = "ACTIVE".equals(response.getMembershipLifecycleState()); + for (String streamKey : expectedStreamKeys) { + String sequence = checkpointSequences.get(streamKey); + if (streamKey.equals(membershipStream)) { + if (positive != isPositiveCanonicalDecimal(sequence)) { + return false; + } + } else if (!"0".equals(sequence)) { + return false; + } + } + if (!positive) { + return "MISSING".equals(response.getMembershipLifecycleState()) + && !response.getMembershipExists() + && !response.getGameplayAdmissionAllowed() + && response.getOutboxSourceEvidenceCount() == 0 + && "1".equals(response.getMembershipVersionMap().get(tenantId)) + && "1".equals(response.getMembershipAuthorityGeneration()) + && "1".equals(tuple.getIssuerAuthGeneration()) + && "1".equals(tuple.getAccountAuthorityGeneration()) + && "1".equals(tuple.getTenantAuthorityGenerationMap().get(tenantId)) + && response.getMembershipVersionCount() == 1; + } + + if (response.getOutboxSourceEvidenceCount() != 1 + || !response.getMembershipExists() + || !response.getGameplayAdmissionAllowed() + || response.getMembershipVersionCount() != 1 + || !hasPositiveMembershipVersion(response)) { + return false; + } + var source = response.getOutboxSourceEvidence(0); + return source.getUnknownFields().asMap().isEmpty() + && source.getOutboxStreamKey().equals(membershipStream) + && source.getOutboxSequence().equals(checkpointSequences.get(membershipStream)) + && isCanonicalUuid(source.getEventId()) + && source.getEventDigest().matches("sha256:[0-9a-f]{64}"); + } + + private static boolean isPositiveCanonicalDecimal(String value) { + return value != null && value.matches("[1-9][0-9]*"); + } + + private static boolean isCanonicalNonNegativeDecimal(String value) { + return value != null && value.matches("(?:0|[1-9][0-9]*)"); + } + + private static boolean isCanonicalUuid(String value) { + if (!StringUtils.hasText(value)) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } + + private static PlayerExecutionContext membershipPlayerContext( + SessionContext caller, + GameplayWorldCatalog.RealmView target, + long characterId, + String requestId) { + return PlayerExecutionContext.newBuilder() + .setAccountId(Long.toString(caller.accountId())) + .setTenantId(Long.toString(target.tenantId())) + .setRealmId(Objects.toString(target.realmId(), "")) + .setPlayableStateNamespaceId(Objects.toString(target.playableStateNamespaceId(), "")) + .setPlayableStateScope(Objects.toString(target.stateScope(), "")) + .setGameInstanceId(Long.toString(target.gameInstanceId())) + .setCharacterId(characterId > 0L ? Long.toString(characterId) : "") + .setSessionId(Long.toString(caller.sessionId())) + .setRequestId(requestId) + .build(); + } + private PlayCommandHandlingResult worldAccessDeniedFailure( SessionContext context, String tenantTag, @@ -1016,19 +1180,21 @@ private boolean isEntitlementUnavailable(ErrorDetail error) { private boolean isSafeMembershipAuthorityResponse( GetTenantMembershipForRuntimeResponse response, SessionContext context, - GameplayWorldCatalog.RealmView selectedRealm) { + GameplayWorldCatalog.RealmView selectedRealm, + String requestId) { if (!StringUtils.hasText(response.getAccountId()) || !StringUtils.hasText(response.getTenantId()) - || !StringUtils.hasText(response.getEvaluatedAt())) { + || !StringUtils.hasText(response.getEvaluatedAt()) + || !isCanonicalUuid(response.getAccountId()) + || !isCanonicalUuid(response.getTenantId()) + || !response.getRequestAccountId().equals(Long.toString(context.accountId())) + || !response.getRequestTenantId().equals(Long.toString(selectedRealm.tenantId())) + || !response.getRequestId().equals(requestId)) { return false; } try { Instant.parse(response.getEvaluatedAt()); - if (Long.parseLong(response.getAccountId()) != context.accountId() - || Long.parseLong(response.getTenantId()) != selectedRealm.tenantId()) { - return false; - } - } catch (DateTimeParseException | NumberFormatException ex) { + } catch (DateTimeParseException ex) { return false; } return true; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index bfabacb888..3e4e43fc38 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -19,7 +19,6 @@ import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; -import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.cache.LookCacheService; import net.firedevops.firemud.cache.ScreenBufferService; @@ -260,21 +259,17 @@ void setUp() { .setAuthToken("stub-token") .setAccountId("123") .build()); - org.mockito.Mockito.doReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("ACTIVE") - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()) + org.mockito.Mockito.doAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1"), + invocation.getArgument(0))) .when(accountClient) .getTenantMembershipForRuntime( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(String.class)); + org.mockito.ArgumentMatchers.any( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); org.mockito.Mockito.doReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") @@ -822,7 +817,11 @@ void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { assertThat(payloads).anyMatch(payload -> json(payload).path("outputs").isArray()); verify(accountClient) .getTenantMembershipForRuntime( - eq("123"), eq("22"), org.mockito.ArgumentMatchers.anyString()); + argThat( + playerContext -> + "123".equals(playerContext.getAccountId()) + && "22".equals(playerContext.getTenantId()) + && !playerContext.getRequestId().isBlank())); verify(accountClient) .getTenantEntitlementsForRuntime(eq("22"), org.mockito.ArgumentMatchers.anyString()); assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)) 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 5d84ceca3b..c541eecf50 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 @@ -142,6 +142,20 @@ private static PlayerExecutionContext directTextContext(String requestId) { .build(); } + private static PlayerExecutionContext runtimeMembershipContext( + String accountId, String tenantId, String requestId) { + return PlayerExecutionContext.newBuilder() + .setAccountId(accountId) + .setTenantId(tenantId) + .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") + .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateScope("SHARED") + .setGameInstanceId("40") + .setSessionId("42") + .setRequestId(requestId) + .build(); + } + @Test void authenticateReturnsUnavailableWhenStubIsNotInitialized() throws Exception { AuthenticateResponse response = newClient(null).authenticate("demo@example.com", "swordfish"); @@ -308,33 +322,36 @@ void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); GetTenantMembershipForRuntimeResponse expected = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("42") - .setTenantId("7") + .setAccountId("00000000-0000-0000-0000-000000000042") + .setTenantId("00000000-0000-0000-0000-000000000007") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) - .setMembershipVersion(12L) + .putMembershipVersion("00000000-0000-0000-0000-000000000007", "12") + .setMembershipAuthorityGeneration("4") + .setRequestAccountId("42") + .setRequestTenantId("7") .setEvaluatedAt("2026-07-31T00:00:00Z") .build(); when(stub.getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class))) .thenReturn(expected); AccountClient client = newClient(stub); + PlayerExecutionContext playerContext = runtimeMembershipContext("42", "7", "request-1"); GetTenantMembershipForRuntimeResponse actual = - client.getTenantMembershipForRuntime("42", "7", null); + client.getTenantMembershipForRuntime(playerContext); ArgumentCaptor captor = ArgumentCaptor.forClass(GetTenantMembershipForRuntimeRequest.class); verify(stub).getTenantMembershipForRuntime(captor.capture()); - assertThat(captor.getValue().getAccountId()).isEqualTo("42"); - assertThat(captor.getValue().getTenantId()).isEqualTo("7"); - assertThat(captor.getValue().getRequestId()).isEmpty(); + assertThat(captor.getValue().getPlayerContext()).isEqualTo(playerContext); assertThat(actual).isEqualTo(expected); } @Test void runtimeMembershipReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetTenantMembershipForRuntimeResponse response = - newClient(null).getTenantMembershipForRuntime("42", "7", "request-1"); + newClient(null) + .getTenantMembershipForRuntime(runtimeMembershipContext("42", "7", "request-1")); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); @@ -358,11 +375,11 @@ void runtimeMembershipRetriesOnceAfterUnavailableAndPreservesSuccess() throws Ex .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetTenantMembershipForRuntimeResponse expected = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("42") - .setTenantId("7") + .setAccountId("00000000-0000-0000-0000-000000000042") + .setTenantId("00000000-0000-0000-0000-000000000007") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) - .setMembershipVersion(12L) + .putMembershipVersion("00000000-0000-0000-0000-000000000007", "12") .build(); when(fixture .retryStub() @@ -370,7 +387,9 @@ void runtimeMembershipRetriesOnceAfterUnavailableAndPreservesSuccess() throws Ex .thenReturn(expected); GetTenantMembershipForRuntimeResponse actual = - fixture.client().getTenantMembershipForRuntime("42", "7", "request-1"); + fixture + .client() + .getTenantMembershipForRuntime(runtimeMembershipContext("42", "7", "request-1")); assertThat(actual).isEqualTo(expected); verify(fixture.initialStub()) @@ -393,7 +412,9 @@ void runtimeMembershipNormalizesExhaustedUnavailableToCanonicalUnavailable() thr .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetTenantMembershipForRuntimeResponse response = - fixture.client().getTenantMembershipForRuntime("42", "7", "request-1"); + fixture + .client() + .getTenantMembershipForRuntime(runtimeMembershipContext("42", "7", "request-1")); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); @@ -472,7 +493,7 @@ void runtimeMembershipNormalizesInitialInternalWithoutRetryOrChannelRebuild() th AccountClient client = newClient(stub, channelFactory); GetTenantMembershipForRuntimeResponse response = - client.getTenantMembershipForRuntime("42", "7", "request-1"); + client.getTenantMembershipForRuntime(runtimeMembershipContext("42", "7", "request-1")); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 6b56b01405..7810427d75 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -101,17 +101,14 @@ void setUp() { .setAllowed(true) .build()); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("ACTIVE") - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1"), + invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() @@ -531,7 +528,8 @@ void playReadsEntitlementMembershipAndGrantBeforeActorRoster() { .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); order .verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); order .verify(accountClient) .getRealmAccessGrantForRuntime( @@ -1049,17 +1047,15 @@ void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding( new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("ACTIVE") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .incomplete( + 123L, 22L, true, "ACTIVE", false, "2", "2026-03-30T00:00:00Z"), + invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1078,16 +1074,14 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setMembershipLifecycleState("MISSING") - .setGameplayAdmissionAllowed(false) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L), + invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle( @@ -1117,24 +1111,22 @@ void playNonPublicInactiveMembershipDoesNotUsePublicJoin() { SessionContext context = previewRealmContext(); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("INACTIVE") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(3L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .incomplete( + 123L, 22L, true, "INACTIVE", false, "3", "2026-03-30T00:00:00Z"), + invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE); + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) - .isEqualTo("error.play.non-public-enrollment-required"); + .isEqualTo("error.play.world-access-denied"); Mockito.verify(accountClient, never()) .getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1333,7 +1325,7 @@ void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String e new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() .setError( @@ -1359,17 +1351,14 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setMembershipLifecycleState("MISSING") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(5L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L), + invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1390,17 +1379,21 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setMembershipLifecycleState(lifecycleState) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .incomplete( + 123L, + 22L, + false, + lifecycleState, + false, + "0", + "2026-03-30T00:00:00Z"), + invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1420,17 +1413,21 @@ void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleSt new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(membershipExists) - .setMembershipLifecycleState(lifecycleState) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(membershipExists ? 3L : 5L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .incomplete( + 123L, + 22L, + membershipExists, + lifecycleState, + true, + membershipExists ? "3" : "5", + "2026-03-30T00:00:00Z"), + invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1446,27 +1443,25 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("INACTIVE") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(4L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .incomplete( + 123L, 22L, true, "INACTIVE", false, "4", "2026-03-30T00:00:00Z"), + invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) - .isEqualTo("error.play.join-required"); - Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); + .isEqualTo("error.play.world-access-denied"); + Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } @ParameterizedTest @@ -1476,17 +1471,14 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setMembershipLifecycleState("MISSING") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L), + invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() @@ -1505,7 +1497,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); Mockito.verify(accountClient, never()) .getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); Mockito.verifyNoInteractions( entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); } @@ -1516,17 +1508,14 @@ void playBillingDenialMasksMissingPublicMembership() { new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setMembershipLifecycleState("MISSING") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L), + invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() @@ -1543,7 +1532,7 @@ void playBillingDenialMasksMissingPublicMembership() { .isEqualTo(GameplayStageCommandConstants.TENANT_BILLING_BLOCKED_CODE); Mockito.verify(accountClient, never()) .getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); Mockito.verifyNoInteractions( entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); } @@ -1554,17 +1543,14 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setMembershipLifecycleState("MISSING") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L), + invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() @@ -1582,7 +1568,8 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) .isEqualTo("error.play.public-production-admission-denied"); Mockito.verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); Mockito.verifyNoInteractions( entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); } @@ -1618,17 +1605,14 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setMembershipLifecycleState("MISSING") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L), + invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() @@ -1646,7 +1630,8 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti Mockito.verify(accountClient) .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); Mockito.verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); Mockito.verifyNoInteractions( entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); } @@ -1657,17 +1642,14 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("ACTIVE") - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("not-a-timestamp") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .incomplete(123L, 22L, true, "ACTIVE", true, "1", "not-a-timestamp"), + invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1684,6 +1666,33 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenReturn( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( + 123L, 22L, "1") + .toBuilder() + .setRequestId("wrong-request-id") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.authority-unavailable"); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + @Test void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = @@ -1751,7 +1760,7 @@ void playWhenMembershipAuthorityUnavailableFailsClosed(String errorCode) { new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 3475ff8cba..e79acb1085 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -17,7 +17,6 @@ import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; -import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.cache.LookCacheService; import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; @@ -164,17 +163,14 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId("77").build()); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("77") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("ACTIVE") - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(77L, 22L, "1"), + invocation.getArgument(0))); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), @@ -457,17 +453,15 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { assertTrue(firstLook.commandResult().accepted()); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("77") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("ACTIVE") - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:01:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .incomplete( + 77L, 22L, true, "ACTIVE", false, "2", "2026-03-30T00:01:00Z"), + invocation.getArgument(0))); TextCommandInterpretationResult secondLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); assertTrue(secondLogin.commandResult().accepted()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 70f1fa60c2..ddb2ec862a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -19,7 +19,6 @@ import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; -import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.cache.LookCacheService; import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; @@ -164,17 +163,14 @@ void setUp() { .setAccountId("123") .build()); when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setMembershipLifecycleState("ACTIVE") - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1"), + invocation.getArgument(0))); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java new file mode 100644 index 0000000000..9a8a2db4c0 --- /dev/null +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.gamesession.support; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.RuntimeAuthorityTuple; +import net.firedevops.firemud.account.v1.RuntimeMembershipBaseline; +import net.firedevops.firemud.account.v1.RuntimeOutboxCheckpoint; +import net.firedevops.firemud.account.v1.RuntimeOutboxSourceEvidence; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** Complete or intentionally incomplete fixtures for the denied runtime membership carrier. */ +public final class RuntimeMembershipTestFixtures { + private static final String STREAM_PREFIX = "account:auth-authority:v1:"; + private static final String ISSUER = "firemud-account-service"; + private static final String EVENT_ID = "00000000-0000-0000-0000-000000000099"; + private static final String EVENT_DIGEST = "sha256:" + "0".repeat(64); + private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; + + private RuntimeMembershipTestFixtures() {} + + public static GetTenantMembershipForRuntimeResponse active( + long accountId, long tenantId, String membershipVersion) { + return complete(accountId, tenantId, true, "ACTIVE", true, membershipVersion); + } + + public static GetTenantMembershipForRuntimeResponse missing(long accountId, long tenantId) { + return complete(accountId, tenantId, false, "MISSING", false, "1"); + } + + public static GetTenantMembershipForRuntimeResponse echoRequestId( + GetTenantMembershipForRuntimeResponse response, PlayerExecutionContext request) { + return response.toBuilder().setRequestId(request.getRequestId()).build(); + } + + public static GetTenantMembershipForRuntimeResponse incomplete( + long accountId, + long tenantId, + boolean membershipExists, + String lifecycle, + boolean gameplayAdmissionAllowed, + String membershipVersion, + String evaluatedAt) { + String accountUuid = uuid(accountId); + String tenantUuid = uuid(tenantId); + GetTenantMembershipForRuntimeResponse.Builder response = + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(accountUuid) + .setTenantId(tenantUuid) + .setRequestAccountId(Long.toString(accountId)) + .setRequestTenantId(Long.toString(tenantId)) + .setMembershipExists(membershipExists) + .setMembershipLifecycleState(lifecycle) + .setGameplayAdmissionAllowed(gameplayAdmissionAllowed) + .setEvaluatedAt(evaluatedAt); + if (membershipVersion != null) { + response.putMembershipVersion(tenantUuid, membershipVersion); + } + return response.build(); + } + + public static GetTenantMembershipForRuntimeResponse advancedTenantWithZeroCheckpoint( + long accountId, long tenantId) { + GetTenantMembershipForRuntimeResponse response = active(accountId, tenantId, "1"); + return response.toBuilder() + .setAuthorityTuple( + response.getAuthorityTuple().toBuilder() + .putTenantAuthorityGeneration(uuid(tenantId), "2")) + .build(); + } + + private static GetTenantMembershipForRuntimeResponse complete( + long accountId, + long tenantId, + boolean exists, + String lifecycle, + boolean admitted, + String membershipVersion) { + String accountUuid = uuid(accountId); + String tenantUuid = uuid(tenantId); + String membershipStream = STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; + List checkpoints = + new ArrayList<>( + List.of( + checkpoint(STREAM_PREFIX + "account/" + accountUuid, "0"), + checkpoint(STREAM_PREFIX + "issuer/" + ISSUER, "0"), + checkpoint(membershipStream, exists ? "1" : "0"), + checkpoint(STREAM_PREFIX + "tenant/" + tenantUuid, "0"))); + checkpoints.sort( + (first, second) -> first.getOutboxStreamKey().compareTo(second.getOutboxStreamKey())); + RuntimeAuthorityTuple tuple = + RuntimeAuthorityTuple.newBuilder() + .setIssuerAuthGeneration("1") + .setAccountAuthorityGeneration("1") + .putTenantAuthorityGeneration(tenantUuid, "1") + .putMembershipAuthorityGeneration(tenantUuid, "1") + .build(); + RuntimeMembershipBaseline baseline = + RuntimeMembershipBaseline.newBuilder() + .setMembershipLifecycleState(lifecycle) + .putMembershipVersion(tenantUuid, membershipVersion) + .setMembershipAuthorityGeneration("1") + .build(); + GetTenantMembershipForRuntimeResponse.Builder response = + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(accountUuid) + .setTenantId(tenantUuid) + .setRequestAccountId(Long.toString(accountId)) + .setRequestTenantId(Long.toString(tenantId)) + .setMembershipExists(exists) + .setMembershipLifecycleState(lifecycle) + .setGameplayAdmissionAllowed(admitted) + .putMembershipVersion(tenantUuid, membershipVersion) + .setMembershipAuthorityGeneration("1") + .setMembershipBaseline(baseline) + .setAuthorityTuple(tuple) + .setIssuanceFence("1") + .addAllOutboxCheckpoints(checkpoints) + .setEvaluatedAt(EVALUATED_AT); + if (exists) { + response.addRoles("player"); + response.addOutboxSourceEvidence( + RuntimeOutboxSourceEvidence.newBuilder() + .setOutboxStreamKey(membershipStream) + .setOutboxSequence("1") + .setEventId(EVENT_ID) + .setEventDigest(EVENT_DIGEST)); + } + return response.build(); + } + + private static RuntimeOutboxCheckpoint checkpoint(String streamKey, String sequence) { + return RuntimeOutboxCheckpoint.newBuilder() + .setOutboxStreamKey(streamKey) + .setOutboxSequence(sequence) + .build(); + } + + private static String uuid(long id) { + if (id <= 0L) { + throw new IllegalArgumentException("test selector IDs must be positive"); + } + return "00000000-0000-0000-0000-" + String.format(Locale.ROOT, "%012d", id); + } +} From 346fc819c8aa384d7362cef9c336f387903144d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 16:31:06 +1300 Subject: [PATCH 10/46] Record disabled membership carrier and composed proof limits --- design/project-management/ai-observations.md | 5 +++++ .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 7bf56695ba..7950f08ce4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -127,3 +127,8 @@ Entry format: - Context: the Account response-envelope Secret materializer emitted canonical UTC timestamps with trailing fractional zeroes removed. A broad developer-tool run intermittently failed its CLI readback although focused tests using whole-second timestamps passed. - Observation: this runner's Python `datetime.fromisoformat` rejected a valid five-digit fractional-second timestamp such as `.00101Z` after offset normalization. A timestamp round-trip sweep reproduced the defect, and the parser was changed to accept the contract's one-to-six fractional digits explicitly; the full 112-test developer-tool suite then passed. - Expected pattern: test exact writer-to-reader timestamp round trips across fractional precisions, including live-clock output, before treating a source-generation/freshness readback as reliable. + +- `2026-09-27`: Proto-touching Gradle proof may need configuration cache disabled + - Context: a combined Account and Game Session focused check regenerated protobuf sources after a membership wire change. + - Observation: Gradle 9.5.1 reached Java/test work but failed while storing its configuration cache because the protobuf plugin's `GenerateProtoTask` captured unsupported project and source-directory objects. The same canonical tasks passed with `--no-configuration-cache`; the first failed exit was not valid test proof even though some tasks had run. + - Expected pattern: for proto-affecting validation, pass `--no-configuration-cache` when this plugin error appears, retain the canonical task paths and service locks, and report the successful rerun rather than treating partial task output as a green gate. 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 e6355ec61d..52bcbfb6a8 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 unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's exact one-tenant `membershipVersion` map in the producer, strict shared codec, canonical digest vectors, immutable evidence, and Account exact retry/readback comparisons. The Account producer may extract a local numeric value only after validating the map; it does not persist or transmit a scalar event field. Shared codec and Account/Game Session vector tests execute locally; PostgreSQL JOIN/reconciliation tests compile but skip without Docker, and the runtime membership RPC remains denied until its complete same-snapshot producer and consumer proof is ready. The unactivated Account ring materializer binds a dedicated service-account username in the protected source record, checks server-reported identity before Secret access, and returns a typed non-secret receipt with source generation/predecessor and exact Secret UID/resourceVersion readback. A focused read-side verifier now checks its closed typed shape, canonical digest, and exact source, writer, and Secret bindings; this remains local structural proof, not authenticated environment/secrets-channel publication. Sole-writer RBAC, protected custody, handoff, deployment readback, and live readiness remain unproved, so no Account ring mount is published. -Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. This is a local producer boundary, not a wire response or Game Session consumer: the runtime RPC remains denied. The exact local Account check executed 377 unit tests, while all 78 PostgreSQL integration tests were skipped without Docker. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one new negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both aggregate gates remain red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's unique snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; the ADR correction is in #2876, while that runtime carrier and consumer remain open. +Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. Its new typed runtime wire and Account encoder carry the complete current-only snapshot with exact caller selector and request-ID echoes. Game Session has a fail-closed structural consumer for that carrier, but neither full event-content/current-authority verification nor live admission is proved; the Account RPC remains denied. The composed local module gate passed with 381 Account unit tests, 1,640 Game Session unit tests, and 43 common-test-support tests executed; all 78 Account integration cases, 112 of 130 Game Session integration cases, and 39 of 40 Game Session cross-service cases skipped without Docker. Thus PostgreSQL, cross-service, and live RPC proof for this new wire remain open. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both earlier aggregate gates were red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's then nine-file snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; #2876 records that authority, and #2880's typed carrier remains disabled pending full producer/consumer proof. 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 durable post-logout episode fencing 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. From aa5d73c05a408ba152ac05f4298cadd52430b831 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 16:37:56 +1300 Subject: [PATCH 11/46] Record bare LOGIN proof and CI activation gap --- .../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 309a5f2a0e..57a0cd0a3d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ The unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. Its new typed runtime wire and Account encoder carry the complete current-only snapshot with exact caller selector and request-ID echoes. Game Session has a fail-closed structural consumer for that carrier, but neither full event-content/current-authority verification nor live admission is proved; the Account RPC remains denied. The composed local module gate passed with 381 Account unit tests, 1,640 Game Session unit tests, and 43 common-test-support tests executed; all 78 Account integration cases, 112 of 130 Game Session integration cases, and 39 of 40 Game Session cross-service cases skipped without Docker. Thus PostgreSQL, cross-service, and live RPC proof for this new wire remain open. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both earlier aggregate gates were red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's then nine-file snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; #2876 records that authority, and #2880's typed carrier remains disabled pending full producer/consumer proof. -V37's deferred database guard rejects an exchange transaction that would commit `PENDING` without its terminal envelope: a pre-commit crash rolls back the claim, while a post-commit exact retry reads the original operation and envelope. This is still storage-only until PostgreSQL executes the new cases and the caller proves that source validation, current authority, credential creation, and envelope completion use that same transaction. Deletion is denied until Account adds a proven receipt/envelope retention and safe-cleanup path; no fixed TTL, timeout, or absent row is interpreted as a terminal result. Lost-response producer/consumer proof remains an activation gate. +V37's deferred database guard rejects an exchange transaction that would commit `PENDING` without its terminal envelope: a pre-commit crash rolls back the claim, while a post-commit exact retry reads the original operation and envelope. The seven V37 PostgreSQL cases executed and passed on #2881 head `25626210c` in CI run `36289042648`, but this remains storage-only until a caller proves that source validation, current authority, credential creation, and envelope completion use that same transaction. Deletion is denied until Account adds a proven receipt/envelope retention and safe-cleanup path; no fixed TTL, timeout, or absent row is interpreted as a terminal result. Lost-response producer/consumer proof remains an activation gate. 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 durable post-logout episode fencing 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. @@ -30,9 +30,9 @@ The in-progress #2873 tenant bridge now has a signed Game Design migration-manif The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. -The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases compile but skipped without Docker; database execution, caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. +The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases passed in CI run `36289042648` on prior #2881 head `25626210c` and skipped locally without Docker; caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. -The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. +The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests currently fail at their shared helper's old successful-bare-LOGIN assertion; there is no supported authenticated first-party fixture until the Account exchange works, and the internal text fixture cannot prove structured public output. They remain an explicit runtime proof gate rather than being disabled or counted as passing. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. The #2876 candidate also adds a local AES-256-GCM response-envelope primitive backed by one Account-only versioned mounted-file ring, with separate connect-token and bare-`LOGIN` purpose keys, key IDs, current-write/older-decrypt rotation, and length-framed exact-operation evidence. Local unit tests execute both-purpose round trips, old-key recovery/removal, wrong-purpose and wrong-operation rejection, and missing/malformed-ring denial. V35 adds an unwired connect-token issuance operation/envelope table with exact identity, digest, pending/terminal state and encrypted-envelope readback; its six PostgreSQL cases reached execution in a prior hosted run, four passed and two failed on a timestamp bind. The corrected-head Account integration task passed, but its success artifact lacks per-test XML. An operator bootstrap candidate creates a protected initial source record once in an owner-only directory and provides an explicit separate rotation action that retains every old purpose key, adds new distinct write keys, and binds a new generation to the previous one without overwriting either source. A separate materializer candidate consumes exact manifest bytes, environment, namespace, generation/predecessor, immutable source-created freshness anchor, and expiry; it verifies retry-stable Secret readback and preserves old decrypt-only keys. The 28 focused materializer tests and combined 139-test developer-tool suite, Ruff, and syntax checks pass locally. Exact-head CI run `36254410583` passed Account Build/Test; its integration task ran and its coverage artifact lists 20 integration classes, but the absent per-case XML prevents an exact executed/skipped count. The aggregate CI gate is red from unchanged Game Session Friends assertions, hosted smoke-tool lint, and an EA-3.1 proof-link check outside #2876's unique diff. Actual protected durable custody, source backup and writer RBAC, deployment/readiness wiring, a live mounted Secret, executed rotation, and proven safe decrypt-only key retirement are still absent. There is no corresponding bare-`LOGIN` operation, wired producer/consumer, or lost-response/live rollout proof. Neither credential path is enabled by the primitive, tool candidates, or V35, and an unavailable key may never authorize reminting. The separately specified credential-bearing `Authenticate` exact-retry envelope is also unimplemented; this two-purpose primitive does not supply its key or enable that operation. From 81955a0c4e4264af7b12dcb9fe5936344317fef4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 16:44:11 +1300 Subject: [PATCH 12/46] Prove first-party bare LOGIN denial before gameplay admission --- ...ommunicationWebSocketCrossServiceTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 46bc398992..09d9ddb28a 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -496,6 +496,27 @@ void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } + @Test + void websocketFirstPartyBareLoginFailsClosedBeforeGameplayAdmission() throws Exception { + ensureTestServicesStarted(); + prepareGameInstance(); + + try (GameplayWebSocketDriver client = openFirstPartyClient("bare-login-unavailable")) { + client.send("LOGIN"); + JsonNode login = awaitStructuredCommand(client, 0, "LOGIN"); + GameplayStructuredCommandAssertions.requireStructuredCommand( + login, "LOGIN", "login", "META", "SESSION"); + assertThat(login.path("accepted").asBoolean()).isFalse(); + assertThat(login.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); + + int baseline = client.responses().size(); + client.send("PLAY demo"); + JsonNode play = awaitStructuredCommand(client, baseline, "PLAY"); + assertThat(play.path("accepted").asBoolean()).isFalse(); + assertThat(play.path("errorCode").asText()).isEqualTo("LOGIN_REQUIRED"); + } + } + @Test void websocketFirstPartySayUsesStructuredCommunicationMetadata() throws Exception { ensureTestServicesStarted(); From 2012b2feb024e000596a419af0ae2a536f8e3cb6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 16:56:15 +1300 Subject: [PATCH 13/46] Accept evidenced inactive membership for explicit join outcome --- .../player-access-and-session.md | 2 + .../AccountJoinPostgresIntegrationTest.java | 81 +++++++++++++++++++ .../test/AccountRuntimeStubServerTest.java | 4 + .../test/AccountRuntimeStubServer.java | 31 +++++-- .../command/text/PlayCommandHandler.java | 13 ++- .../command/text/PlayCommandHandlerTest.java | 24 ++++++ .../RuntimeMembershipTestFixtures.java | 9 ++- 7 files changed, 152 insertions(+), 12 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 52bcbfb6a8..ec6d23304d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,6 +34,8 @@ The #2876 candidate also adds a local AES-256-GCM response-envelope primitive ba At published #2876 head `774356d5a66846a535726f680aa54ce85669160b`, manual CI run `36257232596` passed Account Build/Test, but `:account-service:integrationTest` was `FROM-CACHE`; it does not demonstrate fresh PostgreSQL execution. The gate failed on seven of 39 Game Session Friends/WebSocket cross-service cases, ten hosted smoke-tool Ruff errors, and the EA-3.1 executable-proof-link check. The failing paths are outside #2876's unique diff, but CI alone does not establish the Game Session root cause or merge readiness. The proposed required Account Secret mount remains unpublished: its rendered-manifest contract passes locally, but no environment source, trusted-writer receipt, or readiness proof exists, and deployment cannot safely require the absent Secret. A Game Session sequence-only event-consumer draft was discarded because the accepted contract requires authenticated same-snapshot tuple, fence, membership baseline, complete checkpoints, and source evidence; the current wire does not provide those fields. Runtime RPCs remain denied. +The #2880 membership-snapshot child now carries a typed caller/target request and same-fence Account active/never-joined response candidate with a complete tuple, unchanged baseline, ordered checkpoints, and exact positive-event source evidence. The Account RPC still returns `FAILED_PRECONDITION`; Game Session's current carrier check is structural and does not enable admission. Manual CI run `36291712632` on prior #2880 head `346fc819c8aa384d7362cef9c336f387903144d4` executed Account `:test` and `:integrationTest` successfully, but its successful Account job did not publish per-case JUnit XML, so exact PostgreSQL counts are unavailable. Its four Game Session/TCP Proxy cross-service failures were attributable to #2880's rejection of the fixture's incomplete `INACTIVE` carrier before public-production `JOIN_REQUIRED`. The corrected local candidate accepts only a fully evidenced, non-admitting `INACTIVE` carrier for that outcome while still denying incomplete evidence; the Account producer has no current INACTIVE snapshot path. Focused Play handler and Account stub tests executed locally (65 and 3 tests, zero failures), and the new direct Account same-fence PostgreSQL test compiled but has not run without Docker. Corrected-head CI remains required. + Account's credential-granting gameplay gRPC methods enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Legacy profile GET/PUT now require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy batch reads require the exact Social Groups peer and remain scoped to tenant profiles. Direct account-ID export, external-link, and verification gRPC methods deny before reads or mutation because no authorized internal caller is configured. These guards do not make the broader target method/caller authority complete or restore the disabled runtime reads. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. The Unit 1B child removes `PLAY`'s synthetic account/name/hash fallback and requires a persisted account-roster actor after admission checks, with focused foreign-owner, malformed-row, absent/ambiguous roster, and no-mutation negatives. That Entity list is not yet namespace/policy-qualified, and Account's runtime reads still deny before data access; `CHARS` now returns unavailable before Entity access. These are safety corrections, not a working complete actor-entry path. Typed Account caller/target authority, stable namespace and policy snapshot, descriptor/template resolution, zero/one/many entry behavior, and fork-local copy proof remain ordered pre-v1 work and do not upgrade AA-2.1 status. diff --git a/services/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 963af8063c..40de17d2b1 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 @@ -1053,6 +1053,78 @@ void neverJoinedSnapshotRequiresAndRetainsDurablePairBaselineBeforeFirstJoin() { assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); } + @Test + void runtimeMembershipSnapshotKeepsAbsenceAndFirstJoinEvidenceInOneFencedResult() { + JoinFixture fixture = fixture("active"); + preparePairAuthorityBaseline(fixture); + + var absent = readRuntimeMembershipSnapshot(fixture); + assertThat(absent.requestAccountId()).isEqualTo(fixture.accountId()); + assertThat(absent.requestTenantId()).isEqualTo(fixture.tenantId()); + assertThat(absent.accountUuid()).isEqualTo(fixture.accountUuid().toString()); + assertThat(absent.tenantUuid()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(absent.membershipExists()).isFalse(); + assertThat(absent.gameplayAdmissionAllowed()).isFalse(); + assertThat(absent.membershipBaseline().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(absent.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(absent.membershipBaseline().membershipAuthorityGeneration()) + .isEqualTo( + absent + .authorityTuple() + .membershipAuthorityGeneration() + .get(fixture.tenantUuid().toString())); + assertThat(absent.outboxCheckpoints()) + .containsExactlyElementsOf(expectedMembershipOutboxCheckpoints(fixture, "0")); + assertThat(absent.outboxSourceEvidence()).isEmpty(); + assertThat(absent.roles()).isEmpty(); + assertThat(absent.issuanceFence()).matches("[1-9][0-9]*"); + + assertThat(join(fixture).success()).isTrue(); + var active = readRuntimeMembershipSnapshot(fixture); + var event = readPairBoundPositiveMembershipSnapshot(fixture).authorityEvent(); + assertThat(active.membershipExists()).isTrue(); + assertThat(active.gameplayAdmissionAllowed()).isTrue(); + assertThat(active.membershipBaseline().membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(active.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(active.membershipBaseline().membershipAuthorityGeneration()) + .isEqualTo( + active + .authorityTuple() + .membershipAuthorityGeneration() + .get(fixture.tenantUuid().toString())); + assertThat(active.outboxCheckpoints()) + .containsExactlyElementsOf(expectedMembershipOutboxCheckpoints(fixture, "1")); + assertThat(active.outboxSourceEvidence()) + .containsExactly( + new OutboxSourceEvidence( + authorityStreamKey(fixture), "1", event.eventId(), event.eventDigest())); + assertThat(active.roles()).contains("player"); + assertThat(active.issuanceFence()).matches("[1-9][0-9]*"); + } + + @Test + void runtimeMembershipSnapshotRejectsUnprovedPairAndContradictoryGeneration() { + JoinFixture missingPair = fixture("active"); + assertThatThrownBy(() -> readRuntimeMembershipSnapshot(missingPair)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Never-joined pair baseline is absent"); + + JoinFixture contradictoryPair = fixture("active"); + preparePairAuthorityBaseline(contradictoryPair); + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 WHERE scope_kind = 'MEMBERSHIP' " + + "AND account_uuid = ? AND tenant_uuid = ?", + contradictoryPair.accountUuid(), + contradictoryPair.tenantUuid()); + assertThatThrownBy(() -> readRuntimeMembershipSnapshot(contradictoryPair)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "membership authority generation cannot prove its sequence-zero baseline"); + } + @Test void neverJoinedSnapshotRejectsMissingPairAndAbsentMembershipWithRetainedHistory() { JoinFixture missingPair = fixture("active"); @@ -1154,6 +1226,15 @@ private void preparePairAuthorityBaseline(JoinFixture fixture) { fixture.accountId(), fixture.tenantId())); } + private net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto + readRuntimeMembershipSnapshot(JoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readRuntimeMembershipSnapshot( + fixture.accountId(), fixture.tenantId())); + } + private AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot readPairBoundPositiveMembershipSnapshot(JoinFixture fixture) { return new TransactionTemplate(transactionManager) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index a1226cbace..5731efdb9b 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -49,6 +49,10 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio assertThat(inactive.getMembershipExists()).isTrue(); assertThat(inactive.getGameplayAdmissionAllowed()).isFalse(); assertThat(inactive.getMembershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(inactive.hasMembershipBaseline()).isTrue(); + assertThat(inactive.hasAuthorityTuple()).isTrue(); + assertThat(inactive.getOutboxCheckpointsCount()).isEqualTo(4); + assertThat(inactive.getOutboxSourceEvidenceCount()).isEqualTo(1); server.setMembershipExists(false); var membership = stub.getTenantMembershipForRuntime(request); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 763942d040..3b7ce89b02 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 @@ -185,11 +185,24 @@ public void getTenantMembershipForRuntime( if (exists && admitted && "ACTIVE".equals(lifecycle)) { response = completeMembershipSnapshot( - accountSelector, tenantSelector, request.getPlayerContext().getRequestId(), true); + accountSelector, + tenantSelector, + request.getPlayerContext().getRequestId(), + lifecycle); + } else if (exists && !admitted && "INACTIVE".equals(lifecycle)) { + response = + completeMembershipSnapshot( + accountSelector, + tenantSelector, + request.getPlayerContext().getRequestId(), + lifecycle); } else if (!exists && !admitted && "MISSING".equals(lifecycle)) { response = completeMembershipSnapshot( - accountSelector, tenantSelector, request.getPlayerContext().getRequestId(), false); + accountSelector, + tenantSelector, + request.getPlayerContext().getRequestId(), + lifecycle); } else { response = GetTenantMembershipForRuntimeResponse.newBuilder() @@ -209,7 +222,9 @@ public void getTenantMembershipForRuntime( } private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( - String accountSelector, String tenantSelector, String requestId, boolean exists) { + String accountSelector, String tenantSelector, String requestId, String lifecycle) { + boolean exists = !"MISSING".equals(lifecycle); + boolean admitted = "ACTIVE".equals(lifecycle); String accountUuid = canonicalUuid(accountSelector); String tenantUuid = canonicalUuid(tenantSelector); String membershipStream = @@ -232,7 +247,7 @@ private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( .build(); RuntimeMembershipBaseline baseline = RuntimeMembershipBaseline.newBuilder() - .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") + .setMembershipLifecycleState(lifecycle) .putMembershipVersion(tenantUuid, "1") .setMembershipAuthorityGeneration("1") .build(); @@ -244,8 +259,8 @@ private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( .setRequestTenantId(tenantSelector) .setRequestId(requestId) .setMembershipExists(exists) - .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") - .setGameplayAdmissionAllowed(exists) + .setMembershipLifecycleState(lifecycle) + .setGameplayAdmissionAllowed(admitted) .putMembershipVersion(tenantUuid, "1") .setMembershipAuthorityGeneration("1") .setMembershipBaseline(baseline) @@ -253,8 +268,10 @@ private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( .setIssuanceFence("1") .addAllOutboxCheckpoints(checkpoints) .setEvaluatedAt(EVALUATED_AT); - if (exists) { + if (admitted) { response.addRoles("player"); + } + if (exists) { response.addOutboxSourceEvidence( RuntimeOutboxSourceEvidence.newBuilder() .setOutboxStreamKey(membershipStream) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 8a088c5edc..b056569549 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -798,6 +798,10 @@ private boolean isValidMembershipLifecycleEvidence( && response.getGameplayAdmissionAllowed() && response.getRolesList().contains("player") && hasPositiveMembershipVersion(response); + case "INACTIVE" -> + response.getMembershipExists() + && !response.getGameplayAdmissionAllowed() + && hasPositiveMembershipVersion(response); default -> false; }; } @@ -880,18 +884,18 @@ private static boolean hasCompleteMembershipAuthorityCarrier( if (!actualStreamKeys.equals(expectedStreamKeys)) { return false; } - boolean positive = "ACTIVE".equals(response.getMembershipLifecycleState()); + boolean committedMembership = !"MISSING".equals(response.getMembershipLifecycleState()); for (String streamKey : expectedStreamKeys) { String sequence = checkpointSequences.get(streamKey); if (streamKey.equals(membershipStream)) { - if (positive != isPositiveCanonicalDecimal(sequence)) { + if (committedMembership != isPositiveCanonicalDecimal(sequence)) { return false; } } else if (!"0".equals(sequence)) { return false; } } - if (!positive) { + if (!committedMembership) { return "MISSING".equals(response.getMembershipLifecycleState()) && !response.getMembershipExists() && !response.getGameplayAdmissionAllowed() @@ -906,7 +910,8 @@ private static boolean hasCompleteMembershipAuthorityCarrier( if (response.getOutboxSourceEvidenceCount() != 1 || !response.getMembershipExists() - || !response.getGameplayAdmissionAllowed() + || (response.getGameplayAdmissionAllowed() + != "ACTIVE".equals(response.getMembershipLifecycleState())) || response.getMembershipVersionCount() != 1 || !hasPositiveMembershipVersion(response)) { return false; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 7810427d75..a33484758f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -1464,6 +1464,30 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } + @Test + void evidencedInactiveMembershipRequiresExplicitJoinWithoutReadingEntityRoster() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .inactive(123L, 22L, "4"), + invocation.getArgument(0))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + Mockito.verifyNoInteractions(entityManagementClient); + } + @ParameterizedTest @ValueSource(strings = {"ENTITLEMENT_UNAVAILABLE", "AUTH_UNAVAILABLE"}) void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java index 9a8a2db4c0..8912a6860c 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -29,6 +29,11 @@ public static GetTenantMembershipForRuntimeResponse missing(long accountId, long return complete(accountId, tenantId, false, "MISSING", false, "1"); } + public static GetTenantMembershipForRuntimeResponse inactive( + long accountId, long tenantId, String membershipVersion) { + return complete(accountId, tenantId, true, "INACTIVE", false, membershipVersion); + } + public static GetTenantMembershipForRuntimeResponse echoRequestId( GetTenantMembershipForRuntimeResponse response, PlayerExecutionContext request) { return response.toBuilder().setRequestId(request.getRequestId()).build(); @@ -118,8 +123,10 @@ private static GetTenantMembershipForRuntimeResponse complete( .setIssuanceFence("1") .addAllOutboxCheckpoints(checkpoints) .setEvaluatedAt(EVALUATED_AT); - if (exists) { + if (admitted) { response.addRoles("player"); + } + if (exists) { response.addOutboxSourceEvidence( RuntimeOutboxSourceEvidence.newBuilder() .setOutboxStreamKey(membershipStream) From e39c31b1f42b202c26c34ba83ddf6e4c8247699e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:00:59 +1300 Subject: [PATCH 14/46] Record composed bare LOGIN proof and remaining activation gate --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 5e2b91aec4..9944f12359 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,6 +34,8 @@ The approved first-party bare-`LOGIN` private-delegation exchange is not live. A The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests currently fail at their shared helper's old successful-bare-LOGIN assertion; there is no supported authenticated first-party fixture until the Account exchange works, and the internal text fixture cannot prove structured public output. They remain an explicit runtime proof gate rather than being disabled or counted as passing. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. +Manual CI run `36292018666` on prior #2881 head `aa5d73c05a408ba152ac05f4298cadd52430b831` passed its strict Account evidence gate: all 24 JOIN PostgreSQL cases and seven V37 bare-LOGIN exchange cases executed with no skips or failures, including the required targeted map-shape and transaction tests. Its aggregate gate remained red: seven first-party success assertions still assume the disabled exchange, and four Game Session/TCP Proxy cross-service failures arose from #2880's incomplete `INACTIVE` carrier handling; ten hosted smoke-tool Ruff errors and the EA-3.1 proof-link rule also failed. The #2880 consumer/stub correction has been merged normally into #2881 with its unique non-tracker patch ID unchanged. A new signed-context wire-negative test for bare `LOGIN` and following `PLAY` compiles but skipped locally without Docker; the seven positive scenarios remain unchanged. The corrected composed local module/doc gate passed, with 381 Account and 1,641 Game Session unit tests executed, but all 87 Account PostgreSQL cases and 40/41 Game Session cross-service cases skipped. Corrected-head hosted proof remains necessary, and neither membership nor credential runtime path is enabled. + The #2876 candidate also adds a local AES-256-GCM response-envelope primitive backed by one Account-only versioned mounted-file ring, with separate connect-token and bare-`LOGIN` purpose keys, key IDs, current-write/older-decrypt rotation, and length-framed exact-operation evidence. Local unit tests execute both-purpose round trips, old-key recovery/removal, wrong-purpose and wrong-operation rejection, and missing/malformed-ring denial. V35 adds an unwired connect-token issuance operation/envelope table with exact identity, digest, pending/terminal state and encrypted-envelope readback; its six PostgreSQL cases reached execution in a prior hosted run, four passed and two failed on a timestamp bind. The corrected-head Account integration task passed, but its success artifact lacks per-test XML. An operator bootstrap candidate creates a protected initial source record once in an owner-only directory and provides an explicit separate rotation action that retains every old purpose key, adds new distinct write keys, and binds a new generation to the previous one without overwriting either source. A separate materializer candidate consumes exact manifest bytes, environment, namespace, generation/predecessor, immutable source-created freshness anchor, and expiry; it verifies retry-stable Secret readback and preserves old decrypt-only keys. The 28 focused materializer tests and combined 139-test developer-tool suite, Ruff, and syntax checks pass locally. Exact-head CI run `36254410583` passed Account Build/Test; its integration task ran and its coverage artifact lists 20 integration classes, but the absent per-case XML prevents an exact executed/skipped count. The aggregate CI gate is red from unchanged Game Session Friends assertions, hosted smoke-tool lint, and an EA-3.1 proof-link check outside #2876's unique diff. Actual protected durable custody, source backup and writer RBAC, deployment/readiness wiring, a live mounted Secret, executed rotation, and proven safe decrypt-only key retirement are still absent. There is no corresponding bare-`LOGIN` operation, wired producer/consumer, or lost-response/live rollout proof. Neither credential path is enabled by the primitive, tool candidates, or V35, and an unavailable key may never authorize reminting. The separately specified credential-bearing `Authenticate` exact-retry envelope is also unimplemented; this two-purpose primitive does not supply its key or enable that operation. At published #2876 head `774356d5a66846a535726f680aa54ce85669160b`, manual CI run `36257232596` passed Account Build/Test, but `:account-service:integrationTest` was `FROM-CACHE`; it does not demonstrate fresh PostgreSQL execution. The gate failed on seven of 39 Game Session Friends/WebSocket cross-service cases, ten hosted smoke-tool Ruff errors, and the EA-3.1 executable-proof-link check. The failing paths are outside #2876's unique diff, but CI alone does not establish the Game Session root cause or merge readiness. The proposed required Account Secret mount remains unpublished: its rendered-manifest contract passes locally, but no environment source, trusted-writer receipt, or readiness proof exists, and deployment cannot safely require the absent Secret. A Game Session sequence-only event-consumer draft was discarded because the accepted contract requires authenticated same-snapshot tuple, fence, membership baseline, complete checkpoints, and source evidence; the current wire does not provide those fields. Runtime RPCs remain denied. From 93bc4a45fa940f600d8f4d97d9aefdf20b424f2a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:07:21 +1300 Subject: [PATCH 15/46] Prove concurrent bare LOGIN exchange first writer --- ...oginExchangeRepositoryIntegrationTest.java | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java index de1852f5d8..52ab80a535 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java @@ -3,8 +3,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.List; import java.util.Map; 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 java.util.function.Supplier; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; @@ -144,6 +151,87 @@ void sourceMustBeCommittedAndFirstWriterOwnsTheExchangeIdentity() { .hasMessageContaining("not committed"); } + @Test + void concurrentExactExchangeClaimsHaveOneTerminalFirstWriter() throws Exception { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(70); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Callable exchange = + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Exchange claim race did not start together"); + } + return inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + if (claim.disposition() + == AccountBareLoginExchangeRepository.ClaimDisposition.CLAIMED) { + AccountEnvelopeBinding binding = + binding(claim.operation().operationId(), identity, requestDigest, 71); + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-race", + digest(80), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-race", + digest(80), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + } + return claim; + }); + }; + Future first = executor.submit(exchange); + Future second = executor.submit(exchange); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + var results = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + assertThat(results) + .extracting(AccountBareLoginExchangeRepository.ClaimResult::disposition) + .containsExactlyInAnyOrder( + AccountBareLoginExchangeRepository.ClaimDisposition.CLAIMED, + AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + assertThat(results.get(0).operation().operationId()) + .isEqualTo(results.get(1).operation().operationId()); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()) + .lifecycle()) + .isEqualTo(Lifecycle.COMMITTED); + AccountEnvelopeBinding binding = + binding(results.get(0).operation().operationId(), identity, requestDigest, 71); + assertThat( + inTransaction( + context.transaction(), + () -> + context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .isPresent(); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + @Test void pendingEvidenceThenTerminalSuccessReadBacksExactPurposeBoundEnvelope() { TestContext context = newTestContext(); From 3272a1fe0e38a2d2d7fff19995f0075adf58b50a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:15:12 +1300 Subject: [PATCH 16/46] Prove stored bare LOGIN envelope recovery across retry --- .../player-access-and-session.md | 2 + ...oginExchangeRepositoryIntegrationTest.java | 89 +++++++++++++++++++ 2 files changed, 91 insertions(+) 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 9944f12359..1e78acbb57 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -36,6 +36,8 @@ The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: Manual CI run `36292018666` on prior #2881 head `aa5d73c05a408ba152ac05f4298cadd52430b831` passed its strict Account evidence gate: all 24 JOIN PostgreSQL cases and seven V37 bare-LOGIN exchange cases executed with no skips or failures, including the required targeted map-shape and transaction tests. Its aggregate gate remained red: seven first-party success assertions still assume the disabled exchange, and four Game Session/TCP Proxy cross-service failures arose from #2880's incomplete `INACTIVE` carrier handling; ten hosted smoke-tool Ruff errors and the EA-3.1 proof-link rule also failed. The #2880 consumer/stub correction has been merged normally into #2881 with its unique non-tracker patch ID unchanged. A new signed-context wire-negative test for bare `LOGIN` and following `PLAY` compiles but skipped locally without Docker; the seven positive scenarios remain unchanged. The corrected composed local module/doc gate passed, with 381 Account and 1,641 Game Session unit tests executed, but all 87 Account PostgreSQL cases and 40/41 Game Session cross-service cases skipped. Corrected-head hosted proof remains necessary, and neither membership nor credential runtime path is enabled. +Corrected #2881 head `e39c31b1f42b202c26c34ba83ddf6e4c8247699e` ran in CI `36293121086`: the strict Account gate passed all 26 JOIN and seven V37 PostgreSQL cases with zero skips/failures, including #2880's two new same-fence snapshot cases; the signed-context bare-`LOGIN` denial test executed and passed. Game Session's 41 cross-service cases had exactly seven failures, all existing first-party success scenarios awaiting the Account exchange. TCP Proxy and all other service Build/Test jobs passed. Python Script Validation and the EA-3.1 Dev Tool Contract Check remain red outside this unique change. Two additional V37 repository/crypto tests now locally compile: concurrent exact first-writer terminalization and decrypting the exact retained envelope after a simulated lost response. All 89 local Account integration cases skip without Docker, so these two new tests need hosted execution. They prove storage/recovery primitives only, not Account-issued JWT, caller-bound exchange, live ring custody, or activation. + The #2876 candidate also adds a local AES-256-GCM response-envelope primitive backed by one Account-only versioned mounted-file ring, with separate connect-token and bare-`LOGIN` purpose keys, key IDs, current-write/older-decrypt rotation, and length-framed exact-operation evidence. Local unit tests execute both-purpose round trips, old-key recovery/removal, wrong-purpose and wrong-operation rejection, and missing/malformed-ring denial. V35 adds an unwired connect-token issuance operation/envelope table with exact identity, digest, pending/terminal state and encrypted-envelope readback; its six PostgreSQL cases reached execution in a prior hosted run, four passed and two failed on a timestamp bind. The corrected-head Account integration task passed, but its success artifact lacks per-test XML. An operator bootstrap candidate creates a protected initial source record once in an owner-only directory and provides an explicit separate rotation action that retains every old purpose key, adds new distinct write keys, and binds a new generation to the previous one without overwriting either source. A separate materializer candidate consumes exact manifest bytes, environment, namespace, generation/predecessor, immutable source-created freshness anchor, and expiry; it verifies retry-stable Secret readback and preserves old decrypt-only keys. The 28 focused materializer tests and combined 139-test developer-tool suite, Ruff, and syntax checks pass locally. Exact-head CI run `36254410583` passed Account Build/Test; its integration task ran and its coverage artifact lists 20 integration classes, but the absent per-case XML prevents an exact executed/skipped count. The aggregate CI gate is red from unchanged Game Session Friends assertions, hosted smoke-tool lint, and an EA-3.1 proof-link check outside #2876's unique diff. Actual protected durable custody, source backup and writer RBAC, deployment/readiness wiring, a live mounted Secret, executed rotation, and proven safe decrypt-only key retirement are still absent. There is no corresponding bare-`LOGIN` operation, wired producer/consumer, or lost-response/live rollout proof. Neither credential path is enabled by the primitive, tool candidates, or V35, and an unavailable key may never authorize reminting. The separately specified credential-bearing `Authenticate` exact-retry envelope is also unimplemented; this two-purpose primitive does not supply its key or enable that operation. At published #2876 head `774356d5a66846a535726f680aa54ce85669160b`, manual CI run `36257232596` passed Account Build/Test, but `:account-service:integrationTest` was `FROM-CACHE`; it does not demonstrate fresh PostgreSQL execution. The gate failed on seven of 39 Game Session Friends/WebSocket cross-service cases, ten hosted smoke-tool Ruff errors, and the EA-3.1 executable-proof-link check. The failing paths are outside #2876's unique diff, but CI alone does not establish the Game Session root cause or merge readiness. The proposed required Account Secret mount remains unpublished: its rendered-manifest contract passes locally, but no environment source, trusted-writer receipt, or readiness proof exists, and deployment cannot safely require the absent Secret. A Game Session sequence-only event-consumer draft was discarded because the accepted contract requires authenticated same-snapshot tuple, fence, membership baseline, complete checkpoints, and source evidence; the current wire does not provide those fields. Runtime RPCs remain denied. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java index 52ab80a535..51241ec70f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java @@ -3,6 +3,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; @@ -22,6 +26,7 @@ import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -29,6 +34,7 @@ import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -232,6 +238,89 @@ void concurrentExactExchangeClaimsHaveOneTerminalFirstWriter() throws Exception } } + @Test + void lostExchangeResponseRecoversExactEncryptedResultFromDurableReadback( + @TempDir Path temporaryDirectory) throws Exception { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(72); + byte[] originalResult = "original-private-delegation-result".getBytes(StandardCharsets.UTF_8); + byte[] connectKey = new byte[32]; + byte[] bareLoginKey = new byte[32]; + java.util.Arrays.fill(connectKey, (byte) 1); + java.util.Arrays.fill(bareLoginKey, (byte) 2); + Path manifest = temporaryDirectory.resolve("manifest.v1"); + Files.writeString( + manifest, + "version=1\nactiveKeyId=k1\n" + + "key:k1:bare-login=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(bareLoginKey) + + "\nkey:k1:connect-token=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(connectKey) + + "\n", + StandardCharsets.US_ASCII); + AccountEnvelopeCrypto writer = new AccountEnvelopeCrypto(manifest); + + AccountEnvelopeBinding binding = + inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + AccountEnvelopeBinding issuedBinding = + binding(claim.operation().operationId(), identity, requestDigest, 73); + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-recovery", + digest(80), + issuedBinding.contextEvidenceDigest(), + issuedBinding.authorityTupleDigest(), + issuedBinding.issuanceFenceDigest(), + issuedBinding.postconditionDigest()); + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-recovery", + digest(80), + issuedBinding, + writer.encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + issuedBinding, + originalResult)); + return issuedBinding; + }); + + var retry = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + assertThat(retry.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + assertThat(retry.operation().lifecycle()).isEqualTo(Lifecycle.COMMITTED); + var stored = + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, requestDigest, binding) + .orElseThrow()); + AccountEnvelopeCrypto recoveryReader = new AccountEnvelopeCrypto(manifest); + assertThat( + recoveryReader.decrypt( + stored.envelope(), AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, stored.binding())) + .containsExactly(originalResult); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().find(identity, digest(74)))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdempotencyConflictException.class); + } + @Test void pendingEvidenceThenTerminalSuccessReadBacksExactPurposeBoundEnvelope() { TestContext context = newTestContext(); From d4cc6654b5395086e09428d6f41658022eb87852 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:14:18 +1300 Subject: [PATCH 17/46] fix(game-session): clear stale subject on failed bare login --- .github/workflows/ci.yml | 1 + .../command/text/LoginCommandHandler.java | 33 ++++ .../command/text/LoginCommandHandlerTest.java | 182 ++++++++++++++++++ 3 files changed, 216 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5f5fda367f..e0c5c4b303 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -390,6 +390,7 @@ jobs: bash ./dev-tools/tests/secret-compliance-contract.sh bash ./dev-tools/tests/ensure-local-compose-env-contract.sh bash ./dev-tools/tests/smoke-image-env-contract.sh + bash ./dev-tools/tests/gradle-proof-tooling-contract.sh bash ./dev-tools/tests/architecture-doc-contracts.sh bash ./dev-tools/tests/lint-yaml-contract.sh python3 -m unittest discover -s dev-tools/validation -p 'test_*.py' diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 581eaf06e7..88b98a2d53 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.CommandService; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -263,9 +264,41 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI return failure("CONNECT_SCOPE_MISMATCH", "Connect scope invalid"); } + if (existingSession != null + && existingSession.accountId() > 0L + && (existingSession.accountId() != verifiedContext.accountId() + || existingSession.tenantId() != verifiedContext.tenantId())) { + clearPreviousSessionForVerifiedContext(numericSessionId, existingSession, verifiedContext); + } return failure(AUTH_UNAVAILABLE_CODE, "Authentication service unavailable"); } + private void clearPreviousSessionForVerifiedContext( + long sessionId, SessionContext existingSession, FirstPartyConnectContext verifiedContext) { + if (existingSession.hasGameplayBinding()) { + gameplayPresenceLifecycleService.clearGameplayBinding(existingSession, "LOGIN_FAILED"); + } + sessionContextService.save( + new SessionContext( + sessionId, + verifiedContext.tenantId(), + 0L, + null, + 0L, + null, + 0L, + null, + null, + existingSession.localeTag(), + verifiedContext.gameInstanceId(), + verifiedContext.worldSlug(), + verifiedContext.realmSlug(), + verifiedContext.pointerVersion(), + null, + verifiedContext.connectScopeId(), + verifiedContext.connectRequestId())); + } + private void persistSessionContext( long sessionId, long tenantId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index d312f6615b..dc195b540f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -17,10 +17,14 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.EntityManagementClient; +import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; +import net.firedevops.firemud.gamesession.config.GameLogicProperties; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.presentation.ErrorOutput; @@ -33,6 +37,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; @@ -443,6 +448,147 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { assertEquals(77L, instance.getOwnerAccountId()); } + @Test + void bareLoginForDifferentVerifiedSubjectClearsOldAccountBeforeReturningUnavailable() { + TextCommand loginCommand = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext accountA = staleGameplayContext(1L); + stubMutableSessionContext(accountA); + FirstPartyConnectContext verifiedAccountBContext = + new FirstPartyConnectContext( + 99L, + 33L, + "demo", + "production", + 2L, + 1L, + "scope-account-b", + "jti-account-b", + "request-account-b", + "gateway-account-b"); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn(Optional.of(verifiedAccountBContext)); + GameInstance instance = buildInstance(2L, 33L, 77L); + when(gameInstanceRepository.findById(2L)).thenReturn(Optional.of(instance)); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(33L, 2L)) + .thenReturn(List.of(pointer("demo", "production", 33L, 2L, 1L))); + + LoginCommandHandlingResult result = handler.handle("1", loginCommand, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + ArgumentCaptor savedContext = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(savedContext.capture()); + SessionContext accountBShell = savedContext.getValue(); + assertEquals(33L, accountBShell.tenantId()); + assertEquals(0L, accountBShell.accountId()); + assertNull(accountBShell.loginName()); + assertNull(accountBShell.jwt()); + assertFalse(accountBShell.hasGameplayBinding()); + assertEquals(2L, accountBShell.bootstrapGameInstanceId()); + assertEquals("demo", accountBShell.worldSlug()); + assertEquals("production", accountBShell.realmSlug()); + assertEquals(1L, accountBShell.pointerVersion()); + assertNull(accountBShell.playableStateScope()); + assertEquals("scope-account-b", accountBShell.connectScopeId()); + assertEquals("request-account-b", accountBShell.connectRequestId()); + verify(gameplayPresenceLifecycleService).clearGameplayBinding(accountA, "LOGIN_FAILED"); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + assertEquals(Optional.of(verifiedAccountBContext), firstPartyConnectContextRegistry.find(1L)); + + PlayCommandHandlingResult playResult = + createPlayCommandHandler() + .handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertFalse(playResult.commandResult().accepted()); + assertEquals("LOGIN_REQUIRED", playResult.commandResult().errorCode()); + } + + @Test + void bareLoginForSameVerifiedSubjectPreservesRetryableSessionState() { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext existing = staleGameplayContext(1L); + stubSessionContext(existing); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn( + Optional.of( + new FirstPartyConnectContext( + existing.accountId(), + existing.tenantId(), + "demo", + "production", + 1L, + 1L, + "scope-account-a", + "jti-account-a", + "request-account-a", + "gateway-account-a"))); + GameInstance instance = buildInstance(1L, 22L, 77L); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(any(SessionContext.class), anyString()); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + assertEquals(77L, existing.accountId()); + assertEquals(AUTH_TOKEN, existing.jwt()); + assertTrue(existing.hasGameplayBinding()); + assertEquals("scope-stale", existing.connectScopeId()); + assertEquals("req-stale", existing.connectRequestId()); + } + + @Test + void bareLoginForSameAccountInDifferentTenantClearsOldTenantBeforeReturningUnavailable() { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext accountA = staleGameplayContext(1L); + stubMutableSessionContext(accountA); + FirstPartyConnectContext verifiedTenantBContext = + new FirstPartyConnectContext( + accountA.accountId(), + 33L, + "demo", + "production", + 2L, + 1L, + "scope-tenant-b", + "jti-tenant-b", + "request-tenant-b", + "gateway-tenant-b"); + when(firstPartyConnectContextRegistry.find(1L)).thenReturn(Optional.of(verifiedTenantBContext)); + when(gameInstanceRepository.findById(2L)) + .thenReturn(Optional.of(buildInstance(2L, 33L, accountA.accountId()))); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(33L, 2L)) + .thenReturn(List.of(pointer("demo", "production", 33L, 2L, 1L))); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + ArgumentCaptor savedContext = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(savedContext.capture()); + SessionContext tenantBShell = savedContext.getValue(); + assertEquals(33L, tenantBShell.tenantId()); + assertEquals(0L, tenantBShell.accountId()); + assertNull(tenantBShell.jwt()); + assertFalse(tenantBShell.hasGameplayBinding()); + assertEquals(2L, tenantBShell.bootstrapGameInstanceId()); + assertEquals("scope-tenant-b", tenantBShell.connectScopeId()); + assertEquals("request-tenant-b", tenantBShell.connectRequestId()); + verify(gameplayPresenceLifecycleService).clearGameplayBinding(accountA, "LOGIN_FAILED"); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + assertEquals(Optional.of(verifiedTenantBContext), firstPartyConnectContextRegistry.find(1L)); + + PlayCommandHandlingResult playResult = + createPlayCommandHandler() + .handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertFalse(playResult.commandResult().accepted()); + assertEquals("LOGIN_REQUIRED", playResult.commandResult().errorCode()); + } + @Test void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { TextCommand command = @@ -1409,6 +1555,42 @@ private GameInstance buildInstance(long id, long tenantId, long ownerAccountId) return instance; } + private void stubMutableSessionContext(SessionContext context) { + AtomicReference persistedContext = new AtomicReference<>(context); + when(sessionContextService.findBySessionId(1L)) + .thenAnswer(invocation -> Optional.ofNullable(persistedContext.get())); + when(sessionContextService.findByTenantAndSessionId(anyLong(), eq(1L))) + .thenAnswer( + invocation -> { + long requestedTenantId = invocation.getArgument(0); + return Optional.ofNullable(persistedContext.get()) + .filter(saved -> saved.tenantId() == requestedTenantId); + }); + Mockito.doAnswer( + invocation -> { + persistedContext.set(invocation.getArgument(0)); + return null; + }) + .when(sessionContextService) + .save(any(SessionContext.class)); + } + + private PlayCommandHandler createPlayCommandHandler() { + return new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + GameplayWorldCatalog.forWorldViews(List.of()), + new GameLogicProperties(), + accountClient, + Mockito.mock(EntityManagementClient.class), + Mockito.mock(ModerationPolicyClient.class), + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + Mockito.mock(ScriptEventPublisher.class), + meterRegistry); + } + private static String joinedOutputText(List outputs) { return outputs.stream() .map(PlayerOutput::text) From d62abd5508acb4bbbd767fc8adcbe1b98ea44b34 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:29:37 +1300 Subject: [PATCH 18/46] Bound membership snapshot freshness and correct typed request status --- .../account-service/api-contracts.md | 6 +- .../account-service/runtime-and-data.md | 6 +- .../command/text/PlayCommandHandler.java | 6 +- .../command/text/PlayCommandHandlerTest.java | 103 +++++++++++------- 4 files changed, 74 insertions(+), 47 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 89e93aaa0e..31842945ae 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -115,7 +115,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. 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. +- `GetTenantMembershipForRuntime` (request carrying typed `PlayerExecutionContext`) – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. The proto and Game Session consumer now carry the typed player context, but the Account handler still fails closed before the candidate producer/data read. Game Session performs structural lifecycle and authority-carrier checks; one fresh atomic Account membership snapshot and complete producer/consumer proof remain incomplete. - `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. 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. @@ -257,8 +257,8 @@ 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. +- `GetTenantMembershipForRuntime` (request carrying `PlayerExecutionContext`) 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 status: the membership proto and Game Session consumer now carry typed `PlayerExecutionContext`, but Account's handler still denies before producer/data access with `FAILED_PRECONDITION`. The held-back candidate producer/consumer path and complete snapshot proof remain incomplete. The target internal-only boundary remains canonical; readiness still requires the workload, caller/target, and cross-tenant negative proof for the enabled path. - `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 d2cb17dfb4..b88a5e868c 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -24,9 +24,9 @@ The current public registration path creates only a global Account row and a pla Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. Game Session `PLAY` validates lifecycle consistency against existence, admission, and version fields and rejects a missing or nonpositive membership authority generation. It does not validate `authorityAvailability`, roles, the complete `authorityTuple`, or `outboxCheckpoints`; those fields remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. The current entitlement response likewise lacks the complete Account-authenticated bundle, caller/target binding, authority tuple, billing cutoff, checkpoint set, and fence evidence required by the target contract. Its consumer checks only the represented tenant, positive entitlement version, and evaluation-time fields; this subset does not establish complete snapshot or fence proof. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes fail with `FAILED_PRECONDITION` before Account reads until a typed verified player/target contract and consumer are implemented. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public REST realm discovery, character listing, and connect-token issuance now fail closed even when the legacy four-field grant row exists, because it cannot prove the current lifecycle and state generation. The target lifecycle-qualified grant authority is not implemented; public-production REST behavior remains unchanged. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. Game Session `PLAY` validates lifecycle consistency against existence, admission, and version fields and rejects a missing or nonpositive membership authority generation. It does not validate `authorityAvailability`, roles, the complete `authorityTuple`, or `outboxCheckpoints`; those fields remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. The current entitlement response likewise lacks the complete Account-authenticated bundle, caller/target binding, authority tuple, billing cutoff, checkpoint set, and fence evidence required by the target contract. Its consumer checks only the represented tenant, positive entitlement version, and evaluation-time fields; this subset does not establish complete snapshot or fence proof. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present. The membership proto and Game Session consumer now carry typed `PlayerExecutionContext`, but Account's handler still returns `FAILED_PRECONDITION` before producer/data access; the held-back candidate producer/consumer path and its complete snapshot proof remain incomplete. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public REST realm discovery, character listing, and connect-token issuance now fail closed even when the legacy four-field grant row exists, because it cannot prove the current lifecycle and state generation. The target lifecycle-qualified grant authority is not implemented; public-production REST behavior remains unchanged. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. -The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. Account still cannot treat their bare request-body `accountId`/`tenantId` as verified player or lifecycle context. These runtime reads and the similarly bare realm-grant read must reject before Account data access until the exact Game Session or World Management peer, typed caller/target context, and applicable private delegation are carried and verified. The Game Session consumer still sends the older request shape, so this containment is not a working admission path or proof of the target membership/entitlement snapshot. +The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. The membership request now carries typed `PlayerExecutionContext`, and Game Session sends that typed context; Account's handler still denies before producer/data access with `FAILED_PRECONDITION`. The held-back candidate producer/consumer path remains incomplete, so this typed request is not a working admission path or proof of the target membership/entitlement snapshot. The entitlement and realm-grant reads retain their local request shapes and must likewise remain denied until their exact caller/target contracts are carried and verified. An unwired Account membership-snapshot reader now forms an exact one-tenant version map, a complete ordered four-stream checkpoint set, and separate positive membership source-event evidence only from a fenced local transaction. Its issuer, account, and tenant streams can presently prove sequence zero only while their durable generation and source-version baselines remain at one and no committed outbox head exists; advanced upstream history fails closed until its source-event proof is implemented. A never-joined pair's positive version/generation baseline and absence history are read under the same fence; a changed account-local issuance fence is preserved. This reader is not the gRPC response, does not authenticate the runtime caller, and does not enable the denied method or Game Session admission. @@ -283,7 +283,7 @@ Current `AccountRealmAccessGrant` persistence is limited to the legacy four-fiel ### Runtime Implementation Status and Drift -- Account-first bootstrap 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. Game Session membership, grant, and entitlement gRPC calls currently fail with `FAILED_PRECONDITION` before Account data access; valid-route text `PLAY` consequently returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Those downstream text outcomes are conditional branches exercised with mocked successful Account responses, not current end-to-end behavior; see [Authentication Implementation Status](../../system-architecture-authentication.md#implementation-status). Account REST connect-token issuance and character discovery are separate paths with distinct current checks. Issuance distinguishes explicit `INACTIVE` from other present non-admitting states: eligible public-production missing or `INACTIVE` membership may return `JOIN_REQUIRED`; non-public missing or `INACTIVE` membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`, an `ACTIVE` non-admitting membership is rejected, and a missing non-public grant returns `REALM_ACCESS_DENIED`. Character discovery uses local membership-row existence and admission after target and entitlement checks; only missing eligible public membership may return `JOIN_REQUIRED`, while present non-admitting membership is denied. These paths do not establish the target private/playtest outcome. The local explicit `JOIN`/`Join & Play` operation, Account route/RPC, controller, and Game Session text dispatch exist without complete direct-text proof. The bounded Account-owned worker terminalizes an abandoned `PENDING` JOIN only on exact positive operation/scope/membership/audit readback; scope expiry, absent evidence, and capped automatic attempts leave uncertainty pending with diagnostics and caller retry. PostgreSQL exact-final-head lost-acknowledgement/concurrency proof, recovery after unknown JOIN commits, direct text-to-Logging end-to-end proof, membership-authority-generation reread at connect-token issuance, and broader reconnect/admission-pointer and operator tooling remain incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. +- Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime` (typed `PlayerExecutionContext` request), `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Game Session membership, grant, and entitlement gRPC calls currently fail with `FAILED_PRECONDITION` before Account data access; valid-route text `PLAY` consequently returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Those downstream text outcomes are conditional branches exercised with mocked successful Account responses, not current end-to-end behavior; see [Authentication Implementation Status](../../system-architecture-authentication.md#implementation-status). Account REST connect-token issuance and character discovery are separate paths with distinct current checks. Issuance distinguishes explicit `INACTIVE` from other present non-admitting states: eligible public-production missing or `INACTIVE` membership may return `JOIN_REQUIRED`; non-public missing or `INACTIVE` membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`, an `ACTIVE` non-admitting membership is rejected, and a missing non-public grant returns `REALM_ACCESS_DENIED`. Character discovery uses local membership-row existence and admission after target and entitlement checks; only missing eligible public membership may return `JOIN_REQUIRED`, while present non-admitting membership is denied. These paths do not establish the target private/playtest outcome. The local explicit `JOIN`/`Join & Play` operation, Account route/RPC, controller, and Game Session text dispatch exist without complete direct-text proof. The bounded Account-owned worker terminalizes an abandoned `PENDING` JOIN only on exact positive operation/scope/membership/audit readback; scope expiry, absent evidence, and capped automatic attempts leave uncertainty pending with diagnostics and caller retry. PostgreSQL exact-final-head lost-acknowledgement/concurrency proof, recovery after unknown JOIN commits, direct text-to-Logging end-to-end proof, membership-authority-generation reread at connect-token issuance, and broader reconnect/admission-pointer and operator tooling 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/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 425ad4d2ed..0952451fc2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1204,7 +1204,11 @@ private boolean isSafeMembershipAuthorityResponse( return false; } try { - Instant.parse(response.getEvaluatedAt()); + Instant evaluatedAt = Instant.parse(response.getEvaluatedAt()); + Instant now = Instant.now(); + if (evaluatedAt.isAfter(now) || !evaluatedAt.isAfter(now.minus(15, ChronoUnit.SECONDS))) { + return false; + } } catch (DateTimeParseException ex) { return false; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 3d971b2cec..faf372b400 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -108,8 +108,9 @@ void setUp() { invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1"), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1")), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1054,13 +1055,9 @@ void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding( invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net - .firedevops - .firemud - .gamesession - .support - .RuntimeMembershipTestFixtures - .active(123L, 22L, "2") + freshMembership( + net.firedevops.firemud.gamesession.support + .RuntimeMembershipTestFixtures.active(123L, 22L, "2")) .toBuilder() .setGameplayAdmissionAllowed(false) .build(), @@ -1088,8 +1085,9 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L)), invocation.getArgument(0))); PlayCommandHandlingResult result = @@ -1125,8 +1123,9 @@ void playNonPublicInactiveMembershipDoesNotUsePublicJoin() { invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3"), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .inactive(123L, 22L, "3")), invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1366,8 +1365,9 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L)), invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1393,8 +1393,9 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta .thenAnswer( invocation -> { var response = - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L); + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L)); var malformedLifecycle = response.toBuilder() .setMembershipLifecycleState(lifecycleState) @@ -1428,10 +1429,12 @@ void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleSt invocation -> { var response = "INACTIVE".equals(lifecycleState) - ? net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3") - : net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L); + ? freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .inactive(123L, 22L, "3")) + : freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L)); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( response.toBuilder().setGameplayAdmissionAllowed(true).build(), @@ -1457,8 +1460,9 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "4"), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .inactive(123L, 22L, "4")), invocation.getArgument(0))); PlayCommandHandlingResult result = @@ -1492,8 +1496,9 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1529,8 +1534,9 @@ void playBillingDenialMasksMissingPublicMembership() { invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1566,8 +1572,9 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1632,8 +1639,9 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L), + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1660,8 +1668,9 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti entityManagementClient, sessionContextService, gameplayPresenceLifecycleService); } - @Test - void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { + @ParameterizedTest + @ValueSource(strings = {"malformed", "future", "stale"}) + void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -1670,10 +1679,16 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { .thenAnswer( invocation -> { var response = - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 123L, 22L, "1") + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1")) .toBuilder() - .setEvaluatedAt("not-a-timestamp") + .setEvaluatedAt( + switch (defect) { + case "future" -> Instant.now().plusSeconds(1L).toString(); + case "stale" -> Instant.now().minus(16L, ChronoUnit.SECONDS).toString(); + default -> "not-a-timestamp"; + }) .build(); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId(response, invocation.getArgument(0)); @@ -1692,6 +1707,7 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { Mockito.verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verifyNoInteractions(entityManagementClient); } @Test @@ -1706,8 +1722,9 @@ void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1"), + freshMembership( + net.firedevops.firemud.gamesession.support + .RuntimeMembershipTestFixtures.active(123L, 22L, "1")), invocation.getArgument(0)); return response.toBuilder().setRequestId("wrong-request-id").build(); }); @@ -1737,8 +1754,9 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1"), + freshMembership( + net.firedevops.firemud.gamesession.support + .RuntimeMembershipTestFixtures.active(123L, 22L, "1")), invocation.getArgument(0)); return response.toBuilder().clearMembershipAuthorityGeneration().build(); }); @@ -2029,6 +2047,11 @@ private static String joinedOutputText(List outputs) { .orElse(null); } + private static GetTenantMembershipForRuntimeResponse freshMembership( + GetTenantMembershipForRuntimeResponse response) { + return response.toBuilder().setEvaluatedAt(Instant.now().toString()).build(); + } + private void assertIdentityUnavailableWithoutMutation(PlayCommandHandlingResult result) { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) From 9c2147039f47649580b6e607d3e09e55fe66be1b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:44:33 +1300 Subject: [PATCH 19/46] test(game-session): prove bare first-party login stays denied --- ...ommunicationWebSocketCrossServiceTest.java | 13 ++- ...essionWebSocketHandlerIntegrationTest.java | 92 ++++++++----------- 2 files changed, 50 insertions(+), 55 deletions(-) diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 09d9ddb28a..b080edd672 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -1071,9 +1071,18 @@ private GameplayWebSocketDriver openFirstPartyGameplayClient(String transportSes JsonNode login = awaitStructuredCommand(client, 0, "LOGIN"); GameplayStructuredCommandAssertions.requireStructuredCommand( login, "LOGIN", "login", "META", "SESSION"); - assertThat(login.path("accepted").asBoolean()).withFailMessage(login.toPrettyString()).isTrue(); + assertThat(login.path("accepted").asBoolean()).isFalse(); + assertThat(login.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); + + client.send("LOGIN emberline@example.com swordfish"); + JsonNode credentialLogin = awaitStructuredCommand(client, 1, "LOGIN"); + GameplayStructuredCommandAssertions.requireStructuredCommand( + credentialLogin, "LOGIN", "login", "META", "SESSION"); + assertThat(credentialLogin.path("accepted").asBoolean()) + .withFailMessage(credentialLogin.toPrettyString()) + .isTrue(); client.send("PLAY demo"); - JsonNode play = awaitStructuredCommand(client, 1, "PLAY"); + JsonNode play = awaitStructuredCommand(client, 2, "PLAY"); GameplayStructuredCommandAssertions.requireStructuredCommand( play, "PLAY", "play", "META", "SESSION"); assertThat(play.path("accepted").asBoolean()).withFailMessage(play.toPrettyString()).isTrue(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 3e4e43fc38..5bd1345f6b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -791,7 +791,7 @@ void websocketMoveEnqueuesDurableCommandAfterPlay() throws Exception { } @Test - void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { + void websocketFirstPartyBareLoginFailsClosedWithoutPromotingBootstrapShell() throws Exception { List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "1"))) { @@ -804,36 +804,31 @@ void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { payloads = client.responses(); } - JsonNode loginSuccess = json(payloads.get(0)); + JsonNode loginFailure = json(payloads.get(0)); GameplayStructuredCommandAssertions.requireStructuredCommand( - loginSuccess, "LOGIN", "login", "META", "SESSION"); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); + loginFailure, "LOGIN", "login", "META", "SESSION"); + assertThat(loginFailure.path("accepted").asBoolean()).isFalse(); + assertThat(loginFailure.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); assertThat(payloads) .anyMatch( payload -> GameplayStructuredCommandAssertions.isStructuredCommand( payload, "PLAY", "play", "META", "SESSION") - && json(payload).path("accepted").asBoolean()); - assertThat(payloads).anyMatch(payload -> json(payload).path("outputs").isArray()); - verify(accountClient) - .getTenantMembershipForRuntime( - argThat( - playerContext -> - "123".equals(playerContext.getAccountId()) - && "22".equals(playerContext.getTenantId()) - && !playerContext.getRequestId().isBlank())); - verify(accountClient) - .getTenantEntitlementsForRuntime(eq("22"), org.mockito.ArgumentMatchers.anyString()); + && !json(payload).path("accepted").asBoolean() + && "LOGIN_REQUIRED".equals(json(payload).path("errorCode").asText())); assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)) .hasValueSatisfying( context -> { + assertThat(context.accountId()).isZero(); + assertThat(context.gameInstanceId()).isZero(); + assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(1L); - assertThat(context.worldSlug()).isEqualTo("demo"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-1"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-1"); }); + verify(accountClient, never()) + .getTenantMembershipForRuntime( + org.mockito.ArgumentMatchers.any( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); + verify(commandService, never()).enqueue(eq("1"), eq("LOGIN"), eq(false)); } @Test @@ -884,9 +879,7 @@ void websocketFirstPartyStructuredLobbyBrowseFailsClosedForCharacters() throws E List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "browse-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("REALMS demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "REALMS"), "structured REALMS result"); @@ -965,9 +958,7 @@ void websocketFirstPartyStructuredWhoIncludesActivityState() throws Exception { List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "who-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1030,9 +1021,7 @@ void websocketFirstPartyFreshPlayDoesNotReplayBufferedScreenAndPerformsFreshLook List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "2"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1092,9 +1081,7 @@ void websocketFirstPartyLogoutRetainsReplayStateButSuppressesReplayForFreshRecon GameplayWebSocketDriver.CloseEvent firstCloseEvent; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "logout-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1111,9 +1098,7 @@ void websocketFirstPartyLogoutRetainsReplayStateButSuppressesReplayForFreshRecon java.util.List secondPayloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "logout-2"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1356,9 +1341,7 @@ void websocketFirstPartyReconnectAfterCutoverFailsClosedWithoutLeakingOldGamepla try (GameplayWebSocketDriver first = openFirstPartyDriver( "2", firstPartyClaims("demo", "production", "1", "1", "resume-before-cutover"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(first); first.send("PLAY demo"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1385,9 +1368,7 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog throws Exception { try (GameplayWebSocketDriver first = openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "route-a"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(first); first.send("PLAY demo"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1399,9 +1380,7 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog List payloads; try (GameplayWebSocketDriver second = openFirstPartyDriver("2", firstPartyClaims("sandbox", "production", "2", "1", "route-b"))) { - second.send("LOGIN"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(second); second.send("LOOK"); second.awaitMatching( payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); @@ -1459,9 +1438,7 @@ void websocketFirstPartyPlayRejectsCutoverAfterLogin() throws Exception { GameplayWebSocketDriver.CloseEvent closeEvent; try (GameplayWebSocketDriver client = openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "stale-play"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); client.send("PLAY demo"); client.awaitMatching( @@ -1490,9 +1467,7 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe try (GameplayWebSocketDriver first = openFirstPartyDriver( "2", firstPartyClaims("demo", "production", "1", "1", "scope-selector-a"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(first); first.send("PLAY demo"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1508,9 +1483,7 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe second.send("LOOK"); second.awaitMatching( payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - second.send("LOGIN"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(second); payloads = second.responses(); } @@ -1585,6 +1558,19 @@ private GameplayWebSocketDriver openFirstPartyDriver( connectClaims); } + private void loginFirstPartyWithCredentials(GameplayWebSocketDriver client) throws Exception { + client.send("LOGIN demo@example.com swordfish"); + client.awaitMatching( + payload -> isStructuredCommand(payload, "LOGIN"), "structured credential LOGIN result"); + JsonNode login = + client.responses().stream() + .filter(payload -> isStructuredCommand(payload, "LOGIN")) + .map(GameSessionWebSocketHandlerIntegrationTest::json) + .reduce((first, second) -> second) + .orElseThrow(); + assertThat(login.path("accepted").asBoolean()).isTrue(); + } + private java.util.Map firstPartyClaims( String worldSlug, String realmSlug, From 019b7ddab53a8901a97fbffc0377634b40bd3916 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 11:08:42 +1300 Subject: [PATCH 20/46] wip(account): preserve canonical runtime source evidence --- protos/account/v1/account_service.proto | 2 + .../dto/RuntimeMembershipSnapshotDto.java | 95 ++++++++++- ...countMembershipAuthorityEventProducer.java | 29 +++- .../service/impl/AccountGrpcService.java | 4 +- .../AccountJoinPostgresIntegrationTest.java | 12 +- .../NeverJoinedMembershipSnapshotTest.java | 33 +++- .../service/impl/AccountGrpcServiceTest.java | 161 ++++++++++++++++-- 7 files changed, 314 insertions(+), 22 deletions(-) diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 0cf30dd22e..1439b9b939 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -219,6 +219,8 @@ message RuntimeOutboxSourceEvidence { string outbox_sequence = 2; string event_id = 3; string event_digest = 4; + // Exact canonical Account event bytes, carried separately from its two-field checkpoint. + string canonical_event_json = 5; } message GetRealmAccessGrantForRuntimeRequest { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java index de0c59b0b7..5a30374651 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java @@ -6,7 +6,9 @@ import java.util.Objects; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; /** Same-fence Account snapshot candidate for the denied runtime membership RPC. */ public record RuntimeMembershipSnapshotDto( @@ -22,7 +24,8 @@ public record RuntimeMembershipSnapshotDto( String issuanceFence, Instant evaluatedAt, List outboxCheckpoints, - List outboxSourceEvidence) { + List outboxSourceEvidence, + MembershipEvent sourceEvent) { public RuntimeMembershipSnapshotDto { if (requestAccountId == null || requestAccountId <= 0L @@ -54,6 +57,96 @@ public record RuntimeMembershipSnapshotDto( || membershipExists != roles.contains("player")) { throw new IllegalArgumentException("Runtime membership state is not a supported snapshot"); } + requireConsistentSourceEvent( + accountUuid, + tenantUuid, + membershipExists, + gameplayAdmissionAllowed, + membershipBaseline, + roles, + authorityTuple, + issuanceFence, + outboxCheckpoints, + outboxSourceEvidence, + sourceEvent); + } + + /** + * Revalidates event identity and content against this exact producer snapshot before encoding. + */ + public MembershipEvent requireConsistentSourceEvent() { + return requireConsistentSourceEvent( + accountUuid, + tenantUuid, + membershipExists, + gameplayAdmissionAllowed, + membershipBaseline, + roles, + authorityTuple, + issuanceFence, + outboxCheckpoints, + outboxSourceEvidence, + sourceEvent); + } + + private static MembershipEvent requireConsistentSourceEvent( + String accountUuid, + String tenantUuid, + boolean membershipExists, + boolean gameplayAdmissionAllowed, + MembershipBaseline membershipBaseline, + List roles, + AuthorityTuple authorityTuple, + String issuanceFence, + List outboxCheckpoints, + List outboxSourceEvidence, + MembershipEvent sourceEvent) { + if (!membershipExists) { + if (sourceEvent != null || !outboxSourceEvidence.isEmpty()) { + throw new IllegalArgumentException( + "Sequence-zero membership snapshot cannot carry an event source"); + } + return null; + } + + if (sourceEvent == null || outboxSourceEvidence.size() != 1) { + throw new IllegalArgumentException( + "Positive membership snapshot requires its exact source event"); + } + OutboxSourceEvidence source = outboxSourceEvidence.getFirst(); + MembershipEvent verified = MembershipAuthorityEventV1Codec.verify(source.canonicalEventJson()); + if (!verified.canonicalJson().equals(source.canonicalEventJson()) + || !sourceEvent.canonicalJson().equals(source.canonicalEventJson()) + || !verified.eventId().equals(source.eventId()) + || !verified.eventDigest().equals(source.eventDigest()) + || !verified.outboxStreamKey().equals(source.outboxStreamKey()) + || !verified.outboxSequence().equals(source.outboxSequence()) + || !verified.accountId().equals(accountUuid) + || !verified.tenantId().equals(tenantUuid) + || !verified + .membershipLifecycleState() + .equals(membershipBaseline.membershipLifecycleState()) + || !verified.membershipVersion().equals(membershipBaseline.membershipVersion()) + || !verified + .membershipAuthorityGeneration() + .equals(membershipBaseline.membershipAuthorityGeneration()) + || !verified.authorityTuple().equals(authorityTuple) + || !verified.issuanceFence().equals(issuanceFence) + || !verified.roles().equals(roles) + || verified.gameplayAdmissionAllowed() != gameplayAdmissionAllowed) { + throw new IllegalArgumentException( + "Positive membership source event differs from its exact Account snapshot"); + } + List matchingCheckpoints = + outboxCheckpoints.stream() + .filter(item -> item.outboxStreamKey().equals(verified.outboxStreamKey())) + .toList(); + if (matchingCheckpoints.size() != 1 + || !matchingCheckpoints.getFirst().outboxSequence().equals(verified.outboxSequence())) { + throw new IllegalArgumentException( + "Positive membership source event differs from its outbox checkpoint"); + } + return verified; } private static String requireCanonicalUuid(String value, String field) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index a213739e3c..a4fdcaaf63 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -336,7 +336,8 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( positive.issuanceFence(), positive.evaluatedAt(), positive.outboxCheckpoints(), - positive.outboxSourceEvidence()); + positive.outboxSourceEvidence(), + positive.authorityEvent()); } NeverJoinedMembershipSnapshot absent = @@ -357,7 +358,8 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( absent.issuanceFence(), absent.evaluatedAt(), absent.outboxCheckpoints(), - absent.outboxSourceEvidence()); + absent.outboxSourceEvidence(), + null); } /** @@ -1143,7 +1145,8 @@ private OutboxSourceEvidence sourceEvidence(Checkpoint checkpoint, Event event) checkpoint.outboxStreamKey(), Long.toString(checkpoint.outboxSequence()), event.eventId(), - event.eventDigest()); + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)); } private RoleSnapshot requireRoleSnapshot(Identity identity, AccountTenantMembership membership) { @@ -1329,7 +1332,11 @@ public record OutboxCheckpointEntry(String outboxStreamKey, String outboxSequenc /** Positive committed source-event identity kept outside the two-field checkpoint carrier. */ public record OutboxSourceEvidence( - String outboxStreamKey, String outboxSequence, String eventId, String eventDigest) { + String outboxStreamKey, + String outboxSequence, + String eventId, + String eventDigest, + String canonicalEventJson) { public OutboxSourceEvidence { Objects.requireNonNull(outboxStreamKey, "authority outbox stream key is required"); Objects.requireNonNull(outboxSequence, "authority outbox sequence is required"); @@ -1343,6 +1350,16 @@ public record OutboxSourceEvidence( throw new IllegalArgumentException( "Account authority source event evidence is not canonical"); } + Objects.requireNonNull(canonicalEventJson, "canonical source event JSON is required"); + MembershipEvent event = MembershipAuthorityEventV1Codec.verify(canonicalEventJson); + if (!event.canonicalJson().equals(canonicalEventJson) + || !event.eventId().equals(eventId) + || !event.eventDigest().equals(eventDigest) + || !event.outboxStreamKey().equals(outboxStreamKey) + || !event.outboxSequence().equals(outboxSequence)) { + throw new IllegalArgumentException( + "Account authority source event JSON differs from its exact identity"); + } } } @@ -1496,7 +1513,8 @@ public record PositiveMembershipSnapshot( membershipStreamKey, membershipSequence, authorityEvent.eventId(), - authorityEvent.eventDigest())); + authorityEvent.eventDigest(), + authorityEvent.canonicalJson())); if (!membershipExists || !"ACTIVE".equals(membershipLifecycleState) @@ -1508,6 +1526,7 @@ public record PositiveMembershipSnapshot( || !membershipVersion.equals(authorityEvent.membershipVersion()) || !membershipAuthorityGeneration.equals(authorityEvent.membershipAuthorityGeneration()) || !roles.equals(authorityEvent.roles()) + || gameplayAdmissionAllowed != authorityEvent.gameplayAdmissionAllowed() || !authorityTuple.equals(authorityEvent.authorityTuple()) || !issuanceFence.equals(authorityEvent.issuanceFence()) || !"1".equals(authorityTuple.issuerAuthGeneration()) 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 9e81c7d754..61fee41c9a 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 @@ -500,7 +500,8 @@ static GetTenantMembershipForRuntimeResponse encodeRuntimeMembershipCandidate( .setOutboxStreamKey(evidence.outboxStreamKey()) .setOutboxSequence(evidence.outboxSequence()) .setEventId(evidence.eventId()) - .setEventDigest(evidence.eventDigest())); + .setEventDigest(evidence.eventDigest()) + .setCanonicalEventJson(evidence.canonicalEventJson())); } return response.build(); } @@ -531,6 +532,7 @@ private static void requireCompleteRuntimePlayerContext( } private static void requireRuntimeMembershipEvidence(RuntimeMembershipSnapshotDto snapshot) { + snapshot.requireConsistentSourceEvent(); String tenantUuid = snapshot.tenantUuid(); Map version = snapshot.membershipBaseline().membershipVersion(); AuthorityTuple tuple = snapshot.authorityTuple(); 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 40de17d2b1..6640a82bc2 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 @@ -882,7 +882,8 @@ void positiveMembershipSnapshotReturnsExactCommittedAuthorityEvidence() { authorityStreamKey(fixture), snapshot.authorityEvent().outboxSequence(), snapshot.authorityEvent().eventId(), - snapshot.authorityEvent().eventDigest())); + snapshot.authorityEvent().eventDigest(), + snapshot.authorityEvent().canonicalJson())); } @Test @@ -1041,7 +1042,8 @@ void neverJoinedSnapshotRequiresAndRetainsDurablePairBaselineBeforeFirstJoin() { authorityStreamKey(fixture), "1", positive.authorityEvent().eventId(), - positive.authorityEvent().eventDigest())); + positive.authorityEvent().eventDigest(), + positive.authorityEvent().canonicalJson())); assertThat(joinedPairRow) .containsEntry("membership_exists", true) .containsEntry("membership_version", 2L) @@ -1099,7 +1101,11 @@ void runtimeMembershipSnapshotKeepsAbsenceAndFirstJoinEvidenceInOneFencedResult( assertThat(active.outboxSourceEvidence()) .containsExactly( new OutboxSourceEvidence( - authorityStreamKey(fixture), "1", event.eventId(), event.eventDigest())); + authorityStreamKey(fixture), + "1", + event.eventId(), + event.eventDigest(), + event.canonicalJson())); assertThat(active.roles()).contains("player"); assertThat(active.issuanceFence()).matches("[1-9][0-9]*"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java index 7ca7f0a6d8..5f1317e874 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java @@ -220,7 +220,8 @@ void rejectsSequenceZeroSnapshotWithMissingCheckpointOrSourceEvent() { STREAM_KEY, "1", "04ef66b4-c0ad-3d5b-b3b2-0e8510e72002", - "sha256:" + "a".repeat(64))); + positiveSourceEvent().eventDigest(), + positiveSourceEvent().canonicalJson())); assertThatThrownBy( () -> @@ -288,4 +289,34 @@ private static AuthorityTuple completeTuple() { Optional.empty(), Optional.empty()); } + + private static MembershipAuthorityEventV1Codec.MembershipEvent positiveSourceEvent() { + return MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "04ef66b4-c0ad-3d5b-b3b2-0e8510e72002"), + Map.entry("requestId", "join-request-1"), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", "membership/" + ACCOUNT_ID + "/" + TENANT_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("tenantId", TENANT_ID), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(TENANT_ID, "2")), + Map.entry("membershipAuthorityGeneration", "1"), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(TENANT_ID, "1"), + "membershipAuthorityGeneration", Map.of(TENANT_ID, "1"), + "privateRealmGrantVersions", List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", List.of("player")), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + } } 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 388b6dcab8..e5a4b3da1d 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.Context; import io.grpc.stub.StreamObserver; import java.time.Instant; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -60,7 +61,9 @@ 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.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; @@ -118,6 +121,20 @@ private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( boolean membershipExists, List checkpoints, List sourceEvidence) { + return runtimeMembershipSnapshot( + requestAccountId, + membershipExists, + checkpoints, + sourceEvidence, + membershipExists ? runtimeMembershipAuthorityEvent(Map.of()) : null); + } + + private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( + long requestAccountId, + boolean membershipExists, + List checkpoints, + List sourceEvidence, + MembershipEvent sourceEvent) { return new RuntimeMembershipSnapshotDto( requestAccountId, 20L, @@ -141,7 +158,8 @@ private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( "7", Instant.parse("2026-09-27T00:00:00Z"), checkpoints, - sourceEvidence); + sourceEvidence, + sourceEvent); } private static List runtimeMembershipCheckpoints(String sequence) { @@ -155,12 +173,54 @@ private static List runtimeMembershipCheckpoints(String s } private static List runtimeMembershipSourceEvidence() { + return runtimeMembershipSourceEvidence(runtimeMembershipAuthorityEvent(Map.of())); + } + + private static List runtimeMembershipSourceEvidence(MembershipEvent event) { return List.of( new OutboxSourceEvidence( - "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID, - "1", - "04ef66b4-c0ad-3d5b-b3b2-0e8510e72003", - "sha256:" + "a".repeat(64))); + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.canonicalJson())); + } + + private static MembershipEvent runtimeMembershipAuthorityEvent(Map overrides) { + return runtimeMembershipAuthorityEvent(ACCOUNT_UUID, TENANT_UUID, overrides); + } + + private static MembershipEvent runtimeMembershipAuthorityEvent( + String accountUuid, String tenantUuid, Map overrides) { + Map preimage = new LinkedHashMap<>(); + String streamKey = "account:auth-authority:v1:membership/" + accountUuid + "/" + tenantUuid; + preimage.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("eventId", "04ef66b4-c0ad-3d5b-b3b2-0e8510e72003"); + preimage.put("requestId", "join-request-1"); + preimage.put("outboxStreamKey", streamKey); + preimage.put("outboxSequence", "1"); + preimage.put("sourceScope", "membership/" + accountUuid + "/" + tenantUuid); + preimage.put("accountId", accountUuid); + preimage.put("tenantId", tenantUuid); + preimage.put("membershipExists", true); + preimage.put("membershipLifecycleState", "ACTIVE"); + preimage.put("membershipVersion", Map.of(tenantUuid, "2")); + preimage.put("membershipAuthorityGeneration", "1"); + preimage.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(tenantUuid, "1"), + "membershipAuthorityGeneration", Map.of(tenantUuid, "1"), + "privateRealmGrantVersions", List.of())); + preimage.put("issuanceFence", "7"); + preimage.put("roles", List.of("player")); + preimage.put("gameplayAdmissionAllowed", true); + preimage.put("callerBoundAuthorityInvalidated", false); + preimage.putAll(overrides); + return MembershipAuthorityEventV1Codec.seal(preimage); } private static IssueDirectTextConnectScopeRequest validScopeRequest() { @@ -1762,7 +1822,12 @@ void encodeRuntimeMembershipCandidateEncodesCompleteActivePositiveSnapshot() { assertEquals(1, response.getOutboxSourceEvidenceCount()); assertEquals( "04ef66b4-c0ad-3d5b-b3b2-0e8510e72003", response.getOutboxSourceEvidence(0).getEventId()); - assertEquals("sha256:" + "a".repeat(64), response.getOutboxSourceEvidence(0).getEventDigest()); + assertEquals( + runtimeMembershipAuthorityEvent(Map.of()).eventDigest(), + response.getOutboxSourceEvidence(0).getEventDigest()); + assertEquals( + runtimeMembershipAuthorityEvent(Map.of()).canonicalJson(), + response.getOutboxSourceEvidence(0).getCanonicalEventJson()); } @Test @@ -1811,19 +1876,93 @@ void encodeRuntimeMembershipCandidateRejectsIncompleteCheckpointOrSourceEvidence true, completeCheckpoints.subList(0, completeCheckpoints.size() - 1), runtimeMembershipSourceEvidence()); - RuntimeMembershipSnapshotDto missingSourceEvidence = - runtimeMembershipSnapshot(10L, true, completeCheckpoints, List.of()); - assertThrows( IllegalArgumentException.class, () -> AccountGrpcService.encodeRuntimeMembershipCandidate( validRuntimeMembershipContext(), missingCheckpoint)); + assertThrows( + IllegalArgumentException.class, + () -> runtimeMembershipSnapshot(10L, true, completeCheckpoints, List.of())); + } + + @Test + void runtimeMembershipSnapshotRejectsSourceEventContentThatDiffersFromSnapshot() { + MembershipEvent expected = runtimeMembershipAuthorityEvent(Map.of()); + List inconsistentEvents = + List.of( + runtimeMembershipAuthorityEvent( + Map.of("eventId", "04ef66b4-c0ad-3d5b-b3b2-0e8510e72004")), + runtimeMembershipAuthorityEvent(Map.of("requestId", "join-request-2")), + runtimeMembershipAuthorityEvent(Map.of("outboxSequence", "2")), + runtimeMembershipAuthorityEvent( + "04ef66b4-c0ad-3d5b-b3b2-0e8510e72004", TENANT_UUID, Map.of()), + runtimeMembershipAuthorityEvent( + ACCOUNT_UUID, "04ef66b4-c0ad-3d5b-b3b2-0e8510e72004", Map.of()), + runtimeMembershipAuthorityEvent( + Map.of("membershipLifecycleState", "INACTIVE", "gameplayAdmissionAllowed", false)), + runtimeMembershipAuthorityEvent(Map.of("membershipVersion", Map.of(TENANT_UUID, "3"))), + runtimeMembershipAuthorityEvent( + Map.of( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "2", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(TENANT_UUID, "1"), + "membershipAuthorityGeneration", Map.of(TENANT_UUID, "1"), + "privateRealmGrantVersions", List.of()))), + runtimeMembershipAuthorityEvent(Map.of("issuanceFence", "8")), + runtimeMembershipAuthorityEvent(Map.of("roles", List.of("designer", "player"))), + runtimeMembershipAuthorityEvent(Map.of("gameplayAdmissionAllowed", false))); + + for (MembershipEvent inconsistent : inconsistentEvents) { + assertThrows( + IllegalArgumentException.class, + () -> + runtimeMembershipSnapshot( + 10L, + true, + runtimeMembershipCheckpoints("1"), + runtimeMembershipSourceEvidence(inconsistent), + expected)); + } + } + + @Test + void runtimeOutboxSourceEvidenceRejectsChangedContentOrDigest() { + MembershipEvent event = runtimeMembershipAuthorityEvent(Map.of()); + String changedContent = + event.canonicalJson().replace("\"issuanceFence\":\"7\"", "\"issuanceFence\":\"8\""); + String changedDigest = + event.canonicalJson().replace(event.eventDigest(), "sha256:" + "a".repeat(64)); + assertThrows( IllegalArgumentException.class, () -> - AccountGrpcService.encodeRuntimeMembershipCandidate( - validRuntimeMembershipContext(), missingSourceEvidence)); + new OutboxSourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + changedContent)); + assertThrows( + IllegalArgumentException.class, + () -> + new OutboxSourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + changedDigest)); + assertThrows( + IllegalArgumentException.class, + () -> + new OutboxSourceEvidence( + event.outboxStreamKey(), + "2", + event.eventId(), + event.eventDigest(), + event.canonicalJson())); } private static final class RecordingObserver implements StreamObserver { From 4441fd003d58ef8a1448d82930510367144c6adb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 18:47:49 +1300 Subject: [PATCH 21/46] fix(auth): bind runtime membership snapshot to source event --- .../account-service/api-contracts.md | 2 +- .../player-access-and-session.md | 4 +- .../command/text/PlayCommandHandler.java | 117 +++++++++- .../command/text/PlayCommandHandlerTest.java | 201 ++++++++++++++++++ .../RuntimeMembershipTestFixtures.java | 36 +++- 5 files changed, 349 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 31842945ae..f0b616b04c 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -115,7 +115,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` (request carrying typed `PlayerExecutionContext`) – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. The proto and Game Session consumer now carry the typed player context, but the Account handler still fails closed before the candidate producer/data read. Game Session performs structural lifecycle and authority-carrier checks; one fresh atomic Account membership snapshot and complete producer/consumer proof remain incomplete. +- `GetTenantMembershipForRuntime` (request carrying typed `PlayerExecutionContext`) – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. The proto and Game Session consumer carry the typed player context. The local Account encoder carries canonical positive event content separately from the checkpoint, and the Game Session candidate recomputes its digest and compares the decoded event with the response; sequence zero carries no event. The Account handler still fails closed before the candidate producer/data read. A live authenticated same-snapshot response, complete producer/consumer proof, and runtime activation remain incomplete. - `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. 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. 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 d9764dd4c1..51171477d4 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 unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's exact one-tenant `membershipVersion` map in the producer, strict shared codec, canonical digest vectors, immutable evidence, and Account exact retry/readback comparisons. The Account producer may extract a local numeric value only after validating the map; it does not persist or transmit a scalar event field. Shared codec and Account/Game Session vector tests execute locally; PostgreSQL JOIN/reconciliation tests compile but skip without Docker, and the runtime membership RPC remains denied until its complete same-snapshot producer and consumer proof is ready. The unactivated Account ring materializer binds a dedicated service-account username in the protected source record, checks server-reported identity before Secret access, and returns a typed non-secret receipt with source generation/predecessor and exact Secret UID/resourceVersion readback. A focused read-side verifier now checks its closed typed shape, canonical digest, and exact source, writer, and Secret bindings; this remains local structural proof, not authenticated environment/secrets-channel publication. Sole-writer RBAC, protected custody, handoff, deployment readback, and live readiness remain unproved, so no Account ring mount is published. -Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. Its new typed runtime wire and Account encoder carry the complete current-only snapshot with exact caller selector and request-ID echoes. Game Session has a fail-closed structural consumer for that carrier, but neither full event-content/current-authority verification nor live admission is proved; the Account RPC remains denied. The composed local module gate passed with 381 Account unit tests, 1,640 Game Session unit tests, and 43 common-test-support tests executed; all 78 Account integration cases, 112 of 130 Game Session integration cases, and 39 of 40 Game Session cross-service cases skipped without Docker. Thus PostgreSQL, cross-service, and live RPC proof for this new wire remain open. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both earlier aggregate gates were red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's then nine-file snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; #2876 records that authority, and #2880's typed carrier remains disabled pending full producer/consumer proof. +Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. Its new typed runtime wire and Account encoder carry the complete current-only snapshot with exact caller selector and request-ID echoes. The local positive source carrier now includes canonical event content, and Game Session's candidate validates its digest and exact event/response agreement; sequence zero remains event-free. This is local component proof only, not a live Account-authenticated response, complete current-authority consumption, or admission: the Account RPC remains denied. The composed local module gate passed with 381 Account unit tests, 1,640 Game Session unit tests, and 43 common-test-support tests executed; all 78 Account integration cases, 112 of 130 Game Session integration cases, and 39 of 40 Game Session cross-service cases skipped without Docker. Thus PostgreSQL, cross-service, and live RPC proof for this new wire remain open. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both earlier aggregate gates were red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's then nine-file snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; #2876 records that authority, and #2880's typed carrier remains disabled pending full producer/consumer proof. 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 durable post-logout episode fencing 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. @@ -34,7 +34,7 @@ The #2876 candidate also adds a local AES-256-GCM response-envelope primitive ba At published #2876 head `774356d5a66846a535726f680aa54ce85669160b`, manual CI run `36257232596` passed Account Build/Test, but `:account-service:integrationTest` was `FROM-CACHE`; it does not demonstrate fresh PostgreSQL execution. The gate failed on seven of 39 Game Session Friends/WebSocket cross-service cases, ten hosted smoke-tool Ruff errors, and the EA-3.1 executable-proof-link check. The failing paths are outside #2876's unique diff, but CI alone does not establish the Game Session root cause or merge readiness. The proposed required Account Secret mount remains unpublished: its rendered-manifest contract passes locally, but no environment source, trusted-writer receipt, or readiness proof exists, and deployment cannot safely require the absent Secret. A Game Session sequence-only event-consumer draft was discarded because the accepted contract requires authenticated same-snapshot tuple, fence, membership baseline, complete checkpoints, and source evidence; the current wire does not provide those fields. Runtime RPCs remain denied. -The #2880 membership-snapshot child now carries a typed caller/target request and same-fence Account active/never-joined response candidate with a complete tuple, unchanged baseline, ordered checkpoints, and exact positive-event source evidence. The Account RPC still returns `FAILED_PRECONDITION`; Game Session's current carrier check is structural and does not enable admission. Manual CI run `36291712632` on prior #2880 head `346fc819c8aa384d7362cef9c336f387903144d4` executed Account `:test` and `:integrationTest` successfully, but its successful Account job did not publish per-case JUnit XML, so exact PostgreSQL counts are unavailable. Its four Game Session/TCP Proxy cross-service failures were attributable to #2880's rejection of the fixture's incomplete `INACTIVE` carrier before public-production `JOIN_REQUIRED`. The corrected local candidate accepts only a fully evidenced, non-admitting `INACTIVE` carrier for that outcome while still denying incomplete evidence; the Account producer has no current INACTIVE snapshot path. Focused Play handler and Account stub tests executed locally (65 and 3 tests, zero failures), and the new direct Account same-fence PostgreSQL test compiled but has not run without Docker. Corrected-head CI remains required. +The #2880 membership-snapshot child now carries a typed caller/target request and same-fence Account active/never-joined response candidate with a complete tuple, unchanged baseline, ordered checkpoints, and exact positive-event source evidence. The local Account encoder and Game Session candidate now validate the positive canonical event content and exact response agreement, but the Account RPC still returns `FAILED_PRECONDITION` before data access; this does not enable admission or prove a live composed exchange. Manual CI run `36291712632` on prior #2880 head `346fc819c8aa384d7362cef9c336f387903144d4` executed Account `:test` and `:integrationTest` successfully, but its successful Account job did not publish per-case JUnit XML, so exact PostgreSQL counts are unavailable. Its four Game Session/TCP Proxy cross-service failures were attributable to #2880's rejection of the fixture's incomplete `INACTIVE` carrier before public-production `JOIN_REQUIRED`. The corrected local candidate accepts only a fully evidenced, non-admitting `INACTIVE` carrier for that outcome while still denying incomplete evidence; the Account producer has no current INACTIVE snapshot path. Focused Play handler and Account stub tests executed locally (65 and 3 tests, zero failures), and the new direct Account same-fence PostgreSQL test compiled but has not run without Docker. Corrected-head CI remains required. Account's credential-granting gameplay gRPC methods enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Legacy profile GET/PUT now require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy batch reads require the exact Social Groups peer and remain scoped to tenant profiles. Direct account-ID export, external-link, and verification gRPC methods deny before reads or mutation because no authorized internal caller is configured. These guards do not make the broader target method/caller authority complete or restore the disabled runtime reads. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 0952451fc2..bccfebe7c0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -7,14 +7,18 @@ import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.RuntimeAuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; @@ -918,11 +922,114 @@ private static boolean hasCompleteMembershipAuthorityCarrier( return false; } var source = response.getOutboxSourceEvidence(0); - return source.getUnknownFields().asMap().isEmpty() - && source.getOutboxStreamKey().equals(membershipStream) - && source.getOutboxSequence().equals(checkpointSequences.get(membershipStream)) - && isCanonicalUuid(source.getEventId()) - && source.getEventDigest().matches("sha256:[0-9a-f]{64}"); + if (!source.getUnknownFields().asMap().isEmpty() + || !source.getOutboxStreamKey().equals(membershipStream) + || !source.getOutboxSequence().equals(checkpointSequences.get(membershipStream)) + || !isCanonicalUuid(source.getEventId()) + || !source.getEventDigest().matches("sha256:[0-9a-f]{64}") + || !StringUtils.hasText(source.getCanonicalEventJson())) { + return false; + } + final MembershipAuthorityEventV1Codec.MembershipEvent event; + try { + event = MembershipAuthorityEventV1Codec.verify(source.getCanonicalEventJson()); + } catch (IllegalArgumentException ex) { + return false; + } + return matchesMembershipEvent(response, source, event, checkpointSequences, membershipStream); + } + + private static boolean matchesMembershipEvent( + GetTenantMembershipForRuntimeResponse response, + net.firedevops.firemud.account.v1.RuntimeOutboxSourceEvidence source, + MembershipAuthorityEventV1Codec.MembershipEvent event, + Map checkpointSequences, + String membershipStream) { + return event.canonicalJson().equals(source.getCanonicalEventJson()) + && event.eventId().equals(source.getEventId()) + && event.eventDigest().equals(source.getEventDigest()) + && event.outboxStreamKey().equals(source.getOutboxStreamKey()) + && event.outboxSequence().equals(source.getOutboxSequence()) + && event.outboxStreamKey().equals(membershipStream) + && event.outboxSequence().equals(checkpointSequences.get(membershipStream)) + && event.accountId().equals(response.getAccountId()) + && event.tenantId().equals(response.getTenantId()) + && event.membershipLifecycleState().equals(response.getMembershipLifecycleState()) + && event.membershipVersion().equals(response.getMembershipVersionMap()) + && event.membershipAuthorityGeneration().equals(response.getMembershipAuthorityGeneration()) + && event.issuanceFence().equals(response.getIssuanceFence()) + && event.roles().equals(response.getRolesList()) + && event.gameplayAdmissionAllowed() == response.getGameplayAdmissionAllowed() + && matchesAuthorityTuple(response.getAuthorityTuple(), event.authorityTuple()); + } + + private static boolean matchesAuthorityTuple( + RuntimeAuthorityTuple response, MembershipAuthorityEventV1Codec.AuthorityTuple event) { + if (!response.getIssuerAuthGeneration().equals(event.issuerAuthGeneration()) + || !response.getAccountAuthorityGeneration().equals(event.accountAuthorityGeneration()) + || !response.getTenantAuthorityGenerationMap().equals(event.tenantAuthorityGeneration()) + || !response + .getMembershipAuthorityGenerationMap() + .equals(event.membershipAuthorityGeneration()) + || response.getPrivateRealmGrantVersionsCount() != event.privateRealmGrantVersions().size() + || response.hasAccountSecurityCutoff() != event.accountSecurityCutoff().isPresent() + || response.hasTenantBillingCutoff() != event.tenantBillingCutoff().isPresent()) { + return false; + } + for (int index = 0; index < response.getPrivateRealmGrantVersionsCount(); index++) { + var responseGrant = response.getPrivateRealmGrantVersions(index); + var eventGrant = event.privateRealmGrantVersions().get(index); + if (!responseGrant.getTenantId().equals(eventGrant.tenantId()) + || !responseGrant.getWorldSlug().equals(eventGrant.worldSlug()) + || !responseGrant.getRealmSlug().equals(eventGrant.realmSlug()) + || !responseGrant.getPlaytestLifecycleId().equals(eventGrant.playtestLifecycleId()) + || !responseGrant.getGrantVersion().equals(eventGrant.grantVersion())) { + return false; + } + } + if (response.hasAccountSecurityCutoff()) { + var responseCutoff = response.getAccountSecurityCutoff(); + var eventCutoff = event.accountSecurityCutoff().orElseThrow(); + if (!responseCutoff + .getAccountAuthorityGeneration() + .equals(eventCutoff.accountAuthorityGeneration()) + || !responseCutoff.getOutboxStreamKey().equals(eventCutoff.outboxStreamKey()) + || !responseCutoff.getOutboxSequence().equals(eventCutoff.outboxSequence())) { + return false; + } + } + if (response.hasTenantBillingCutoff()) { + var eventCutoffs = event.tenantBillingCutoff().orElseThrow(); + var responseCutoffs = response.getTenantBillingCutoff().getEntriesList(); + if (responseCutoffs.size() != eventCutoffs.size()) { + return false; + } + Set responseCutoffTenants = new HashSet<>(); + for (var responseEntry : responseCutoffs) { + var eventCutoff = eventCutoffs.get(responseEntry.getTenantId()); + if (!responseCutoffTenants.add(responseEntry.getTenantId()) + || eventCutoff == null + || !responseEntry + .getCutoff() + .getTenantAuthorityGeneration() + .equals(eventCutoff.tenantAuthorityGeneration()) + || !responseEntry + .getCutoff() + .getTenantBillingSequence() + .equals(eventCutoff.tenantBillingSequence()) + || !responseEntry.getCutoff().getOutboxStreamKey().equals(eventCutoff.outboxStreamKey()) + || !responseEntry + .getCutoff() + .getOutboxSequence() + .equals(eventCutoff.outboxSequence())) { + return false; + } + } + if (!responseCutoffTenants.equals(eventCutoffs.keySet())) { + return false; + } + } + return true; } private static boolean isPositiveCanonicalDecimal(String value) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index faf372b400..fc32dde859 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -4,14 +4,20 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; +import java.util.Map; import java.util.Optional; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; @@ -44,6 +50,7 @@ class PlayCommandHandlerTest { private static final String PLAY_COMMAND_NAME = "PLAY"; + private static final ObjectMapper JSON = new ObjectMapper(); private final SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); private final SessionContextService sessionContextService = @@ -1773,6 +1780,158 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var response = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1")); + String changedCanonicalJson = + resealWithMembershipVersion( + response.getOutboxSourceEvidence(0).getCanonicalEventJson(), "2"); + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + replaceCanonicalEvent(response, changedCanonicalJson, true), + invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService) + .save(Mockito.argThat(saved -> saved.characterId() == 0L && saved.gameInstanceId() == 0L)); + } + + @Test + void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var response = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1")); + String changedCanonicalJson = + changeCanonicalEventWithoutResealing( + response.getOutboxSourceEvidence(0).getCanonicalEventJson()); + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + replaceCanonicalEvent(response, changedCanonicalJson, false), + invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService) + .save(Mockito.argThat(saved -> saved.characterId() == 0L && saved.gameInstanceId() == 0L)); + } + + @Test + void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var response = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1")); + var source = + response.getOutboxSourceEvidence(0).toBuilder().clearCanonicalEventJson(); + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + response.toBuilder() + .clearOutboxSourceEvidence() + .addOutboxSourceEvidence(source) + .build(), + invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService) + .save(Mockito.argThat(saved -> saved.characterId() == 0L && saved.gameInstanceId() == 0L)); + } + + @Test + void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var response = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1")); + var mismatchedResponse = + response.toBuilder() + .putMembershipVersion("00000000-0000-0000-0000-000000000022", "2") + .setMembershipBaseline( + response.getMembershipBaseline().toBuilder() + .putMembershipVersion("00000000-0000-0000-0000-000000000022", "2")) + .build(); + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(mismatchedResponse, invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService) + .save(Mockito.argThat(saved -> saved.characterId() == 0L && saved.gameInstanceId() == 0L)); + } + @ParameterizedTest @ValueSource(strings = {"target", "version", "stale", "future", "malformed"}) void unsafeEntitlementSnapshotFailsClosed(String defect) { @@ -2047,6 +2206,48 @@ private static String joinedOutputText(List outputs) { .orElse(null); } + private static GetTenantMembershipForRuntimeResponse replaceCanonicalEvent( + GetTenantMembershipForRuntimeResponse response, + String canonicalJson, + boolean synchronizeSourceMetadata) { + var source = + response.getOutboxSourceEvidence(0).toBuilder().setCanonicalEventJson(canonicalJson); + if (synchronizeSourceMetadata) { + var event = MembershipAuthorityEventV1Codec.verify(canonicalJson); + source + .setOutboxStreamKey(event.outboxStreamKey()) + .setOutboxSequence(event.outboxSequence()) + .setEventId(event.eventId()) + .setEventDigest(event.eventDigest()); + } + return response.toBuilder().clearOutboxSourceEvidence().addOutboxSourceEvidence(source).build(); + } + + private static String resealWithMembershipVersion( + String canonicalJson, String membershipVersion) { + try { + ObjectNode event = (ObjectNode) JSON.readTree(canonicalJson); + ((ObjectNode) event.get("membershipVersion")) + .put("00000000-0000-0000-0000-000000000022", membershipVersion); + event.remove("eventDigest"); + return MembershipAuthorityEventV1Codec.seal( + JSON.convertValue(event, new TypeReference>() {})) + .canonicalJson(); + } catch (IOException ex) { + throw new AssertionError("test event should be valid JSON", ex); + } + } + + private static String changeCanonicalEventWithoutResealing(String canonicalJson) { + try { + ObjectNode event = (ObjectNode) JSON.readTree(canonicalJson); + event.put("requestId", "tampered-membership-request"); + return event.toString(); + } catch (IOException ex) { + throw new AssertionError("test event should be valid JSON", ex); + } + } + private static GetTenantMembershipForRuntimeResponse freshMembership( GetTenantMembershipForRuntimeResponse response) { return response.toBuilder().setEvaluatedAt(Instant.now().toString()).build(); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java index 8912a6860c..595b3af693 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -3,11 +3,13 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Map; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.RuntimeAuthorityTuple; import net.firedevops.firemud.account.v1.RuntimeMembershipBaseline; import net.firedevops.firemud.account.v1.RuntimeOutboxCheckpoint; import net.firedevops.firemud.account.v1.RuntimeOutboxSourceEvidence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; /** Complete or intentionally incomplete fixtures for the denied runtime membership carrier. */ @@ -15,7 +17,6 @@ public final class RuntimeMembershipTestFixtures { private static final String STREAM_PREFIX = "account:auth-authority:v1:"; private static final String ISSUER = "firemud-account-service"; private static final String EVENT_ID = "00000000-0000-0000-0000-000000000099"; - private static final String EVENT_DIGEST = "sha256:" + "0".repeat(64); private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; private RuntimeMembershipTestFixtures() {} @@ -127,12 +128,41 @@ private static GetTenantMembershipForRuntimeResponse complete( response.addRoles("player"); } if (exists) { + MembershipAuthorityEventV1Codec.MembershipEvent event = + MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", EVENT_ID), + Map.entry("requestId", "runtime-membership-request"), + Map.entry("outboxStreamKey", membershipStream), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", "membership/" + accountUuid + "/" + tenantUuid), + Map.entry("accountId", accountUuid), + Map.entry("tenantId", tenantUuid), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", lifecycle), + Map.entry("membershipVersion", Map.of(tenantUuid, membershipVersion)), + Map.entry("membershipAuthorityGeneration", "1"), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(tenantUuid, "1"), + "membershipAuthorityGeneration", Map.of(tenantUuid, "1"), + "privateRealmGrantVersions", List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", admitted ? List.of("player") : List.of()), + Map.entry("gameplayAdmissionAllowed", admitted), + Map.entry("callerBoundAuthorityInvalidated", false))); response.addOutboxSourceEvidence( RuntimeOutboxSourceEvidence.newBuilder() .setOutboxStreamKey(membershipStream) .setOutboxSequence("1") - .setEventId(EVENT_ID) - .setEventDigest(EVENT_DIGEST)); + .setEventId(event.eventId()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson())); } return response.build(); } From 8399ddb0aca36c7a674bacde3fbad62c8c625471 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 18:56:20 +1300 Subject: [PATCH 22/46] docs(auth): state bare LOGIN fail-closed proof accurately --- .../microservices/game-session-service/protocols.md | 4 ++-- .../implementation-tracking/player-access-and-session.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 492eda06b7..56c519e704 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -102,10 +102,10 @@ Current local `JOIN` availability and the membership-authority-generation gap ar Telnet and WebSocket clients share the line-based syntax, but transport context determines which `LOGIN` form is valid: - For Telnet and other non-WebSocket text clients, fresh public `WORLDS` discovery precedes `LOGIN`; `LOGIN ` requests a verified-email code and `LOGIN ` performs an immediate password-or-code authentication attempt. Bare `LOGIN` does not start an interactive prompt. -- For sessions on the Gateway-routed first-party WebSocket route `/ws/game/**` that already carry a validated Gateway connect context, bare `LOGIN` completes gameplay authentication from the pre-established bootstrap identity instead of prompting for credentials. First-party browser, mobile-browser, native-mobile, and other first-party non-browser clients use the protected connect-token cookie; only the target-only, explicitly classified `non_first_party_public` route variant may use the dedicated connect-token handshake header after its proof is complete. This bootstrap identity must not quietly reintroduce gameplay binding into `LOGIN`; `PLAY` remains the sole gameplay-admission and gameplay-scope binding step. Reauthentication as a different account clears every retained character, runtime-route, playable-scope, and connect-scope field before `PLAY`; only an exact same-account reconnect may retain its candidate gameplay context for fresh admission validation. +- For sessions on the Gateway-routed first-party WebSocket route `/ws/game/**` that already carry a validated Gateway connect context, target bare `LOGIN` completes gameplay authentication through Account's one-use, caller-bound delegation exchange instead of prompting for credentials. The current candidate returns `AUTH_UNAVAILABLE` before promotion because that exchange is not implemented; Gateway context alone is not Account authorization. First-party browser, mobile-browser, native-mobile, and other first-party non-browser clients use the protected connect-token cookie; only the target-only, explicitly classified `non_first_party_public` route variant may use the dedicated connect-token handshake header after its proof is complete. This bootstrap identity must not quietly reintroduce gameplay binding into `LOGIN`; `PLAY` remains the sole gameplay-admission and gameplay-scope binding step. Reauthentication as a different account clears every retained character, runtime-route, playable-scope, and connect-scope field before `PLAY`; only an exact same-account reconnect may retain its candidate gameplay context for fresh admission validation. - The same `OK ` and `ERROR ` response format applies to all transports so clients can react consistently. -Multi-line prompt exchanges are planned but not implemented for Telnet and non-bootstrap clients. On those transports, bare `LOGIN` currently returns `ERROR PROMPT_LOGIN_UNSUPPORTED Prompt-based login is not implemented yet; send LOGIN [secret].` First-party `/ws/game/**` sessions with a validated connect context are the exception: bare `LOGIN` consumes the bootstrap-backed context and must not ask the browser to resend credentials. +Multi-line prompt exchanges are planned but not implemented for Telnet and non-bootstrap clients. On those transports, bare `LOGIN` currently returns `ERROR PROMPT_LOGIN_UNSUPPORTED Prompt-based login is not implemented yet; send LOGIN [secret].` First-party `/ws/game/**` sessions with a validated connect context are the target exception: bare `LOGIN` must use the Account exchange without asking the browser to resend credentials, but currently returns `AUTH_UNAVAILABLE` without promoting an authenticated session. After `LOGIN` succeeds, an existing member normally issues `PLAY [realm] [character]`; a first-time public-production player must issue `JOIN ` once before `PLAY`. `REALMS` and `CHARS` remain available as lobby helper commands when the player's choice is ambiguous or when they want to browse. `PLAY` is the gameplay-admission and gameplay-binding step; it is not merely a continuation of authentication. This step binds the authenticated connection to a world-scoped gameplay session and enforces tenant authorization, realm routing, public-admission rules, and entitlements. 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 ef13216881..389dc04c9f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,11 +32,11 @@ The current Unit 1B draft's conditional Game Session `PLAY` branch now distingui The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases passed in CI run `36289042648` on prior #2881 head `25626210c` and skipped locally without Docker; caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. -The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests currently fail at their shared helper's old successful-bare-LOGIN assertion; there is no supported authenticated first-party fixture until the Account exchange works, and the internal text fixture cannot prove structured public output. They remain an explicit runtime proof gate rather than being disabled or counted as passing. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. +The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests failed on an earlier head because their helper still expected bare-LOGIN success. The corrected helper now asserts `AUTH_UNAVAILABLE` and no promotion for that attempt, then uses credential-bearing LOGIN for supported gameplay coverage; the dedicated negative fixture expects following `PLAY` to require login. Both affected Docker-backed classes skipped locally, so this is a corrected assertion, not executed WebSocket end-to-end proof or a working Account exchange. Positive first-party bare-LOGIN proof remains an explicit activation gate. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. -Manual CI run `36292018666` on prior #2881 head `aa5d73c05a408ba152ac05f4298cadd52430b831` passed its strict Account evidence gate: all 24 JOIN PostgreSQL cases and seven V37 bare-LOGIN exchange cases executed with no skips or failures, including the required targeted map-shape and transaction tests. Its aggregate gate remained red: seven first-party success assertions still assume the disabled exchange, and four Game Session/TCP Proxy cross-service failures arose from #2880's incomplete `INACTIVE` carrier handling; ten hosted smoke-tool Ruff errors and the EA-3.1 proof-link rule also failed. The #2880 consumer/stub correction has been merged normally into #2881 with its unique non-tracker patch ID unchanged. A new signed-context wire-negative test for bare `LOGIN` and following `PLAY` compiles but skipped locally without Docker; the seven positive scenarios remain unchanged. The corrected composed local module/doc gate passed, with 381 Account and 1,641 Game Session unit tests executed, but all 87 Account PostgreSQL cases and 40/41 Game Session cross-service cases skipped. Corrected-head hosted proof remains necessary, and neither membership nor credential runtime path is enabled. +Manual CI run `36292018666` on prior #2881 head `aa5d73c05a408ba152ac05f4298cadd52430b831` passed its strict Account evidence gate: all 24 JOIN PostgreSQL cases and seven V37 bare-LOGIN exchange cases executed with no skips or failures, including the required targeted map-shape and transaction tests. Its aggregate gate remained red: seven first-party success assertions still assume the disabled exchange, and four Game Session/TCP Proxy cross-service failures arose from #2880's incomplete `INACTIVE` carrier handling; ten hosted smoke-tool Ruff errors and the EA-3.1 proof-link rule also failed. The #2880 consumer/stub correction has been merged normally into #2881 with its unique non-tracker patch ID unchanged. A new signed-context wire-negative test for bare `LOGIN` and following `PLAY` compiles but skipped locally without Docker; the seven positive scenarios still retained their obsolete success assertions at that checkpoint; the later fixture correction is described above. The corrected composed local module/doc gate passed, with 381 Account and 1,641 Game Session unit tests executed, but all 87 Account PostgreSQL cases and 40/41 Game Session cross-service cases skipped. Corrected-head hosted proof remains necessary, and neither membership nor credential runtime path is enabled. -Corrected #2881 head `e39c31b1f42b202c26c34ba83ddf6e4c8247699e` ran in CI `36293121086`: the strict Account gate passed all 26 JOIN and seven V37 PostgreSQL cases with zero skips/failures, including #2880's two new same-fence snapshot cases; the signed-context bare-`LOGIN` denial test executed and passed. Game Session's 41 cross-service cases had exactly seven failures, all existing first-party success scenarios awaiting the Account exchange. TCP Proxy and all other service Build/Test jobs passed. Python Script Validation and the EA-3.1 Dev Tool Contract Check remain red outside this unique change. Two additional V37 repository/crypto tests now locally compile: concurrent exact first-writer terminalization and decrypting the exact retained envelope after a simulated lost response. All 89 local Account integration cases skip without Docker, so these two new tests need hosted execution. They prove storage/recovery primitives only, not Account-issued JWT, caller-bound exchange, live ring custody, or activation. +Corrected #2881 head `e39c31b1f42b202c26c34ba83ddf6e4c8247699e` ran in CI `36293121086`: the strict Account gate passed all 26 JOIN and seven V37 PostgreSQL cases with zero skips/failures, including #2880's two new same-fence snapshot cases; the signed-context bare-`LOGIN` denial test executed and passed. Game Session's 41 cross-service cases had exactly seven failures from the then-current first-party success assertions; those assertions were subsequently corrected to the fail-closed behavior described above, while the Account exchange remains unimplemented. TCP Proxy and all other service Build/Test jobs passed. Python Script Validation and the EA-3.1 Dev Tool Contract Check remain red outside this unique change. Two additional V37 repository/crypto tests now locally compile: concurrent exact first-writer terminalization and decrypting the exact retained envelope after a simulated lost response. All 89 local Account integration cases skip without Docker, so these two new tests need hosted execution. They prove storage/recovery primitives only, not Account-issued JWT, caller-bound exchange, live ring custody, or activation. The #2876 candidate also adds a local AES-256-GCM response-envelope primitive backed by one Account-only versioned mounted-file ring, with separate connect-token and bare-`LOGIN` purpose keys, key IDs, current-write/older-decrypt rotation, and length-framed exact-operation evidence. Local unit tests execute both-purpose round trips, old-key recovery/removal, wrong-purpose and wrong-operation rejection, and missing/malformed-ring denial. V35 adds an unwired connect-token issuance operation/envelope table with exact identity, digest, pending/terminal state and encrypted-envelope readback; its six PostgreSQL cases reached execution in a prior hosted run, four passed and two failed on a timestamp bind. The corrected-head Account integration task passed, but its success artifact lacks per-test XML. An operator bootstrap candidate creates a protected initial source record once in an owner-only directory and provides an explicit separate rotation action that retains every old purpose key, adds new distinct write keys, and binds a new generation to the previous one without overwriting either source. A separate materializer candidate consumes exact manifest bytes, environment, namespace, generation/predecessor, immutable source-created freshness anchor, and expiry; it verifies retry-stable Secret readback and preserves old decrypt-only keys. The 28 focused materializer tests and combined 139-test developer-tool suite, Ruff, and syntax checks pass locally. Exact-head CI run `36254410583` passed Account Build/Test; its integration task ran and its coverage artifact lists 20 integration classes, but the absent per-case XML prevents an exact executed/skipped count. The aggregate CI gate is red from unchanged Game Session Friends assertions, hosted smoke-tool lint, and an EA-3.1 proof-link check outside #2876's unique diff. Actual protected durable custody, source backup and writer RBAC, deployment/readiness wiring, a live mounted Secret, executed rotation, and proven safe decrypt-only key retirement are still absent. There is no corresponding bare-`LOGIN` operation, wired producer/consumer, or lost-response/live rollout proof. Neither credential path is enabled by the primitive, tool candidates, or V35, and an unavailable key may never authorize reminting. The separately specified credential-bearing `Authenticate` exact-retry envelope is also unimplemented; this two-purpose primitive does not supply its key or enable that operation. From 48680d89f1298867c9f5b7653d1781aeb0aa8dbc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 19:32:01 +1300 Subject: [PATCH 23/46] test(auth): use fresh canonical membership fixture evidence --- .../test/AccountRuntimeStubServerTest.java | 64 ++++++++++++++++++- .../test/AccountRuntimeStubServer.java | 45 +++++++++++-- .../RuntimeMembershipTestFixtures.java | 4 +- 3 files changed, 102 insertions(+), 11 deletions(-) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index 5731efdb9b..4475d3c687 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -4,12 +4,15 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import java.time.Instant; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GetProfileRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.common.account.AccountProfileJson; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import org.junit.jupiter.api.Test; class AccountRuntimeStubServerTest { @@ -41,11 +44,31 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio .setTenantId("1") .setRequestId("request-1")) .build(); - assertThat(stub.getTenantMembershipForRuntime(request).getMembershipLifecycleState()) - .isEqualTo("ACTIVE"); + Instant activeBefore = Instant.now(); + GetTenantMembershipForRuntimeResponse active = stub.getTenantMembershipForRuntime(request); + Instant activeAfter = Instant.now(); + assertThat(active.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(active.getRequestId()).isEqualTo("request-1"); + assertMembershipEventMatches(active, "ACTIVE", true); + assertThat(Instant.parse(active.getEvaluatedAt())).isBetween(activeBefore, activeAfter); + + var secondRequest = + request.toBuilder() + .setPlayerContext( + request.getPlayerContext().toBuilder().setRequestId("request-2").build()) + .build(); + var secondActive = stub.getTenantMembershipForRuntime(secondRequest); + assertThat(secondActive.getRequestId()).isEqualTo("request-2"); + assertMembershipEventMatches(secondActive, "ACTIVE", true); + assertThat(secondActive.getOutboxSourceEvidence(0).getCanonicalEventJson()) + .isEqualTo(active.getOutboxSourceEvidence(0).getCanonicalEventJson()); + assertThat(secondActive.getOutboxSourceEvidence(0).getEventDigest()) + .isEqualTo(active.getOutboxSourceEvidence(0).getEventDigest()); server.denyGameplayAdmission(); + Instant inactiveBefore = Instant.now(); var inactive = stub.getTenantMembershipForRuntime(request); + Instant inactiveAfter = Instant.now(); assertThat(inactive.getMembershipExists()).isTrue(); assertThat(inactive.getGameplayAdmissionAllowed()).isFalse(); assertThat(inactive.getMembershipLifecycleState()).isEqualTo("INACTIVE"); @@ -53,18 +76,55 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio assertThat(inactive.hasAuthorityTuple()).isTrue(); assertThat(inactive.getOutboxCheckpointsCount()).isEqualTo(4); assertThat(inactive.getOutboxSourceEvidenceCount()).isEqualTo(1); + assertMembershipEventMatches(inactive, "INACTIVE", false); + assertThat(Instant.parse(inactive.getEvaluatedAt())) + .isBetween(inactiveBefore, inactiveAfter); server.setMembershipExists(false); + Instant missingBefore = Instant.now(); var membership = stub.getTenantMembershipForRuntime(request); + Instant missingAfter = Instant.now(); assertThat(membership.getMembershipExists()).isFalse(); assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); assertThat(membership.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(membership.getOutboxSourceEvidenceCount()).isZero(); + assertThat(Instant.parse(membership.getEvaluatedAt())) + .isBetween(missingBefore, missingAfter); } finally { channel.shutdownNow(); } } } + private static void assertMembershipEventMatches( + GetTenantMembershipForRuntimeResponse response, String lifecycle, boolean admitted) { + var source = response.getOutboxSourceEvidence(0); + var event = MembershipAuthorityEventV1Codec.verify(source.getCanonicalEventJson()); + assertThat(event.canonicalJson()).isEqualTo(source.getCanonicalEventJson()); + assertThat(event.eventDigest()).isEqualTo(source.getEventDigest()); + assertThat(event.eventId()).isEqualTo(source.getEventId()); + assertThat(event.accountId()).isEqualTo(response.getAccountId()); + assertThat(event.tenantId()).isEqualTo(response.getTenantId()); + assertThat(event.outboxStreamKey()).isEqualTo(source.getOutboxStreamKey()); + assertThat(event.outboxSequence()).isEqualTo(source.getOutboxSequence()); + assertThat(event.membershipLifecycleState()).isEqualTo(lifecycle); + assertThat(event.membershipVersion()).isEqualTo(response.getMembershipVersionMap()); + assertThat(event.membershipAuthorityGeneration()) + .isEqualTo(response.getMembershipAuthorityGeneration()); + assertThat(event.authorityTuple().issuerAuthGeneration()) + .isEqualTo(response.getAuthorityTuple().getIssuerAuthGeneration()); + assertThat(event.authorityTuple().accountAuthorityGeneration()) + .isEqualTo(response.getAuthorityTuple().getAccountAuthorityGeneration()); + assertThat(event.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(response.getAuthorityTuple().getTenantAuthorityGenerationMap()); + assertThat(event.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(response.getAuthorityTuple().getMembershipAuthorityGenerationMap()); + assertThat(event.authorityTuple().privateRealmGrantVersions()).isEmpty(); + assertThat(event.issuanceFence()).isEqualTo(response.getIssuanceFence()); + assertThat(event.roles()).containsExactlyElementsOf(response.getRolesList()); + assertThat(event.gameplayAdmissionAllowed()).isEqualTo(admitted); + } + @Test void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { 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 3b7ce89b02..d203286814 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -40,15 +40,17 @@ import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.account.AccountProfileJson; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; 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 implements AutoCloseable { - private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final String MEMBERSHIP_EVENT_ID = "00000000-0000-0000-0000-000000000099"; + private static final String MEMBERSHIP_EVENT_REQUEST_ID = "runtime-membership-request"; private static final Set IMPLEMENTED_RUNTIME_METHODS = Set.of( "Ping", @@ -214,7 +216,7 @@ public void getTenantMembershipForRuntime( .setMembershipExists(exists) .setMembershipLifecycleState(lifecycle) .setGameplayAdmissionAllowed(admitted) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(Instant.now().toString()) .build(); } responseObserver.onNext(response); @@ -267,17 +269,46 @@ private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( .setAuthorityTuple(tuple) .setIssuanceFence("1") .addAllOutboxCheckpoints(checkpoints) - .setEvaluatedAt(EVALUATED_AT); + .setEvaluatedAt(Instant.now().toString()); if (admitted) { response.addRoles("player"); } if (exists) { + MembershipAuthorityEventV1Codec.MembershipEvent event = + MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", MEMBERSHIP_EVENT_ID), + Map.entry("requestId", MEMBERSHIP_EVENT_REQUEST_ID), + Map.entry("outboxStreamKey", membershipStream), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", "membership/" + accountUuid + "/" + tenantUuid), + Map.entry("accountId", accountUuid), + Map.entry("tenantId", tenantUuid), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", lifecycle), + Map.entry("membershipVersion", Map.of(tenantUuid, "1")), + Map.entry("membershipAuthorityGeneration", "1"), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(tenantUuid, "1"), + "membershipAuthorityGeneration", Map.of(tenantUuid, "1"), + "privateRealmGrantVersions", List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", admitted ? List.of("player") : List.of()), + Map.entry("gameplayAdmissionAllowed", admitted), + Map.entry("callerBoundAuthorityInvalidated", false))); response.addOutboxSourceEvidence( RuntimeOutboxSourceEvidence.newBuilder() .setOutboxStreamKey(membershipStream) .setOutboxSequence("1") - .setEventId("00000000-0000-0000-0000-000000000099") - .setEventDigest("sha256:" + "0".repeat(64))); + .setEventId(event.eventId()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson())); } return response.build(); } @@ -309,7 +340,7 @@ public void getRealmAccessGrantForRuntime( .setRealmSlug(request.getRealmSlug()) .setGranted(realmAccessGranted.get()) .setGrantVersion(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(Instant.now().toString()) .build()); responseObserver.onCompleted(); } @@ -325,7 +356,7 @@ public void getTenantEntitlementsForRuntime( .setAllowPublicJoin(allowPublicJoin.get()) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(Instant.now().toString()) .build()); responseObserver.onCompleted(); } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java index 595b3af693..36b7f5a74d 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.support; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -17,7 +18,6 @@ public final class RuntimeMembershipTestFixtures { private static final String STREAM_PREFIX = "account:auth-authority:v1:"; private static final String ISSUER = "firemud-account-service"; private static final String EVENT_ID = "00000000-0000-0000-0000-000000000099"; - private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; private RuntimeMembershipTestFixtures() {} @@ -123,7 +123,7 @@ private static GetTenantMembershipForRuntimeResponse complete( .setAuthorityTuple(tuple) .setIssuanceFence("1") .addAllOutboxCheckpoints(checkpoints) - .setEvaluatedAt(EVALUATED_AT); + .setEvaluatedAt(Instant.now().toString()); if (admitted) { response.addRoles("player"); } From ebffef6d88bd927354c4da47c1e13f1956d6b813 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 19:55:50 +1300 Subject: [PATCH 24/46] test(auth): keep WebSocket entitlement evidence fresh --- .../websocket/GameSessionWebSocketHandlerIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 3e4e43fc38..b16bd44a52 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -276,7 +276,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) .getTenantEntitlementsForRuntime( From 61ca37fdeea8784448929dd5ce1716f7475fb00c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 20:12:14 +1300 Subject: [PATCH 25/46] test(auth): align WebSocket login expectations with guarded path --- .../GameSessionWebSocketHandlerIntegrationTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index ae73b65914..fb5beab359 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -484,7 +484,7 @@ void websocketLoginThenLookUsesAuthenticatedPath() throws Exception { assertThat(context.roomInstanceId()).isNotBlank(); }); - verify(commandService).enqueue("41", "LOGIN demo@example.com swordfish", false); + verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService).enqueue("41", "LOOK", false); verify(gameLogicClient) .resolveLook( @@ -851,7 +851,7 @@ void websocketLoginCanBrowseRealmsWhileCharactersFailClosed() throws Exception { && payload.contains("Live Realm (production) [shared, allow_new]")); assertThat(payloads) .anyMatch(payload -> payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE")); - verify(commandService).enqueue("41", "LOGIN demo@example.com swordfish", false); + verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); verify(accountClient) @@ -1427,8 +1427,8 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog assertThat(context.worldSlug()).isEqualTo("sandbox"); assertThat(context.realmSlug()).isEqualTo("production"); assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-route-b"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-route-b"); + assertThat(context.connectScopeId()).isNull(); + assertThat(context.connectRequestId()).isNull(); }); } @@ -1514,8 +1514,8 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe assertThat(context.worldSlug()).isEqualTo("demo"); assertThat(context.realmSlug()).isEqualTo("production"); assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-scope-selector-b"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-scope-selector-b"); + assertThat(context.connectScopeId()).isNull(); + assertThat(context.connectRequestId()).isNull(); }); assertThat(gameplayPresenceService.findConnectedBySessionId(2L)).isEmpty(); } From c6fa3ea9436c2cb69a6e13710da4db9a0e53cf3e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 21:52:06 +1300 Subject: [PATCH 26/46] Require executed Script Pin PostgreSQL retry proof in CI --- .github/workflows/ci.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 116ab5656b..97903cc2e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -943,7 +943,7 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - if [[ "${{ matrix.module }}" == "account-service" ]]; then + if [[ "${{ matrix.module }}" == "account-service" || "${{ matrix.module }}" == "game-session-service" ]]; then ./gradlew :${{ matrix.module }}:check -PfullCheck --no-build-cache else ./gradlew :${{ matrix.module }}:check -PfullCheck @@ -961,6 +961,15 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ account-service + - name: 🔎 Verify Game Session PostgreSQL proof case + if: ${{ matrix.module == 'game-session-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamesession.repository.ScriptPinOperationRepositoryIntegrationTest \ + --require-case 'net.firedevops.firemud.gamesession.repository.ScriptPinOperationRepositoryIntegrationTest#pinAdmissionBaseMustStillMatchTheRowLockedRuntimeAndIsBoundToTheReceipt()' \ + game-session-service + - name: 📦 Build Runtime JAR if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) }} run: ./gradlew :${{ matrix.module }}:bootJar -PfullCheck From 1f0577b1f348280c4c630502df9ad5faa0f416e4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 22:57:33 +1300 Subject: [PATCH 27/46] Require executed connect issuance recovery proof in Account CI Extend the existing strict PostgreSQL evidence gate to V35 source issuance, including concurrent first writer, exact lost-response recovery and deletion guards. Parent proof must be propagated before publication. Focused actionlint passes. --- .github/workflows/ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97903cc2e9..9856c37a5f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -957,8 +957,12 @@ jobs: --strict \ --require-suite net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#concurrentExactIssuanceClaimsHaveOneTerminalFirstWriter()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#lostIssuanceResponseRecoversExactEncryptedResultFromDurableReadback(Path)' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#directDeletionOfIssuanceOperationOrResponseEnvelopeIsRejected()' \ account-service - name: 🔎 Verify Game Session PostgreSQL proof case From d83cb33c827b36fcd8e7197ab276a7710eb5fb2c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 23:06:00 +1300 Subject: [PATCH 28/46] Prepare durable verified pair authority within typed snapshots Read verified sequence-zero absence without manual baseline setup; preserve complete authority/checkpoint/source evidence and first JOIN ordering. Unmapped, inactive and retained-history inputs remain denied. Runtime RPC stays unavailable; exact composed validation follows downstream propagation. --- ...countMembershipAuthorityEventProducer.java | 2 +- .../AccountJoinPostgresIntegrationTest.java | 52 ++++++++++++++----- 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 2bcd4229ec..603663812d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -316,7 +316,7 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( if (accountId <= 0L || legacyTenantId <= 0L) { throw new IllegalArgumentException("Account and retained tenant identities must be positive"); } - joinOperationRepository.lockAccount(accountId); + preparePairAuthorityForRuntimeSnapshot(accountId, legacyTenantId); if (membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId).isPresent()) { PositiveMembershipSnapshot positive = readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId); 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 3d3be6cf9e..2953297717 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 @@ -1094,9 +1094,9 @@ void neverJoinedSnapshotRequiresAndRetainsDurablePairBaselineBeforeFirstJoin() { @Test void runtimeMembershipSnapshotKeepsAbsenceAndFirstJoinEvidenceInOneFencedResult() { JoinFixture fixture = fixture("active"); - preparePairAuthorityBaseline(fixture); var absent = readRuntimeMembershipSnapshot(fixture); + Map baselineRow = membershipPairAuthorityRow(fixture); assertThat(absent.requestAccountId()).isEqualTo(fixture.accountId()); assertThat(absent.requestTenantId()).isEqualTo(fixture.tenantId()); assertThat(absent.accountUuid()).isEqualTo(fixture.accountUuid().toString()); @@ -1117,8 +1117,36 @@ void runtimeMembershipSnapshotKeepsAbsenceAndFirstJoinEvidenceInOneFencedResult( assertThat(absent.outboxSourceEvidence()).isEmpty(); assertThat(absent.roles()).isEmpty(); assertThat(absent.issuanceFence()).matches("[1-9][0-9]*"); + assertThat(baselineRow) + .containsEntry("membership_exists", false) + .containsEntry("membership_version", 1L) + .containsEntry("membership_authority_generation", 1L) + .containsEntry("last_event_sequence", 0L) + .containsEntry("last_event_id", null) + .containsEntry("last_event_digest", null); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countAuthorityMembershipEvents(fixture)).isZero(); + assertThat(countAuthorityMembershipStreams(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + assertThat(countMembershipAuthorityGenerations(fixture)).isEqualTo(1L); + assertThat(countMembershipPairAuthorities(fixture)).isEqualTo(1L); - assertThat(join(fixture).success()).isTrue(); + var retriedAbsence = readRuntimeMembershipSnapshot(fixture); + assertThat(retriedAbsence.membershipExists()).isFalse(); + assertThat(retriedAbsence.membershipBaseline()).isEqualTo(absent.membershipBaseline()); + assertThat(retriedAbsence.authorityTuple()).isEqualTo(absent.authorityTuple()); + assertThat(retriedAbsence.outboxCheckpoints()).isEqualTo(absent.outboxCheckpoints()); + assertThat(retriedAbsence.outboxSourceEvidence()).isEmpty(); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(baselineRow); + assertThat(countAuthorityMembershipEvents(fixture)).isZero(); + assertThat(countAuthorityMembershipStreams(fixture)).isZero(); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + + JoinPublicProductionResult joined = join(fixture); + assertThat(joined.success()).isTrue(); + assertThat(joined.membershipVersion()).isEqualTo(2L); + assertThat(joined.membershipAuthorityGeneration()).isEqualTo(1L); var active = readRuntimeMembershipSnapshot(fixture); var event = readPairBoundPositiveMembershipSnapshot(fixture).authorityEvent(); assertThat(active.membershipExists()).isTrue(); @@ -1144,15 +1172,11 @@ void runtimeMembershipSnapshotKeepsAbsenceAndFirstJoinEvidenceInOneFencedResult( event.canonicalJson())); assertThat(active.roles()).contains("player"); assertThat(active.issuanceFence()).matches("[1-9][0-9]*"); + assertThat(active.outboxSourceEvidence()).hasSize(1); } @Test - void runtimeMembershipSnapshotRejectsUnprovedPairAndContradictoryGeneration() { - JoinFixture missingPair = fixture("active"); - assertThatThrownBy(() -> readRuntimeMembershipSnapshot(missingPair)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Never-joined pair baseline is absent"); - + void runtimeMembershipSnapshotRejectsContradictoryGeneration() { JoinFixture contradictoryPair = fixture("active"); preparePairAuthorityBaseline(contradictoryPair); dsl.execute( @@ -1164,7 +1188,7 @@ void runtimeMembershipSnapshotRejectsUnprovedPairAndContradictoryGeneration() { assertThatThrownBy(() -> readRuntimeMembershipSnapshot(contradictoryPair)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining( - "membership authority generation cannot prove its sequence-zero baseline"); + "Absent Account membership differs from its durable pair authority baseline"); } @Test @@ -1233,9 +1257,9 @@ void neverJoinedSnapshotReaderRejectsMissingPairWithoutEnrollingIt() { } @Test - void runtimeSnapshotPreparationRejectsUnmappedTenantAndAbsentMembershipHistory() { + void runtimeMembershipSnapshotRejectsUnmappedTenantAndAbsentMembershipHistory() { JoinFixture unmappedTenant = fixture("active", TenantAssociationSetup.MISSING); - assertThatThrownBy(() -> prepareRuntimeSnapshotAuthority(unmappedTenant)) + assertThatThrownBy(() -> readRuntimeMembershipSnapshot(unmappedTenant)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("approved Account tenant association is absent"); assertThat(countMemberships(unmappedTenant)).isZero(); @@ -1259,7 +1283,7 @@ void runtimeSnapshotPreparationRejectsUnmappedTenantAndAbsentMembershipHistory() assertThat(joined.success()).isTrue(); assertThat(countMemberships(removedMembership)).isZero(); assertThat(countAuthorityMembershipEvents(removedMembership)).isEqualTo(1L); - assertThatThrownBy(() -> prepareRuntimeSnapshotAuthority(removedMembership)) + assertThatThrownBy(() -> readRuntimeMembershipSnapshot(removedMembership)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining( "Retained Account membership history has no supported restoration path"); @@ -1269,7 +1293,7 @@ void runtimeSnapshotPreparationRejectsUnmappedTenantAndAbsentMembershipHistory() } @Test - void runtimeSnapshotPreparationRejectsInactiveMembershipWithoutChangingAuthority() { + void runtimeMembershipSnapshotRejectsInactiveMembershipWithoutChangingAuthority() { JoinFixture fixture = fixture("active"); JoinPublicProductionResult joined = join(fixture); Map pairRow = membershipPairAuthorityRow(fixture); @@ -1280,7 +1304,7 @@ void runtimeSnapshotPreparationRejectsInactiveMembershipWithoutChangingAuthority + "gameplay_admission_allowed = FALSE WHERE id = ?", joined.membershipId()); - assertThatThrownBy(() -> prepareRuntimeSnapshotAuthority(fixture)) + assertThatThrownBy(() -> readRuntimeMembershipSnapshot(fixture)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not a positive active explicit membership"); assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairRow); From c3a0ff17992d4a5244c9cd22b56367c193f14f1b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 23:09:24 +1300 Subject: [PATCH 29/46] Clarify verified enrollment versus unproved snapshot fallback --- .../service/AccountMembershipAuthorityEventProducer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 603663812d..32aac78520 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -306,7 +306,7 @@ public PositiveMembershipSnapshot readCurrentPairBoundPositiveMembershipSnapshot * Reads one same-fence runtime membership result from the proved active-positive or never-joined * sequence-zero path. * - *

This deliberately has no inactive, unpaired, or synthesized fallback. The caller owns the + *

This deliberately has no inactive, unproved, or synthesized fallback. The caller owns the * Account transaction and the RPC remains unavailable until its consumer validates this whole * evidence bundle. */ From 18db99fe0b1f16ecee858b82f30f07106787ed4d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 01:39:29 +1300 Subject: [PATCH 30/46] Converge complete selected-target contexts and deny legacy admission --- ...30-risk-based-active-session-revocation.md | 2 +- ...-safe-session-token-rotation-and-logout.md | 2 +- ...035-single-record-issued-token-registry.md | 39 +- .../microservices/account-service/README.md | 1 + .../account-service/runtime-and-data.md | 4 +- .../game-session-service/README.md | 2 + .../game-session-service/runtime-and-data.md | 2 + .../spring-cloud-gateway/client-behavior.md | 1 + .../system-architecture-authentication.md | 4 +- .../system-architecture-gateway.md | 45 +- ...em-architecture-jwt-and-token-contracts.md | 58 +- .../design-alignment/README.md | 2 +- .../platform-operations-and-delivery.md | 1 + .../player-access-and-session.md | 17 +- ...r-experience-commands-and-communication.md | 18 +- .../service/impl/AccountServiceImpl.java | 93 +-- .../service/impl/AccountServiceImplTest.java | 169 +++-- services/common-security/build.gradle.kts | 2 + .../security/GatewayConnectContext.java | 95 +++ .../security/GatewayConnectContextCodec.java | 607 +++++++++++++++++ .../GatewayConnectContextCodecTest.java | 436 ++++++++++++ ...lectedTargetConnectContextTestVectors.java | 87 +++ .../FirstPartyConnectContextConfig.java | 21 - .../FirstPartyConnectContextProperties.java | 2 +- .../FirstPartyConnectContextService.java | 78 +-- ...ommunicationWebSocketCrossServiceTest.java | 428 +----------- ...essionWebSocketHandlerIntegrationTest.java | 641 +----------------- .../FirstPartyConnectContextServiceTest.java | 418 ++---------- .../filter/GameplayHandshakeFilter.java | 90 +-- .../filter/GameplayHandshakeFilterTest.java | 114 +--- 30 files changed, 1583 insertions(+), 1896 deletions(-) create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContext.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java create mode 100644 services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/SelectedTargetConnectContextTestVectors.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java diff --git a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md index be9f80d9a8..dd666691d9 100644 --- a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md +++ b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md @@ -28,7 +28,7 @@ The previous target distinguished soft and hard billing states and required even ### Canonical Authority Tuple Boundary -[ADR 0035](./adr-0035-single-record-issued-token-registry.md) owns the single normative `authorityTuple` schema and exact field names. This ADR does not redefine that schema. It applies the tuple unchanged to revocation events, Account leases, gameplay bindings, and active-session cutoff decisions; `issuanceFence` remains the Account composite authority fence copied alongside the tuple, never a substitute for a tuple member. Account carries the same fence through applicable canonical outbox and logout/revocation evidence so consumers cannot accept authority evidence assembled across different Account linearization points. +[JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) owns the single normative `authorityTuple` schema and exact field names. This ADR does not redefine that schema. It applies the tuple unchanged to revocation events, Account leases, gameplay bindings, and active-session cutoff decisions; `issuanceFence` remains the Account composite authority fence copied alongside the tuple, never a substitute for a tuple member. Account carries the same fence through applicable canonical outbox and logout/revocation evidence so consumers cannot accept authority evidence assembled across different Account linearization points. Revocation-local admission decisions, exact-binding leases, and gameplay bindings also carry the complete canonical `outboxCheckpoints` set: one exact `{outboxStreamKey, outboxSequence}` entry for every applicable scoped outbox stream. This set is admission freshness evidence, not a member of `authorityTuple` or a general JWT/registry claim, and any stream coordinates embedded in cutoff evidence must equal their corresponding set entries. diff --git a/design/architecture/decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md b/design/architecture/decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md index 570bb9871e..9c9b0bf473 100644 --- a/design/architecture/decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md +++ b/design/architecture/decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md @@ -28,7 +28,7 @@ The current target already requires periodic refresh, atomic binding replacement ### Canonical Authority Tuple Boundary -[ADR 0035](./adr-0035-single-record-issued-token-registry.md) owns the single normative `authorityTuple` schema and exact field names. This ADR references that schema without redefining it. Rotation-local requirements copy the unchanged tuple into every applicable JWT/registry snapshot, Account lease, gameplay binding, refresh request, rebind proof, installation acknowledgement, and outbox payload; `issuanceFence` is copied alongside it as the Account composite authority fence captured by the issuance transaction or CAS. `membershipBaseline` is the one immutable Account-snapshot carrier `{membershipLifecycleState, membershipVersion, membershipAuthorityGeneration}` for a tenant-bound gameplay binding, where `membershipVersion` is the complete canonical exact one-tenant map `{tenantId: version}`. The baseline remains independent from the other tuple members, and its lifecycle, map, and generation are compared as one object. Alongside the tuple and unchanged baseline, `outboxCheckpoints` is the complete set of one exact `{outboxStreamKey, outboxSequence}` checkpoint for every applicable authority stream in the operation scope, with no aggregate maximum or omitted stream. It is canonicalized in stream-key order and copied unchanged through protected binding metadata, the installation claim and acknowledgement, binding CAS payloads, replacement leases, `TOKEN_ROTATION` operation evidence, retries, reconciliation records, and rotation proofs. Any missing, extra, stale, regressed, or mismatched baseline or checkpoint fails closed; checkpoints prove source position but never become an alternate authority. An authenticated Account event may update only a derived consumer-local projection after its checkpoint is validated, never the Account authority or source evidence. +[JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) owns the single normative `authorityTuple` schema and exact field names. This ADR references that schema without redefining it. Rotation-local requirements copy the unchanged tuple into every applicable JWT/registry snapshot, Account lease, gameplay binding, refresh request, rebind proof, installation acknowledgement, and outbox payload; `issuanceFence` is copied alongside it as the Account composite authority fence captured by the issuance transaction or CAS. `membershipBaseline` is the one immutable Account-snapshot carrier `{membershipLifecycleState, membershipVersion, membershipAuthorityGeneration}` for a tenant-bound gameplay binding, where `membershipVersion` is the complete canonical exact one-tenant map `{tenantId: version}`. The baseline remains independent from the other tuple members, and its lifecycle, map, and generation are compared as one object. Alongside the tuple and unchanged baseline, `outboxCheckpoints` is the complete set of one exact `{outboxStreamKey, outboxSequence}` checkpoint for every applicable authority stream in the operation scope, with no aggregate maximum or omitted stream. It is canonicalized in stream-key order and copied unchanged through protected binding metadata, the installation claim and acknowledgement, binding CAS payloads, replacement leases, `TOKEN_ROTATION` operation evidence, retries, reconciliation records, and rotation proofs. Any missing, extra, stale, regressed, or mismatched baseline or checkpoint fails closed; checkpoints prove source position but never become an alternate authority. An authenticated Account event may update only a derived consumer-local projection after its checkpoint is validated, never the Account authority or source evidence. The `membershipBaseline` is a first-class carrier, not a scalar alias or three independently sourced fields. For the tenant-bound rotation scope its `membershipVersion` key set is exactly `{tenantId}`, its value is a JSON string in the canonical grammar `0` or `[1-9][0-9]*`, and only a process-local arbitrary-precision extraction may use that value as a scalar. The complete unchanged baseline is carried and exact-compared through every rotation boundary: the Account refresh request and serializable predicate; `TOKEN_ROTATION` operation stages; replacement lease; pending, active, and retiring registry postconditions; `rebindHandle`; `PENDING` rebind attempt and response envelope; first binding CAS and readback; installation claim, `BINDING_INSTALLED` attempt, acknowledgement request, acknowledgement digest, and Account `INSTALLED` postcondition; second binding CAS; every retry, abort/retire path, and reconciler; and every durable rotation record and proof. A missing, extra, differently keyed, scalarized, stale, regressed, or cross-snapshot lifecycle, map, generation, or baseline fails closed. No stage may reconstruct the baseline from a tuple member, a high-water mark, or a latest-only membership value. diff --git a/design/architecture/decisions/adr-0035-single-record-issued-token-registry.md b/design/architecture/decisions/adr-0035-single-record-issued-token-registry.md index a6840ced8c..abfe427775 100644 --- a/design/architecture/decisions/adr-0035-single-record-issued-token-registry.md +++ b/design/architecture/decisions/adr-0035-single-record-issued-token-registry.md @@ -28,43 +28,16 @@ Tenant and global authorization already comes from strictly validated signed cla The current implementation writes account and tenant keys but does not consistently enforce the complete registry contract in downstream validators. Global entries, full authority-generation enforcement, and end-to-end revocation proof remain incomplete. -### Canonical Authority Tuple +### Registry and Gameplay-Connect Profile Boundary -Within this ADR set, ADR 0035 owns the single normative registry/revocation `authorityTuple` schema and exact nested field names, aligned with the canonical runtime contract in [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md). Other ADRs reference this schema and may add only local lifecycle or proof requirements; they must not duplicate, rename, or reinterpret tuple members. +The canonical `authorityTuple` schema, exact nested field names, JWT profile shapes, and token-to-context mappings are owned by [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) and its [Account-signed selected-target gameplay-connect schema](../system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema). This ADR defines how registry-backed records and lifecycle operations consume that authority; it does not duplicate or rename the canonical schema. -Every registry-backed JWT claim set, registry record, revocation event, Account lease, gameplay binding, refresh request, rebind proof, and installation acknowledgement uses the same logical `authorityTuple` and exact field names. The separate `gameplay-connect` profile is outside the issued-token-registry schema and has its own versioned field set. Its signed claims are exactly `iss`, `aud`, `iat`, `exp`, `jti`, `accountId`, `tenantId`, `gameInstanceId`, `worldSlug`, `realmSlug`, `pointerVersion`, `catalogRevision`, `connectScopeId`, `requestId`, bounded selected-target `authorityTuple`, separate exact `membershipVersion`, and `replayAdmissionFence`, with `kid` carried in the JOSE header. The tuple and membership map are immutable issuance evidence for the later exact-binding admission checks, and the profile uses ADR 0029's single-use replay contract instead of an ordinary registry record or Account evidence-bundle read at Gateway. +Registry-backed JWT claims, registry records, revocation events, Account leases, gameplay bindings, refresh requests, rebind proofs, and installation acknowledgements use the applicable canonical `authorityTuple` unchanged. `gameplay-connect` is outside the ordinary issued-token registry and uses the dedicated Account issuance/replay record and Gateway single-use replay contract in ADR 0029. Its exact Account-signed selected-target claim set is defined only in JWT and Token Contracts. The Gateway context is a separate signed assertion; its source-to-context field mappings and receiver bindings are defined by the JWT and Gateway architecture owners. -The gameplay-connect profile explicitly forbids ordinary-registry fields that are not in that field set: `schemaVersion`, registry `issuer`/profile/type fields as claim aliases, `sub`, `nbf`, `signerGeneration`, `tokenGeneration`, `issuanceFence`, registry `state`, Account registry bundle/source/freshness fields, and rotation/lease/installation fields such as `rotationOperationId`, `leaseId`, `leaseVersion`, `gameplayBindingId`, and `installationFence`. `iss`, `aud`, `iat`, `exp`, `jti`, `accountId`, `authorityTuple`, and `membershipVersion` are allowed gameplay-connect claims and do not make the profile registry-backed. The Account `connect-token-issuance-evidence/v1` carrier and dedicated replay record use the same gameplay-connect target, tuple, membership, `jti`, `iat`, `exp`, and `replayAdmissionFence` evidence; they may additionally carry only their operation/request identity, digest, replay-record identity, Account source/checkpoint references, and bounded issuance/retry evidence. The Gateway-signed context carries those same values, names `jti` as `connectTokenJti`, and adds only its transport verification fields (`verifiedAt`, `expiresAt`, and `gatewayRequestId`). These names are carriers of the same evidence, not alternate authority fields. +The `gameplay-connect` profile has no ordinary `session:auth:token:` record, `tokenGeneration`, or `issuanceFence`; its exact required and forbidden claims, including conditional lifecycle fields, are those in the canonical profile table. The Account issuance carrier and dedicated replay record bind the source token identity, selected target, exact authority evidence, and `replayAdmissionFence` under their own durable operation identity and digest. Gateway preserves the selected target and authority evidence, maps the source `requestId`, `jti`, and `iat` to context `connectRequestId`, `connectTokenJti`, and `issuedAt`, and adds only its registered receiver and verification fields as defined in [Gateway Architecture](../system-architecture-gateway.md#gateway-output-rules-downstream-trusted). In this ADR, unqualified references to the ordinary JWT registry, registry state, or `tokenGeneration` apply only to the registry-backed profiles. `gameplay-connect` retains its separate Account issuance/replay record, signed `replayAdmissionFence`, Gateway `jti` consume marker, and dedicated replay/fence acceptance contract; it never inherits ordinary registry or generation checks. -```text -authorityTuple: { - issuerAuthGeneration, - accountAuthorityGeneration, - tenantAuthorityGeneration: { tenantId: generation }, - membershipAuthorityGeneration: { tenantId: generation }, - privateRealmGrantVersions: [ - { tenantId, worldSlug, realmSlug, playtestLifecycleId, grantVersion } - ], - accountSecurityCutoff: { - accountAuthorityGeneration, - outboxStreamKey, - outboxSequence - }?, - tenantBillingCutoff: { - tenantId: { - tenantAuthorityGeneration, - tenantBillingSequence, - outboxStreamKey, - outboxSequence - } - }? -} -``` - -`issuerAuthGeneration` and `accountAuthorityGeneration` are positive Account-owned generations. `tenantAuthorityGeneration` and `membershipAuthorityGeneration` are independent maps keyed by exact tenant IDs; each map's applicable keys are determined separately by the token profile and route classification. The closed `billing_safe_tenant` exception can therefore require a membership entry while deliberately omitting the target-tenant generation. Explicitly unscoped artifacts use empty maps. `privateRealmGrantVersions` contains exact `{tenantId, worldSlug, realmSlug, playtestLifecycleId, grantVersion}` entries for every non-public grant, including ordinary private and playtest grants, and is empty for public production. There is no ordinary-private grant entry without `playtestLifecycleId`. `accountSecurityCutoff` and `tenantBillingCutoff` are optional cutoff evidence, not replacement authorities; each is omitted when it is not applicable, and a present `tenantBillingCutoff` contains only exact applicable tenant-ID entries. `membershipVersion` is a separate Account-owned membership projection/version map. Its one canonical non-applicable representation is the empty map `{}`; it is never omitted, `null`, a scalar sentinel, or a textual not-applicable value. When applicable, it contains only exact tenant-ID entries. The JWT claim, registry field, Account evidence-bundle value, and binding value must be structurally and value-equal; `membershipVersion` is compared independently from `membershipAuthorityGeneration`, and neither field substitutes for the other. A missing applicable field, extra scope, malformed value, or mismatch fails closed. - The mandatory `playtestLifecycleId` requirement follows the direct-cutover contract in [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md) and [ADR 0138](./adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md): a non-public grant-bearing record or token that lacks it fails closed and is invalidated, unless objective retained-data evidence first proves one unambiguous current lifecycle for an explicit migration and fresh grant/token issuance. No dual-format read, four-field alias, or runtime compatibility bridge is permitted. The tuple is copied without renaming or reinterpretation into every applicable registry record/claim, payload, lease, binding, refresh request, rebind proof, and installation acknowledgement. `issuanceFence` is copied alongside the tuple as the Account composite authority fence captured by the issuance transaction or CAS; it is not a substitute for any tuple member. @@ -77,7 +50,7 @@ Account exposes one immutable, versioned `account-auth-evidence-bundle/v1` for e Account issuance and refresh use one Account transaction or composite CAS/fence to create the durable Account evidence and the versioned `account-auth-evidence-bundle/v1` reference. That transaction/CAS does not create the Coordination Redis registry record or any Redis lease or Game Session binding/installation. Each operation-bound registry, lease, binding transition, and installation postcondition is separately versioned, fenced, and idempotent outside the Account transaction and carries the same immutable `operationId`, caller `requestId`, canonical request digest, token digest, and `issuanceFence`; retries and reconciliation apply only missing postconditions. A steady-state gameplay binding instead retains the canonical ADR 0031 binding schema and does not acquire operation-scoped fields after its transition is terminal. `operationId` identifies the one durable Account operation and cannot change after creation. `requestId` is the immutable logical retry identity supplied by the owning API; where a public surface uses `requestId` as its operation ID, it remains the same single identity and no second public identifier is introduced. The canonical token digest is `tokenHash`, the fixed-length SHA-256 digest of the complete compact JWT, and it is immutable for that token identity; it is distinct from the canonical request digest, which never contains raw JWT bytes. The registry record stores the matching Account `bundleVersion`, `sourceVersion`, `sourceFence`, and freshness/linearization evidence with its tuple. Lease, operation-bound binding transition, and installation evidence stores its owning service's positive version/fence plus the exact registry identity and Account bundle reference it satisfies. -Every registry-backed JWT authorization attempt, including `IssueConnectToken` with a presented `player-bootstrap`, performs exactly one atomic issued-token registry lookup, which must return the exact `state=active` record and its positive registry version, then reads exactly one complete immutable Account bundle and each applicable downstream owner evidence at the exact version/fence named by the registry or durable operation. It compares the JWT, registry tuple, every applicable cutoff as its complete generation-plus-`outboxStreamKey`-plus-`outboxSequence` tuple, every applicable `outboxCheckpoint`, separate `membershipVersion`, Account fences, and each independently owned lease, binding, or installation version as one decision. The `membershipVersion` claim, registry field, and Account evidence value must use the same exact map, including `{}` for non-applicable membership; no omitted/null/sentinel form is equal. If an owner reports that a requested bundle, registry-linked postcondition, or version/fence was superseded while it was being read, the consumer discards the entire attempt and retries from a new registry lookup; a second change or any reachable mismatch denies. Timeouts and unavailable owners return retryable `AUTH_UNAVAILABLE`. No consumer rereads unrelated fields, combines evidence from different attempts, or claims a cross-store atomic snapshot. +Every registry-backed JWT authorization attempt, including `IssueConnectToken` with a presented `player-bootstrap`, performs exactly one atomic issued-token registry lookup, which must return the exact `state=active` record and its positive registry version, then reads exactly one complete immutable Account bundle and each applicable downstream owner evidence at the exact version/fence named by the registry or durable operation. It compares the JWT, registry tuple, every applicable cutoff as its complete generation-plus-`outboxStreamKey`-plus-`outboxSequence` tuple, every applicable `outboxCheckpoint`, separate `membershipVersion`, Account fences, and each independently owned lease, binding, or installation version as one decision. The `membershipVersion` claim, registry field, Account evidence value, and each applicable lease, binding, rebind, rotation, installation, and retry carrier must preserve exactly equal map structure and key/value pairs, including canonical `{}` for non-applicable membership; no omitted, `null`, scalar, or sentinel form is equal. `membershipVersion` remains an independent comparison from `authorityTuple.membershipAuthorityGeneration`; both values must match the same applicable Account authority snapshot. If an owner reports that a requested bundle, registry-linked postcondition, or version/fence was superseded while it was being read, the consumer discards the entire attempt and retries from a new registry lookup; a second change or any reachable mismatch denies. Timeouts and unavailable owners return retryable `AUTH_UNAVAILABLE`. No consumer rereads unrelated fields, combines evidence from different attempts, or claims a cross-store atomic snapshot. An unreachable or timed-out Account bundle, registry, lease, binding, or evidence source is unavailable and returns retryable `AUTH_UNAVAILABLE`. A reachable bundle or record that is missing, malformed, ambiguous, stale, regressed, expired, or mismatched is authoritative invalid/revoked evidence and denies the operation; it is not reclassified as unavailable. The same classification applies to retries and reconciliation, so a timeout cannot become success and reachable invalid evidence cannot become an availability exception. @@ -236,7 +209,7 @@ Opaque tokens can provide the same server-side revocation but require the state - Define one versioned bounded record schema with exact issuer/`iss` mapping, a non-empty string JWT `kid`, exact `signerGeneration`/`kid` linkage, immutable `operationId`/`requestId` and request-digest semantics, token `tokenHash` semantics, profile-specific `tokenGeneration` semantics, and mandatory conditional rotation fields on every supported version, and validate every field against the cryptographically verified token and matching Account-owned evidence. - Prove that registry `iat`/`nbf`/`exp` values remain UTC epoch seconds, every catalog entry has a finite `maxTokenLifetimeSeconds`, logical expiry denies at `exp`, and physical TTL uses checked `max(0, exp * 1000 - now_ms) + FIREMUD_AUTH_SESSION_SAFETY_MARGIN_MS`; prove the exact boundary, over-limit rejection, and overflow/rejection behavior for active and expired records without treating the safety margin as authorization time. - Make issuance return contingent on successful reconciliation of every required separately fenced registry, lease, binding, installation, and `pending -> active` activation postcondition; prove cardinality and claim-shape rejection before the one signing operation, compact-JWT/`tokenHash` and canonical-record byte measurement after signing, and all byte-limit rejection before durable issuance commit or registry registration. Account evidence alone never leaks a usable unregistered or non-`active` token and partial postcondition failure remains recoverable. -- Prove `IssueConnectToken` locally validates the presented `player-bootstrap`, performs exactly one active issued-token registry lookup and exactly one Account `account-auth-evidence-bundle/v1` read, and rejects cache-only, claim-only, duplicate-read, missing, stale, or mismatched evidence; prove `selectedRouteMembershipEvidence` contains `membershipLifecycleState=ACTIVE`, the exact one-tenant `membershipAuthorityGeneration` map, and the exact one-tenant `membershipVersion` map from the same Account membership snapshot, rejecting missing, non-`ACTIVE`, stale, regressed, separately assembled, or mismatched evidence. Prove `connect-token-issuance-evidence/v1` exact map cardinality, carrier/replay-record byte caps, operation/digest/`jti`/fence binding, exact `runtimeEntitlementAuthorityReference` and `admissionPointerAuthorityReference` binding in the same Account issuance evidence boundary, durable exact-retry replay, and rejection before signing or dedicated replay-record acceptance. Prove the gameplay-connect/v1 field set and its replay-record, Account carrier, and Gateway context mappings use exactly the shared target, bounded selected-target `authorityTuple`, separate `membershipVersion`, token identity, and `replayAdmissionFence` evidence; reject every forbidden ordinary-registry field listed above, never enter the zero-cardinality `player-bootstrap` JWT claims or ordinary registry record, and use the no-registry replay exception only for the minted artifact. +- Prove `IssueConnectToken` locally validates the presented `player-bootstrap`, performs exactly one active issued-token registry lookup and exactly one Account `account-auth-evidence-bundle/v1` read, and rejects cache-only, claim-only, duplicate-read, missing, stale, or mismatched evidence; prove `selectedRouteMembershipEvidence` contains `membershipLifecycleState=ACTIVE`, the exact one-tenant `membershipAuthorityGeneration` map, and the exact one-tenant `membershipVersion` map from the same Account membership snapshot, rejecting missing, non-`ACTIVE`, stale, regressed, separately assembled, or mismatched evidence. Prove `connect-token-issuance-evidence/v1` exact map cardinality, carrier/replay-record byte caps, operation/digest/`jti`/fence binding, exact `runtimeEntitlementAuthorityReference` and `admissionPointerAuthorityReference` binding in the same Account issuance evidence boundary, durable exact-retry replay, and rejection before signing or dedicated replay-record acceptance. Prove the canonical [`gameplay-connect/v1` field set and mappings](../system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema) across its replay record, Account carrier, and Gateway context using the exact selected target, bounded `authorityTuple`, separate `membershipVersion`, token identity, and `replayAdmissionFence`; reject every claim forbidden by that profile, never enter the zero-cardinality `player-bootstrap` JWT claims or ordinary registry record, and use the no-registry replay exception only for the minted artifact. - Update shared validators so every applicable JWT-presenting registry-backed control-plane, bootstrap, and admission operation performs local token-profile validation and exactly one active registry lookup followed by exactly one Account evidence-bundle read before scope authorization. - Prove missing, expired, malformed, unsupported-version, missing/wrong `kid`, state-specific `pending`/`active`/`retiring`/`revoked`, wrong-profile, wrong-account, wrong-generation, missing/mismatched conditional rotation evidence, deleted, and unavailable registry state fails closed with stable errors. - Prove per-token logout durably advances the exact-token `PENDING_LOGOUT` fence before deleting one record and leaves other tokens active; prove stale refresh, rebind, installation, and reconciliation CAS paths cannot recreate or mutate that logged-out identity, while rotation establishes a valid replacement before exposure and removes the predecessor after bounded overlap. diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 3baa4d7a85..5e25d46118 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -6,6 +6,7 @@ Manages user accounts and authentication for the platform. It stores profile dat ## Implementation Status +- Gameplay connect-token success is currently denied, including legacy successful replay, until Account can prove the complete selected-target issuance evidence. The target first-party bootstrap/`LOGIN`/`PLAY` description above is not a usable end-to-end path; see [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) for the producer and proof gates. - Provider-specific external identity linking is target-state only; no provider is advertised until its server-verified authorization, global subject uniqueness, recovery, unlink, and end-to-end login proof are complete. - The caller-asserted external-link persistence/service scaffold remains unsupported implementation drift, but its REST route is removed and the exact legacy public-edge path is denied. No provider integration is advertised or externally available. - Credential-bearing gameplay `Authenticate` and its verified-email challenge authenticate global Account identity without a tenant or membership prerequisite. The resulting private delegation token is account-scoped; Game Session retains any bootstrap tenant only as local transport context, and selected-target membership, grant, and entitlement remain separate `JOIN`/`PLAY` checks. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1dee510d8f..9bbd75cbd6 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -24,7 +24,9 @@ The current public registration path creates only a global Account row and a pla Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. Game Session `PLAY` validates lifecycle consistency against existence, admission, and version fields and rejects a missing or nonpositive membership authority generation. It does not validate `authorityAvailability`, roles, the complete `authorityTuple`, or `outboxCheckpoints`; those fields remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. The current entitlement response likewise lacks the complete Account-authenticated bundle, caller/target binding, authority tuple, billing cutoff, checkpoint set, and fence evidence required by the target contract. Its consumer checks only the represented tenant, positive entitlement version, and evaluation-time fields; this subset does not establish complete snapshot or fence proof. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present. The membership proto and Game Session consumer now carry typed `PlayerExecutionContext`, but Account's handler still returns `FAILED_PRECONDITION` before producer/data access; the held-back candidate producer/consumer path and its complete snapshot proof remain incomplete. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public REST realm discovery, character listing, and connect-token issuance now fail closed even when the legacy four-field grant row exists, because it cannot prove the current lifecycle and state generation. The target lifecycle-qualified grant authority is not implemented; public-production REST behavior remains unchanged. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. Game Session `PLAY` validates lifecycle consistency against existence, admission, and version fields and rejects a missing or nonpositive membership authority generation. It does not validate `authorityAvailability`, roles, the complete `authorityTuple`, or `outboxCheckpoints`; those fields remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. The current entitlement response likewise lacks the complete Account-authenticated bundle, caller/target binding, authority tuple, billing cutoff, checkpoint set, and fence evidence required by the target contract. Its consumer checks only the represented tenant, positive entitlement version, and evaluation-time fields; this subset does not establish complete snapshot or fence proof. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present. The membership proto and Game Session consumer now carry typed `PlayerExecutionContext`, but Account's handler still returns `FAILED_PRECONDITION` before producer/data access; the held-back candidate producer/consumer path and its complete snapshot proof remain incomplete. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public REST realm discovery, character listing, and connect-token issuance now fail closed even when the legacy four-field grant row exists, because it cannot prove the current lifecycle and state generation. The target lifecycle-qualified grant authority is not implemented. Public-production discovery and explicit `JOIN` retain their existing behavior, but connect-token issuance currently fails closed and produces no successful selected-target credential until the complete evidence path is available. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. + +The latest local Unit 1B source checkpoint also rejects both cached idempotent replay and freshly constructed success when the complete selected-target authority evidence is unavailable. This is a fail-closed guard, not a complete Account-signed `gameplay-connect` producer, durable issuance proof, or activation of the target `IssueConnectToken` RPC; end-to-end source evidence and consumer proof remain open. The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. The membership request now carries typed `PlayerExecutionContext`, and Game Session sends that typed context; Account's handler still denies before producer/data access with `FAILED_PRECONDITION`. The held-back candidate producer/consumer path remains incomplete, so this typed request is not a working admission path or proof of the target membership/entitlement snapshot. The entitlement and realm-grant reads retain their local request shapes and must likewise remain denied until their exact caller/target contracts are carried and verified. diff --git a/design/architecture/microservices/game-session-service/README.md b/design/architecture/microservices/game-session-service/README.md index 871c6afd12..c13327621a 100644 --- a/design/architecture/microservices/game-session-service/README.md +++ b/design/architecture/microservices/game-session-service/README.md @@ -30,6 +30,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status +First-party context admission currently fails closed. The complete codec is a component boundary, not an enabled bare-`LOGIN` exchange or first-party gameplay proof; independent Gateway keys, canonical identity mapping, and Account producer/consumer proof remain required in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + Current seams are narrower: patch/request convergence reads, instance-scoped pause/resume, region-epoch fencing, and existing version-fence paths do not yet prove complete `scriptPinEpoch` propagation, final-effect enforcement, or Game-Session-owned append-only history. Track those implementation and proof gaps in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). ## Terminology diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 5a0e93f475..a6bdc412a0 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- The shared Gateway connect-context codec now declares and verifies the complete signed-context shape and has local vectors, but first-party runtime parsing remains fail-closed. It does not admit the target context until the independent Gateway Ed25519 verification key is published, Account-to-tenant UUID mapping is available, and the real Account exchange/source-evidence path is proved. Codec and vector presence is not a live issuer/consumer handoff or gameplay-admission proof. + - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. - **Target effective-settings boundary:** keep this as a read-only operator surface but make authorization route-aware. Bind a tenant-scoped role to the exact target tenant and require persisted session tenant ownership/equality; allow a global `platformAdmin` branch to select a tenant only with current operator authorization, target-tenant generation, and `privileged_control`. Reject ambiguous/missing target authority, tenant/session mismatches, and unavailable owner/session evidence before invoking any resolver. The negative proof must cover scoped cross-tenant synthetic and persisted-session reads and the global branch without privileged control. - Script pin/epoch rollout remains partial: the authoritative `{scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId}` owner read, CAS-backed pin transition, and instance-bound Automation admission epoch validation are live. Local instance-scoped Automation admission, duplicate replay, durable tick staging/replay, and final Game Session execution now compare the complete tuple; the live ledger is still limited to current atomic request/result rows, and bounded rollout-history readback plus complete source/target remote command identity and final-effect fencing remain gaps. See the [canonical runtime-execution owner](../../system-architecture-scripting-runtime-execution.md#normative-target-contract) and the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). diff --git a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md index d1718c1a24..0780e14e28 100644 --- a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md +++ b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md @@ -37,6 +37,7 @@ Unless explicitly described as current behavior, the sections below define the t - 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 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. +- The latest local first-party handshake guard refuses to create the Gateway context before replay-marker mutation when the independent Ed25519 signing key is unavailable. The shared full-context codec and vectors are component-level artifacts, not proof of a live complete Account/Gateway/Game Session producer-consumer path; key publication/rotation, exact selected-target binding, replay continuity, and activation proof remain open. - **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). - The current public `/api/session/**` inventory is limited to `GET /api/session/ping`; internal `/sessions*` mutations remain non-public. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 42284c0791..1b4ea65b2f 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -373,9 +373,9 @@ Authentication-local consequences are limited to bootstrap and admission sequenc Gateway strips the external carrier and attaches one signed, short-lived non-JWT context. Gateway owns issuance, replay, its dedicated asymmetric signing-key namespace, verification-key publication and rotation, and carrier policy as defined by [Gateway architecture](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake). Game Session owns receiving-service validation, including explicit audience/recipient binding, before applying gameplay admission. A JWS serialization does not turn this envelope into an Account-issued JWT profile or permit reuse of Account signing keys. -Minimum context fields are `accountId`, `tenantId`, `realmId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `playtestLifecycleId` and positive `playtestStateGeneration` when the target is non-public (both absent for public production), `gameInstanceId`, `pointerVersion`, `catalogRevision`, `connectScopeId`, `connectRequestId`, `audience: game-session`, `recipient: game-session-service`, the exact bounded selected-target `authorityTuple`, separate exact `membershipVersion`, `connectTokenJti`, `replayAdmissionFence`, `issuedAt`, `verifiedAt`, `expiresAt`, and `gatewayRequestId`. The signed context's `issuedAt`-to-`expiresAt` lifetime is no longer than 30 seconds, subject only to the configured bounded clock-skew handling owned by Gateway. `connectRequestId` is the canonical signed-context name and carries the source `gameplay-connect` token's `requestId` (the connect-token issuance/request-operation identity); the context does not expose that source field under the generic name `requestId`. +The complete Account-signed selected-target claim set and source-to-context name mapping are defined by [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema); the Gateway-owned receiver bindings, verification timestamps, and bounded context deadline are defined by [Gateway Architecture](./system-architecture-gateway.md#gateway-output-rules-downstream-trusted). Authentication does not duplicate that schema. Its local receiving-service contract is to validate the complete signed assertion and its registered `audience`/`recipient` before using the Account-selected identity, target, or authority evidence. The context deadline is absolute: clock skew cannot rewrite source `issuedAt` or extend `expiresAt`. -- Game Session validates the asymmetric signature and `kid` against Gateway verification keys, validates the exact audience/recipient binding, enforces the bounded expiry, and rejects missing, invalid, wrong-recipient, or expired context with `CONNECT_CONTEXT_INVALID` before `PLAY`. +- Game Session validates the asymmetric signature and `kid` against Gateway verification keys, validates the exact audience/recipient binding, enforces `expiresAt` without post-expiry grace, and rejects missing, invalid, wrong-recipient, or expired context with `CONNECT_CONTEXT_INVALID` before `PLAY`. - Game Session does not implement a second replay authority for `connectTokenJti`; it treats that value as access-controlled correlation and must not emit it as a metric label, ordinary log field, or trace attribute. - `CONNECT_SCOPE_MISMATCH` is computed by exact comparison of this verified context and server-resolved first-party scope `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion}`; non-public targets additionally compare `playtestLifecycleId` and positive `playtestStateGeneration`, while public-production targets omit both. It is never computed from raw `X-Tenant-Id` or `X-Game-Instance-Id` headers. - Verification-key cache refresh and bounded failure reasons remain the Gateway/Game Session operational contract; unknown or unavailable keys fail closed. diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 5256fde783..8d7c180fce 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -14,9 +14,9 @@ Unless otherwise noted, this document describes target-state gateway behavior. C - **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. The Gate 2 candidate adds a watched projected Gateway listener certificate/key and client CA for new handshakes, preserving established bridges; local reload tests are not hosted served-certificate or convergence proof. 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. +- 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` denies first-party admission before replay mutation; its retained legacy marker helper is not a target browser-deny, readiness, or replay-fence writer. 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. - Dynamic REST and gRPC route-management APIs remain local/dev/test-only ephemeral capabilities. The current implementation does not yet enforce the target profile, endpoint isolation, validation, or startup boundary, so these APIs must not be treated as production-safe merely because they exist. -- Connect-token carrier parsing, required routing claims, expiry, and Redis replay checks are implemented for `/ws/game/**`, but current claims and the emitted signed context do not carry and prove durable `realmId`, the current carrier path still does not reject duplicate header values or duplicate token cookies, and successful cookie authentication strips the connect-token cookie carrier from the forwarded request. The protected-cookie `/ws/game/**` variant and bootstrap-backed bare `LOGIN` handoff are implemented but non-promotable in player-facing environments until the named Gateway readiness evidence is complete: exact selector-to-`{tenantId, realmId}` resolution and claim/context equality, carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. The target contract also requires explicit future-`iat` tolerance, `exp` tolerance, and the 30-second `iat`-to-`exp` hard maximum; the current shared `JwtUtil` parser uses JJWT defaults (no configured clock skew), and `GameplayHandshakeFilter` does not yet explicitly enforce those target `iat`/lifetime bounds. These readiness gaps do not mean that the existing signature, claim, expiry, carrier, or replay checks are absent. +- Connect-token carrier parsing and legacy signature/routing checks remain local seams for `/ws/game/**`, but first-party context creation, forwarding, and admission are denied before replay mutation. No independent Ed25519 signer is wired into the runtime, and neither the protected-cookie path nor bootstrap-backed bare `LOGIN` is currently usable. The shared full-context codec and vectors prove only their focused semantic boundary, not a live Account-to-Gateway-to-Game Session handoff. Complete Account selected-target issuance, independent Gateway key publication, ambiguous-carrier rejection, selector/claim/context equality, replay-marker durability and quarantine continuity, and Account planned-rotation/compromise-cutover evidence remain required before activation. Detailed status and proof belong to [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - The target bounded typed Game Session → Gateway lifecycle-intent contract is not implemented or versioned yet. Current Gateway behavior infers lifecycle intent from upstream close/error behavior; the target and its implementation/proof boundary are recorded in [ADR 0131](./decisions/adr-0131-lifecycle-distinct-gameplay-close-taxonomy.md#implementation-status). Gateway remains the sole authority for translating that intent into external WebSocket close semantics. ## Gateway Pattern @@ -142,7 +142,7 @@ After applying strip/authentication rules, the gateway sets or forwards the down - `X-Proxy-Connection-Id` – preserved unchanged only after TCP Proxy authentication as the sole gateway-authenticated, server-owned opaque raw-name correlation field so downstream services can correlate lifecycle signals with the TCP Proxy's `NotifyDisconnect {proxyConnectionId, disconnectSequence}`; the raw inbound header is stripped before this authenticated value is re-added. It is not authentication or session authority. - `X-Game-Instance-Id` / `X-Tenant-Id` – downstream game/tenant context generated from authenticated TCP Proxy metadata when the corresponding `X-Proxy-Game-Instance-Id` / `X-Proxy-Tenant-Id` inputs are present. Raw proxy names are stripped and never forwarded. - `X-World-Slug` / `X-Realm-Slug` / `X-Pointer-Version` – one all-or-none routing bundle derived from verified connect-token claims on non-proxy admission or accepted from the authenticated TCP Proxy bridge. A partial, malformed, or non-positive-version bundle is rejected. These values and the game/tenant fields remain advisory admission context; Game Session validates them against current session, entitlement, catalog, and admission-pointer authority. -- `X-Firemud-Connect-Context` – for non-proxy `/ws/game/**` handshakes that pass connect-token validation, gateway emits a short-lived signed context payload containing the complete verified connect scope: `accountId`, `tenantId`, `realmId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `pointerVersion`, `catalogRevision`, `connectScopeId`, `connectRequestId`, `audience: game-session`, `recipient: game-session-service`, the bounded selected-target `authorityTuple` including its applicable caller-membership generation, exact `membershipVersion: {tenantId: version}` map containing only the selected tenant, `replayAdmissionFence`, `connectTokenJti`, `issuedAt`, `verifiedAt`, `expiresAt`, and `gatewayRequestId`. Multi-Tenancy resolves the tenant-local `{tenantId, realmSlug}` selectors to the durable `realmId`; Account carries that exact resolved realm snapshot and admission evidence in the `gameplay-connect` token. Private/playtest targets additionally carry the exact `playtestLifecycleId` and positive `playtestStateGeneration`; public-production contexts omit both and reject either field if present. The lifecycle ID and generation must equal the verified source claim and selected-target context exactly, and remain distinct from the admission-pointer `pointerVersion`. The context `expiresAt` is no later than the source `gameplay-connect` JWT `exp` and no later than `issuedAt + 30 seconds`; Gateway never extends the source token lifetime or grants a post-consumption grace period. The `audience` and `recipient` values are registered context bindings, not client input. Gateway carries these Account-produced selectors, durable realm identity, and authority evidence unchanged without reinterpretation, independent realm resolution, or rescoping; its provenance and Game Session's joint continuation validation are defined by the [canonical JWT and token contract](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) and [ADR 0137](./decisions/adr-0137-isolated-playtest-state-modes-and-reset.md). Game Session must validate the complete context schema, signature, expiry bounds, exact audience/recipient and claim/context equality, then validate the durable realm identity, lifecycle ID, positive generation, namespace, and current caller grant together for private/playtest admission before using this context; public-production admission rejects those playtest fields. Replay protection for `connectTokenJti` remains Gateway-owned and is not re-implemented as a second authority in Game Session. `connectTokenJti` is internal replay/audit evidence and is never returned in client metadata or protocol output. +- `X-Firemud-Connect-Context` – for non-proxy `/ws/game/**` handshakes that pass connect-token validation, Gateway signs a separate short-lived assertion for the registered Game Session receiver. It carries the complete Account-selected target and authority evidence unchanged from the canonical [Account-signed `gameplay-connect` schema](./system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema), including the conditional non-public lifecycle and generation fields. Its source-to-context field mapping is `requestId` → `connectRequestId`, `jti` → `connectTokenJti`, and `iat` → `issuedAt`. The Gateway assertion adds only `audience: game-session`, `recipient: game-session-service`, `verifiedAt`, `gatewayRequestId`, and bounded `expiresAt`; these receiver bindings are registered values, not client input. `issuedAt`, `verifiedAt`, and `expiresAt` are UTC epoch seconds, with `issuedAt` exactly equal to source `iat` and `expiresAt` no later than the earlier of source `exp` and `issuedAt + 30` seconds. Gateway rejects before replay consumption or context signing when `verifiedAt >= expiresAt`. Clock skew may account for clock comparison but cannot rewrite `issuedAt`, extend `expiresAt`, or create post-expiry context acceptance. The existing discovery-scope digest representation is unchanged, including its canonical RFC3339 `evaluatedAt` input. Gateway enforces exact source-claim/context equality before signing; Game Session validates the complete context schema, Gateway signature, exact audience/recipient, and deadline before using it. Public-production contexts omit and reject both playtest fields. Replay protection for `connectTokenJti` remains Gateway-owned and is not re-implemented as a second authority in Game Session. `connectTokenJti` is internal replay/audit evidence and is never returned in client metadata or protocol output. - `X-Firemud-Connection-Mode` – gateway-owned marker identifying the gameplay admission path. `first_party_web` identifies public non-proxy WebSockets admitted through the protected first-party cookie path; `trusted_tcp_proxy` identifies only the authenticated internal TCP Proxy mTLS bridge and is not a public WebSocket mode. A future `non_first_party_public` value is reserved but unavailable. The current `first_party_web` value covers browser/mobile-browser and native or other nonbrowser Account clients using a protected cookie jar; it identifies the verified connect-token path rather than a browser-only client class. It does not authorize a tokenless generic WebSocket path or imply current support for `X-Firemud-Connect-Token`. Game Session must treat this header as meaningful only when produced by the gateway after trust/canonicalization filters run, and must reject `/ws/game/**` admissions that present neither supported mode. - `X-Session-Id` is not part of the canonical header contract and must not be emitted or consumed for gameplay/session binding decisions. @@ -369,45 +369,28 @@ This section is the canonical source of truth for connect-token enforcement and - The cookie value is the connect token. Browser JavaScript must not read, copy, or persist the token outside the cookie; client code uses the non-secret response metadata from `POST /auth/connect-token` for retry and expiry UX. - Gateway must accept exactly one non-empty, single-valued currently supported connect-token carrier on non-proxy `/ws/game/**` handshakes. Duplicate header values, duplicate token cookies, or simultaneous header and cookie carriers are rejected as `CONNECT_TOKEN_REJECTED`; Gateway never chooses precedence among ambiguous credentials. The target header carrier remains unavailable until its dedicated route proof is complete. - Gateway must not accept connect tokens from query parameters in player-facing environments. Query-carried values do not satisfy the token requirement and are never promoted into a supported carrier. -- **Required claims** - - `accountId` - - `tenantId` - - `realmId` - - `playableStateNamespaceId` - - `playableStateScope` (server-derived from the selected catalog policy) - - `gameInstanceId` - - `worldSlug` - - `realmSlug` - - `playtestLifecycleId` (required for private/playtest targets; absent and rejected for public production) - - `playtestStateGeneration` (required and positive for private/playtest targets; absent and rejected for public production) - - `pointerVersion` (admission-pointer fence, distinct from `playtestStateGeneration`) - - `catalogRevision` - - `connectScopeId` - - `requestId` (the source connect-token issuance/request-operation identity; the signed Gateway → Game Session context names this field `connectRequestId`) - - bounded selected-target `authorityTuple` including its applicable caller-membership generation and separate exact selected-tenant `membershipVersion: {tenantId: version}` map, carried as distinct fields under the [canonical JWT and token contract](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) - - `iat` (absolute issuance time) - - `exp` (absolute expiration) - - `jti` (single-use nonce for replay defense) - - `replayAdmissionFence` (shared replay-readiness fence observed at issuance) +- **Account-signed source profile** + - Gateway validates the complete required and absent claim set in the canonical [`gameplay-connect/v1` profile](./system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema), including Account's server-resolved durable `realmId`, `playableStateNamespaceId`, `playableStateScope`, exact bounded `authorityTuple`, separate selected-tenant `membershipVersion`, and conditional non-public lifecycle/generation fields. It verifies the exact issuer, `aud=gameplay-connect`, signature/key, and claims before consuming replay state; the Account schema owns the field list and claim-level shape rules. + - Gateway preserves the selected target and authority evidence unchanged in its context. The discovery `connectScopeId` and its existing RFC3339 `evaluatedAt` digest input are not converted or re-serialized as part of the context timestamp contract. - **Lifetime and replay** - Token lifetime has a platform hard maximum of 30 seconds from signed `iat` to `exp`. Issuers may choose a shorter lifetime; Gateway rejects a missing or future-skewed `iat`, an `exp` that does not follow `iat`, or a declared lifetime above the hard maximum even if the signature and current expiry are otherwise valid. - - `firemud.gateway.connectTokenClockSkewMs` (environment variable `FIREMUD_GATEWAY_CONNECT_TOKEN_CLOCK_SKEW_MS`) is the one connect-token clock-skew setting. It defaults to `5000` ms and must be within `0..5000` ms. Gateway uses the same value for future-`iat` tolerance, expiry acceptance, replay-marker expiry, and replay-protection quarantine; no separate `small_skew`, JWT skew, or replay skew may be configured for this path. An invalid, unknown, or inconsistent value fails player-facing readiness. - - Gateway must reject expired tokens and tokens whose `jti` has already been observed within the replay window. + - `firemud.gateway.connectTokenClockSkewMs` (environment variable `FIREMUD_GATEWAY_CONNECT_TOKEN_CLOCK_SKEW_MS`) is the one connect-token clock-skew setting. It defaults to `5000` ms and must be within `0..5000` ms. Gateway uses it for future-`iat` comparison, replay-marker retention padding, and replay-protection quarantine; it does not extend source-token or signed-context admission past `exp`. No separate `small_skew`, JWT skew, or replay skew may be configured for this path. An invalid, unknown, or inconsistent value fails player-facing readiness. + - Gateway must reject a source token at or after its signed `exp`, and tokens whose `jti` has already been observed within the replay window. Future-`iat` tolerance never replaces or resets the signed `iat`. - After signature, issuer/audience, lifetime, required-claim, and request-scope validation succeeds, Gateway requires shared replay readiness to be `OPEN`, the signed `replayAdmissionFence` to equal the current fence, and the Gateway-owned browser deny marker for the token `jti` to be absent, then atomically repeats those checks while consuming `jti` before opening the upstream WebSocket. The token is spent even if the subsequent upgrade or backend connection fails; a retry obtains a newly issued token. - - Replay cache entries must expire automatically at `exp + firemud.gateway.connectTokenClockSkewMs`. The replay marker covers the complete token acceptance window and must not be shortened to a fixed 30 seconds from consumption. - - A hard Account or security revocation blocks new issuance for the revoked account or authority. A successful consume is terminal for that exact token `jti`. A deny-marker write becomes a confirmed terminal denial only after its configured same-connection `WAITAOF` acknowledgement succeeds; Gateway then never admits that `jti` again during its remaining acceptance window. Consuming one token does not prevent a later independently authorized issuance with a new request identity and `jti`. Gateway evaluates the token against its deployment-approved synchronized UTC epoch-millisecond wall clock: target future-`iat` tolerance permits acceptance no earlier than `iat - firemud.gateway.connectTokenClockSkewMs`, and target expiry tolerance permits acceptance no later than `exp + firemud.gateway.connectTokenClockSkewMs`. Therefore, when `exp - iat` is at the 30-second hard maximum, the complete possible acceptance interval is at most 30 seconds plus two configured skew intervals (40 seconds at the default 5-second skew); measured from the signed `iat` to the latest consume, the bound is 30 seconds plus one skew interval. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed: the marker may have been written and Gateway must deny if it observes it, but the caller retains the bounded token-window outcome until the write is durably acknowledged or the token expires and must not report terminal no-grace revocation earlier. + - Replay cache entries must expire automatically at `exp + firemud.gateway.connectTokenClockSkewMs`. This is conservative security retention padding after the strict source-token admission deadline, not additional credential or context lifetime. The replay marker covers the complete token acceptance window and must not be shortened to a fixed 30 seconds from consumption. + - A hard Account or security revocation blocks new issuance for the revoked account or authority. A successful consume is terminal for that exact token `jti`. A deny-marker write becomes a confirmed terminal denial only after its configured same-connection `WAITAOF` acknowledgement succeeds; Gateway then never admits that `jti` again during its remaining strict acceptance window. Consuming one token does not prevent a later independently authorized issuance with a new request identity and `jti`. Gateway evaluates the token against its deployment-approved synchronized UTC epoch-millisecond wall clock: target future-`iat` tolerance permits acceptance no earlier than `iat - firemud.gateway.connectTokenClockSkewMs`, while signed `exp` remains the hard admission deadline. The exact signed `iat` is preserved when Gateway constructs context `issuedAt`, and context `expiresAt` remains no later than the earlier of source `exp` and `issuedAt + 30 seconds`; clock skew does not extend either lifetime. Thus, when `exp - iat` is at the 30-second hard maximum, strict source admission spans at most 30 seconds plus one future-`iat` tolerance interval (35 seconds at the default 5-second skew); replay markers are retained through the additional configured expiry-padding interval. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed: the marker may have been written and Gateway must deny if it observes it, but the caller retains the bounded pre-expiry token-window outcome until the write is durably acknowledged or the token expires and must not report terminal no-grace revocation earlier. - Account owns two logically isolated, prefix-separated connect-token issuance-result families for idempotent `/auth/connect-token` retries: the current unversioned legacy `session:connect-token:tenant::account::scope::request:` map and the target `session:connect-token:v1:tenant::account::scope::request:` projection. **Current runtime:** the legacy value contains the raw issued token or deterministic cached failure. **Target state:** the target value carries `schemaVersion: "connect-token-issuance-result-v1"` and a bounded Account-encrypted response envelope containing the exact result, opened for an exact retry only after current authority and issuance state are reconciled; it is not JWT reconstruction or admission authority. Target readers never fall back to the legacy family. Because the legacy writer lacks an issuance fence, target enablement requires full Account-cohort quiescence, in-flight drain, and the configured legacy TTL/retry horizon. The full persistence contract is owned by [Account connect-token issuance persistence](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Gateway alone owns the target replay-consumption, browser-revocation denial, and readiness/fence state in the Coordination Redis contract; an issuance-result projection, replay marker, deny marker, and readiness record never substitute for each other. - Replay and browser-revocation marker ownership is Gateway-only; downstream services do not participate in connect-token replay or browser-deny checks. - Replay checks must be backed by the player-facing Coordination Redis deployment (not Cache/Rate-Limit Redis or per-pod memory) so `jti` replay decisions are consistent across horizontally scaled gateway pods and cannot be selectively evicted. The deployment requires Redis 7.2+ with AOF enabled, `noeviction`, replay-key ACL isolation, and admission-blocking capacity thresholds. The atomic marker script is followed by `WAITAOF requiredLocalAofCount requiredReplicaAofCount timeout`; `DURABLE_REPLAY_CONSUME_ACK` succeeds only when the reported AOF-fsync counts meet the configured thresholds, with at least one local AOF acknowledgement. The browser-deny write uses the same pinned Coordination connection and configured timeout/threshold after the write; its propagation remains in the default `redis.REPL_ALL` mode. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed and cannot be reported as terminal revocation. `WAIT`, read-back, or a successful client write is not a substitute, and this contract does not claim protection from disk or hardware destruction. - Replay and browser-revocation state use the canonical target representation defined by the Redis ownership and recovery documents, with bounded cardinality and deterministic expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. The readiness/fence record and marker state must remain one script-compatible Coordination Redis atomicity domain under that contract. The legacy representation emitted by the current writer is migration-only drift and cannot be treated as target state. - The replay and deny-marker prefixes are security-critical, non-evicting coordination state. Gateway's one consume script checks readiness state, signed fence/cutoff, and deny-marker absence before creating the replay marker; consumption is successful only after that script and the configured Redis 7.2+ `WAITAOF` acknowledgement both succeed. A deny marker that linearizes before or during the consume race returns a denial without creating the replay marker; a consume already linearized is spent and cannot be retroactively undone by a later browser logout. A browser revocation is confirmed only after its deny write and same-connection durability acknowledgement succeed; an uncertain deny write remains unconfirmed. Capacity or acknowledgement failure rejects the handshake rather than accepting an uncertain marker. A crash or connection loss between marker creation and acknowledgement is treated as uncertain consumption, not as an opportunity to unconsume or retry the token. - - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. + - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second preserves replay-marker retention through `exp + skew`. That second interval is security-state cleanup padding, not acceptance through `exp + skew`; source-token and signed-context admission still stop at their signed deadlines. Account stops issuing connect tokens and Gateway rejects admission until the full retention barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. - Replay-quarantine lifecycle is a monitored security state. Gateway must emit low-cardinality `gateway.connect_token.replay_quarantine_entries_total{reason=...}`, `gateway.connect_token.replay_quarantine_exits_total{outcome=...}`, `gateway.connect_token.replay_quarantine_active`, and `gateway.connect_token.replay_quarantine_duration_seconds`, plus structured records containing the shared `replayAdmissionFence`, `state`, `quarantineStartedAt`, `quarantineUntil`, and `openedAt` values. Alertmanager must alert when a player-facing quarantine is entered, remains active past `quarantineUntil` or has no observed exit, or exits without fresh `DURABLE_REPLAY_CONSUME_ACK` proof. Dashboards must show entry/exit counts and duration. Labels must exclude `jti`, tenant identifiers, and other high-cardinality values. - Replay-cache outage behavior: - Player-facing environments (`/ws/game/**` in `enforce` mode): fail closed with HTTP `403` and `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` when replay protection is unavailable. - Non-player-facing dev/preview environments: fail-open is allowed only when explicitly configured for local iteration and must emit drift metrics. -Gameplay-connect is an explicit bounded revocation-freshness exception, not a second Account token-registry authority. A valid token may remain usable only before its one atomic exact-`jti` consume marker is committed and only within the target acceptance interval from `iat - firemud.gateway.connectTokenClockSkewMs` through `exp + firemud.gateway.connectTokenClockSkewMs`, whose maximum width is 30 seconds plus two configured skew intervals (40 seconds at the default 5-second skew). A hard Account or security revocation blocks new issuance and downstream admission; it may leave only that bounded pre-consumption window for an already-issued token. Once the marker is consumed, the token grants no further authority, and no `player-bootstrap` lifetime or `FIREMUD_AUTH_SESSION_EXPIRATION_MS=300000` gameplay-continuity setting extends this Gateway replay window. +Gameplay-connect is an explicit bounded revocation-freshness exception, not a second Account token-registry authority. A valid token may be consumed only before its one atomic exact-`jti` marker is committed and before the signed source `exp`; future-`iat` tolerance may begin acceptance at `iat - firemud.gateway.connectTokenClockSkewMs`, but never resets `iat` or extends the hard expiry. The replay marker remains retained through `exp + firemud.gateway.connectTokenClockSkewMs` as security-state padding, without authorizing a post-expiry handshake or context. A hard Account or security revocation blocks new issuance and downstream admission; it may leave only that bounded pre-consumption, pre-expiry window for an already-issued token. Once the marker is consumed, the token grants no further authority, and no `player-bootstrap` lifetime or `FIREMUD_AUTH_SESSION_EXPIRATION_MS=300000` gameplay-continuity setting extends this Gateway replay window. - **Validation outcomes** - Invalid, expired, replayed, scope-mismatched, or replay-protection-unavailable token state is rejected with HTTP `403` and the bounded handshake error classes below. @@ -429,9 +412,9 @@ This token is an edge admission/rate-limiting hint only. It does not replace `LO - **Verified context handoff (Gateway -> Game Session)** - After successful connect-token validation, Gateway must emit a signed, short-lived connect context (`X-Firemud-Connect-Context`) for the upgraded `/ws/game/**` connection. - Gateway strips every external connect-token carrier before forwarding. The raw header or cookie token never reaches Game Session or another upstream service. - - Context payload must carry the registered schema: `accountId`, `tenantId`, `realmId`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `pointerVersion`, `catalogRevision`, `connectScopeId`, `connectRequestId`, `audience: game-session`, `recipient: game-session-service`, the bounded selected-target `authorityTuple` including its applicable caller-membership generation, exact `membershipVersion: {tenantId: version}` map containing only the selected tenant, `replayAdmissionFence`, `connectTokenJti`, `issuedAt`, `verifiedAt`, `expiresAt`, and `gatewayRequestId`; private/playtest contexts additionally carry the exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public-production contexts omit and reject both. `playtestStateGeneration` is separate from the admission-pointer `pointerVersion`. Multi-Tenancy resolves the tenant-local `{tenantId, realmSlug}` selectors to the durable `realmId`, and Account carries that exact resolved realm snapshot and admission evidence in the `gameplay-connect` token. Gateway is the producer and must set the registered audience and recipient itself; it carries the Account-issued selected-target snapshot's durable realm identity, selectors, namespace/scope claims, and authority evidence unchanged, with exact equality through the signed context, and does not own or derive an independent realm, namespace, or scope authority. Gateway accepts those realm, namespace/scope, and runtime-target fields only as the server-resolved target already bound to the exact `catalogRevision`/`pointerVersion` pair; it must not select a newer pointer, substitute carrier fields, or resolve a separate realm/namespace/scope. The lifecycle ID and generation must match the verified source claims and selected-target context exactly. The evidence provenance, lifecycle/grant predicate, and Game Session continuation check are defined by the [canonical JWT and token contract](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple) and [ADR 0137](./decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); Game Session is the consumer and must validate those exact values before admission. + - The payload and source-to-context mapping are exactly those in [Gateway Output Rules](#gateway-output-rules-downstream-trusted), over the canonical Account-signed [`gameplay-connect/v1` profile](./system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema). Gateway sets the registered receiver bindings itself, verifies exact source-claim/context equality before signing, and copies Account's resolved realm identity, selected target, and authority evidence unchanged; it does not select a newer pointer or independently resolve realm, namespace, or scope. Conditional lifecycle and generation equality is enforced as defined by the two canonical owners. - The producer/consumer contract proof must cover one representative signed context with every required field and exact `audience`/`recipient`, plus rejection of missing or wrong audience/recipient, altered claims, wrong field types, invalid signature/key, and expired context. Signature verification alone is not proof of the handoff contract. - - Game Session validates the complete signed-context schema before using any field for `LOGIN`, `PLAY`, or scope comparison. Required fields are present with their declared scalar, map, or object types; `authorityTuple` and the selected-tenant `membershipVersion` map are structurally exact; `audience=game-session`, `recipient=game-session-service`, the positive `first_party_web` mode, signature (`kid` aware), bounded `issuedAt`/`expiresAt`, and all context bindings are valid. Private/playtest contexts require a positive `playtestStateGeneration` and exact `playtestLifecycleId`/generation equality with the verified source claims and selected target, followed by current lifecycle, namespace, and caller-grant validation; public-production contexts reject either playtest field. A missing field, wrong-typed field, altered claim, or field not bound to the Gateway-verified source token/selected target is rejected before any scope fallback or `PLAY` use. Replay protection for `connectTokenJti` is performed only at Gateway handshake time. + - Game Session validates the complete signed-context schema before using any field for `LOGIN`, `PLAY`, or scope comparison. Required fields and the exact selected-target authority evidence must match the canonical source profile; `audience=game-session`, `recipient=game-session-service`, the positive `first_party_web` mode, Gateway signature (`kid` aware), and `expiresAt` with no post-expiry grace must all validate. Private/playtest contexts require the exact lifecycle and positive-generation values already verified against the source token by Gateway, plus current lifecycle, namespace, and caller-grant validation; public-production contexts reject either playtest field. A missing field, wrong-typed field, altered claim, or field not bound by Gateway to its verified source token/selected target is rejected before any scope fallback or `PLAY` use. Replay protection for `connectTokenJti` is performed only at Gateway handshake time. - Missing/invalid/expired context on non-proxy handshakes that required connect-token validation must be rejected with the existing gameplay protocol error `ERROR CONNECT_CONTEXT_INVALID reason=` before `PLAY` (no scope fallback to raw headers). The bounded reasons are `missing_field`, `wrong_field_type`, `altered_claim`, `unbound_claim`, `invalid_signature`, `unknown_kid`, `expired`, `audience_mismatch`, and `recipient_mismatch`; they are machine-readable subreasons, not a second browser or handshake taxonomy. - If the failure occurs before HTTP 101, Gateway exposes the existing handshake class and reason surface to capable non-browser HTTP callers and structured operator telemetry; source-token failures use `CONNECT_TOKEN_REJECTED` with `reason=invalid_token_content` when that is the classified cause. If the signed context is rejected after HTTP 101, Game Session uses the existing `ERROR ` protocol surface above and closes the socket. Browser clients use the conservative pre-upgrade recovery rule above and the established gameplay protocol for post-upgrade failures; they do not infer class or reason from inaccessible failed-upgrade headers. - Gateway must also emit `X-Firemud-Connection-Mode: first_party_web` for these first-party protected-cookie connect-token-validated handshakes, including native or other nonbrowser Account clients using a protected cookie jar. This current marker does not establish support for `X-Firemud-Connect-Token`; a future dedicated nonbrowser route may use the same marker only after its route and proof are complete. diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index c014230df3..5c766504f5 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -4,7 +4,7 @@ This document defines the JWT profiles, claim requirements, issued-token registr ## Implementation Status -This document defines target-state token and revocation behavior. Current implementation remains drifted: the runtime has no complete issued-token registry or Account-owned authority-generation issuance, advancement, propagation, and validation path; checked-in player-facing Kustomize delivery is legacy Secret-backed signing plus a public `jwt-jwks` Secret, while hosted preview Helm remains on its diagnostic public `jwt-jwks` ConfigMap path; validators still use shared-HMAC verification rather than Account JWKS; and the runtime still permits the documented classpath JWKS fallback when the configured file is absent. The first implemented authority-generation path must prove that issuance and refresh cannot cross a concurrent generation advance and that every affected route rejects stale generations; no such runtime proof is currently claimed. +This document defines target-state token and revocation behavior. Current implementation remains drifted: the runtime has no complete issued-token registry or Account-owned authority-generation issuance, advancement, propagation, and validation path; checked-in player-facing Kustomize delivery is legacy Secret-backed signing plus a public `jwt-jwks` Secret, while hosted preview Helm remains on its diagnostic public `jwt-jwks` ConfigMap path; validators still use shared-HMAC verification rather than Account JWKS; and the runtime still permits the documented classpath JWKS fallback when the configured file is absent. The selected-target `gameplay-connect` profile below is target state, not current wire behavior; its complete Account producer, Gateway assertion, Game Session consumer, and negative-proof path is not implemented. No `IssueConnectToken` RPC or changed credential path may be activated before that complete producer/consumer proof passes. The first implemented authority-generation path must prove that issuance and refresh cannot cross a concurrent generation advance and that every affected route rejects stale generations; no such runtime proof is currently claimed. Each registry-backed revocable `control-ui`, `player-bootstrap`, or receiver-specific private player-delegation JWT has exactly one Account-owned Coordination Redis record: `session:auth:token:`. The separate `gameplay-connect` profile is not registry-backed and uses its dedicated single-use replay contract. @@ -45,7 +45,7 @@ The pre-v1 grant cutover is direct: a JWT, issued-token registry record, authori The tuple is copied without renaming or reinterpretation into every applicable registry-backed JWT/registry claim, payload, lease, binding, refresh request, rebind proof, and installation acknowledgement. `issuanceFence` is copied alongside the tuple as the Account composite authority fence captured by the issuance transaction or CAS; it is not a substitute for any tuple member. -For Account's `GetTenantMembershipForRuntime` response and persisted or cross-service gameplay carriers, `membershipVersion` is the exact one-tenant map `{tenantId: version}`. The response, gameplay binding, Account lease, `rebindHandle`, rotation carrier, and exact retry evidence compare the complete key/value map, not a scalar or a partial/merged value. A receiver may extract a scalar for process-local calculations only after validating that map; it must not transmit or persist the scalar as `membershipVersion`. The map remains a separate predicate from `authorityTuple.membershipAuthorityGeneration`, which must also be compared exactly. +`membershipVersion` is separate from `authorityTuple` and is a required map in each profile schema: when membership is non-applicable its canonical value is `{}`, never omission, `null`, a scalar, or a sentinel. For Account's `GetTenantMembershipForRuntime` response and persisted or cross-service gameplay carriers, an applicable `membershipVersion` is the exact one-tenant map `{tenantId: version}`. Across the JWT claim, registry record, Account evidence bundle, and each applicable lease, binding, rebind, rotation, installation, and retry carrier, the complete map structure and key/value pairs must remain exactly equal. A receiver may extract a scalar for process-local calculations only after validating that map; it must not transmit or persist the scalar as `membershipVersion`. The map remains an independent predicate from `authorityTuple.membershipAuthorityGeneration`, which must also be compared exactly; neither value may be inferred from or substituted for the other. For the `gameplay-connect` token and `X-Firemud-Connect-Context`, Account derives the caller-bound `authorityTuple.membershipAuthorityGeneration` and the separate `membershipVersion` map from the same authoritative membership snapshot for the exact selected tenant. They remain independent predicates and neither may be reconstructed from the other, a cached projection, or a later read. Before continuation, including reconnect/resume, Game Session must compare both values together against one fresh Account membership snapshot; if either comparison cannot be established from that snapshot, continuation fails closed. @@ -297,18 +297,55 @@ When a `platformAdmin` caller uses a `tenant_regular` route or a `cross_tenant_d Services must enforce this claim contract before role/tenant authorization: -For `gameplay-connect`, the complete issuance contract is the Account `IssueConnectToken` route entry plus [the canonical connect-token issuance contract](./system-architecture-authentication.md#connect-token-issuance-api), with the exact field mapping below. The presented `player-bootstrap` JWT is still registry-backed and must complete its one active-registry lookup and one Account evidence-bundle read; only the newly minted `gameplay-connect` artifact uses the no-ordinary-registry replay path. Account requires an existing caller-bound `membershipLifecycleState=ACTIVE` membership and takes the selected-route membership evidence from one authoritative snapshot: `authorityTuple.tenantAuthorityGeneration` has exactly one selected-tenant key, `authorityTuple.membershipAuthorityGeneration` has exactly one selected-tenant key for that caller membership, and the separate `membershipVersion` map has exactly one entry with the same key. `authorityTuple.privateRealmGrantVersions` is `[]` for public production or exactly one selected-realm grant entry for every non-public realm, whether ordinary private or playtest; each entry includes `playtestLifecycleId`. The `connect-token-issuance-evidence/v1` boundary binds `accountId`, `connectScopeId`, `requestId`, `requestDigest`, `selectedRouteMembershipEvidence`, the complete bounded `authorityTuple`, separate `membershipVersion`, `jti`, `replayAdmissionFence`, `runtimeEntitlementAuthorityReference`, and `admissionPointerAuthorityReference`. Account exposes a successful result only after the dedicated issuance/replay record and request outcome are `COMMITTED`; exact retries return the stored success or deterministic failure without minting another token. The dedicated record is not `session:auth:token:` and does not inherit its registry-only fields: `tokenGeneration` and `issuanceFence` are absent for `gameplay-connect`, while all other profile-specific required/absent claims in this table remain authoritative. +For `gameplay-connect`, issuance follows the Account `IssueConnectToken` authorization entry in the [authorization route matrix](./system-architecture-authz-route-matrix.md); Account's local request and persistence consequences are in [Account API Contracts](./microservices/account-service/api-contracts.md) and [Connect-Token Issuance Persistence](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The profile's exact claim shape and mapping are defined here. The presented `player-bootstrap` JWT is still registry-backed and must complete its one active-registry lookup and one Account evidence-bundle read; only the newly minted `gameplay-connect` artifact uses the no-ordinary-registry replay path. Account requires an existing caller-bound `membershipLifecycleState=ACTIVE` membership and takes the selected-route membership evidence from one authoritative snapshot: `authorityTuple.tenantAuthorityGeneration` has exactly one selected-tenant key, `authorityTuple.membershipAuthorityGeneration` has exactly one selected-tenant key for that caller membership, and the separate `membershipVersion` map has exactly one entry with the same key. `authorityTuple.privateRealmGrantVersions` is `[]` for public production or exactly one selected-realm grant entry for every non-public realm, whether ordinary private or playtest; each entry includes `playtestLifecycleId`. The `connect-token-issuance-evidence/v1` boundary binds `accountId`, `connectScopeId`, `requestId`, `requestDigest`, `selectedRouteMembershipEvidence`, the complete bounded `authorityTuple`, separate `membershipVersion`, `jti`, `replayAdmissionFence`, `runtimeEntitlementAuthorityReference`, and `admissionPointerAuthorityReference`. Account exposes a successful result only after the dedicated issuance/replay record and request outcome are `COMMITTED`; exact retries return the stored success or deterministic failure without minting another token. The dedicated record is not `session:auth:token:` and does not inherit its registry-only fields: `tokenGeneration` and `issuanceFence` are absent for `gameplay-connect`, while all other profile-specific required/absent claims in this table remain authoritative. + +#### Account-Signed Selected-Target Gameplay-Connect Schema + +The following is the canonical `gameplay-connect/v1` Account-signed JWT claim set. `authorityTuple` is the complete bounded schema defined in [Canonical Authority Tuple](#canonical-authority-tuple), not a partial projection. + +```text +{ + iss, + aud: "gameplay-connect", + iat, + exp, + jti, + accountId, + tenantId, + realmId, + worldSlug, + realmSlug, + playableStateNamespaceId, + playableStateScope, + gameInstanceId, + pointerVersion, + catalogRevision, + connectScopeId, + requestId, + authorityTuple, + membershipVersion: { selectedTenantId: version }, + replayAdmissionFence, + playtestLifecycleId?, + playtestStateGeneration? +} +``` + +Account resolves and binds `tenantId`, durable `realmId`, `worldSlug`, `realmSlug`, stable `playableStateNamespaceId`, server-derived `playableStateScope`, `gameInstanceId`, `pointerVersion`, and `catalogRevision` from the exact server-issued `connectScopeId` and current authoritative catalog, policy, and admission-pointer state. The `playableStateScope` projection uses the canonical [realm catalog and admission-pointer contract](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); this JWT profile adds no alternate representation. None is accepted as caller-selected routing authority. For public production, `authorityTuple.privateRealmGrantVersions` is `[]` and both playtest claims are absent. For every non-public target, both `playtestLifecycleId` and positive `playtestStateGeneration` are required and match the selected target and its exact lifecycle-bound grant evidence. The selected tenant is the sole key in `authorityTuple.tenantAuthorityGeneration`, `authorityTuple.membershipAuthorityGeneration`, and the separate `membershipVersion` map; the membership generation and version come from the same fresh caller-bound Account snapshot. Applicable cutoff objects remain exact and independently required under the canonical tuple rules. + +The Account JWT keeps registered claim names `requestId`, `jti`, and `iat`. Gateway maps those source values, respectively, to `connectRequestId`, `connectTokenJti`, and `issuedAt` in its separate signed context; it does not create new Account claims or reinterpret their values. The source JWT `iat` and `exp`, and Gateway context `issuedAt`, `verifiedAt`, and `expiresAt`, are UTC epoch-second timestamps. The signed context uses registered `audience` and `recipient` bindings for its Gateway-to-Game Session receiver; these and `verifiedAt`, `gatewayRequestId`, and `expiresAt` are Gateway assertion fields, not Account JWT claims. Context `expiresAt` is no later than the earlier of source `exp` and `issuedAt + 30` seconds; clock skew cannot change `issuedAt` or extend that deadline. The existing discovery scope digest representation is unchanged: its `evaluatedAt` remains the canonical RFC3339 value covered by the existing `connectScopeSnapshotDigest/v1` preimage. + +This is a closed Account claim set: all listed claims are required except the two conditional playtest claims, and unlisted or extra claims are rejected. The compact JWT carries its stable Account `kid` in the JOSE header, not as a claim. The profile does not contain `schemaVersion`, registry `issuer`/profile/type aliases, `sub`, `nbf`, `signerGeneration`, `tokenGeneration`, `issuanceFence`, registry state or Account bundle/source/freshness evidence, rotation/lease/installation fields, or Gateway-only context fields. The complete Gateway assertion additions and receiving-service checks are defined in [Gateway Architecture](./system-architecture-gateway.md#gateway-output-rules-downstream-trusted); the Authentication document records only the local bootstrap and admission handoff. | Claim | `control-ui` JWT | `player-bootstrap` JWT | `gameplay-connect` JWT | `game-session-account-delegation` JWT | Notes | | --- | --- | --- | --- | --- | --- | | `iss` | Required | Required | Required | Required | Must match Account Service issuer value | -| `sub` | Required | Required | Not required | Required | Must identify the account subject where required | -| `jti` | Required | Required | Required | Required | Unique per issued token; the gameplay-connect value is the single-use replay nonce | +| `sub` | Required | Required | Absent | Required | Must identify the account subject where required | +| `jti` | Required | Required | Required | Required | Unique per issued token; the gameplay-connect value is the single-use replay nonce and Gateway preserves it as `connectTokenJti` | | `accountId` | Required | Required | Required | Required | Must be consistent with `sub` mapping where `sub` is required | | `aud` | Required (`control-ui`) | Required (`player-bootstrap`) | Required (`gameplay-connect`) | Required (`account-service`) | Exact allowed values are centrally configured | -| `iat` | Required | Required | Required | Required | UTC epoch seconds | -| `nbf` | Required | Required | Not required | Required | Token not usable before this time when present | -| `exp` | Required | Required | Required | Required | Token unusable after this time | +| `iat` | Required | Required | Required | Required | UTC epoch seconds; Gateway preserves the gameplay-connect value as context `issuedAt` | +| `nbf` | Required | Required | Absent | Required | Token not usable before this time when present | +| `exp` | Required | Required | Required | Required | Token unusable after this time; `gameplay-connect` lifetime is at most 30 seconds from `iat` | | `tokenGeneration` | Required | Required | Absent (ordinary registry-only lineage field) | Required | Positive integer for issued-token-registry lineage; gameplay-connect instead uses its dedicated single-use replay contract | | `authorityTuple` | Required | Required | Required | Required | Complete applicable tuple. For `gameplay-connect`, the exact bounded selected-target tuple is immutable issuance evidence passed unchanged through Gateway context into the later admission lease/binding checks; it is not registry-backed or standalone gameplay authority | | `authorityTuple.issuerAuthGeneration` | Required | Required | Required | Required | Positive monotonic Account-owned issuer generation captured at issuance | @@ -321,15 +358,18 @@ For `gameplay-connect`, the complete issuance contract is the Account `IssueConn | `authorityTuple.tenantBillingCutoff` | Present when applicable | Present when applicable | Present for the selected tenant when applicable | Present when applicable | Optional exact tenant billing cutoff captured at issuance; it remains independently rechecked by the admission contract where required | | `issuanceFence` | Required | Required | Absent (ordinary registry-only issuance field) | Required | Positive Account composite fence captured with the tuple | | `tenantId` | Not required | Not required | Required | Not required | Gameplay-connect admission scope | +| `realmId` | Not required | Not required | Required | Not required | Account-resolved durable realm identity from the selected target | | `gameInstanceId` | Not required | Not required | Required | Not required | Server-resolved gameplay-connect runtime target | | `worldSlug` | Not required | Not required | Required | Not required | Stable gameplay-connect world selector | | `realmSlug` | Not required | Not required | Required | Not required | Stable gameplay-connect realm selector | +| `playableStateNamespaceId` | Not required | Not required | Required | Not required | Stable playable-state identity resolved by Account for the selected realm | +| `playableStateScope` | Not required | Not required | Required | Not required | Server-derived selected-realm policy scope; not caller input | | `playtestLifecycleId` | Not required | Not required | Required for a non-public target; absent for public production | Not required | Must equal the selected-realm `authorityTuple.privateRealmGrantVersions` lifecycle and the admission-pointer snapshot exactly | | `playtestStateGeneration` | Not required | Not required | Required and positive for a non-public target; absent for public production | Not required | Exact lifecycle-reset generation from the admission-pointer snapshot; distinct from `pointerVersion` | | `pointerVersion` | Not required | Not required | Required | Not required | Gameplay-connect routing-freshness fence | | `catalogRevision` | Not required | Not required | Required | Not required | Exact gameplay-connect discovery-catalog revision bound to the selected target | | `connectScopeId` | Not required | Not required | Required | Not required | Opaque discovery scope used for issuance | -| `requestId` | Not required | Not required | Required | Not required | Connect-token issuance idempotency identity | +| `requestId` | Not required | Not required | Required | Not required | Connect-token issuance idempotency identity; Gateway preserves it as context `connectRequestId` | | `replayAdmissionFence` | Not required | Not required | Required | Not required | Exact shared replay-readiness fence observed at issuance; Gateway validates equality before authorization and repeats the check atomically during token consumption | | `globalRoles` | Optional list | Optional list | Absent | Optional list | Omission and explicit `[]` both mean no global roles; when present, the exact role list is required. `gameplay-connect` admission never authorizes from role claims | | `scopedRoles` | Required; `{}` when none | Empty map | Absent | Optional; generation maps align to delegated binding scope rather than this claim | Omission is rejected for `control-ui`; generation-map keys must be subsets of its tenant UUID keys and must exactly match the independent token-allowed target-tenant and caller-membership route predicates; no generation map may introduce an unclaimed tenant | diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 7274d1a03a..2c2285fc41 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work was rebuilt into #2826 Schema, the dependen | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Provisional; earlier two-cycle report boundary completed, required implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861) | #2857 corrects bounded Game Session admission/reconnect behavior; #2861 prepares ADR 0144's non-mutating email-link GET landing and explicit POST, not a deployed mail journey. Cycle 1 found misleading current `PLAY`/`CHARS` and post-logout claims plus routed issuer, Entity roster, and signed-context gaps. Cycle 2 found stale successful-admission claims in Reconnection, TCP, Account runtime and Realm Routing; these now distinguish Account REST token issuance from fail-closed Game Session gRPC reads. The repeated issuer, signed-context and durable-reconnect observations remain named activation successors. Account runtime reads still deny new text `PLAY` before data access. Exact-current-head CI, PostgreSQL/cross-service proof, Account and Entity target authority, signed-context handoff, HTTPS/mail/abuse controls, and live browser proof remain open. The prior code-head CI run `36006632988` cleared 27 WebSocket and 39 Game Session cross-service cases but was red overall; local Docker skips are not runtime proof. | +| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2881](https://github.com/benhook1013/FireMUD/pull/2881) | Earlier discovery and train pre-review did not complete the section. The tail contains JOIN recovery, retained tenant mapping, durable pair authority, authenticated snapshot preparation, purpose-separated envelopes and one-use exchange storage. Exact #2881 `b2a2f31b0` [CI 36703863842](https://github.com/benhook1013/FireMUD/actions/runs/36703863842) executed 29 JOIN, 9 connect-issuance and 9 bare-LOGIN storage PostgreSQL cases without skips or failures; Account and Game Session jobs passed, while aggregate CI remains red on recorded inherited failures. These are storage/snapshot proofs, not end-to-end credential issuance or live admission. Required Account connect/delegation producers, full authority/consumer proof, fresh Game Design tenant handoff, signed-context convergence, protected ring delivery, durable reconnect, HTTPS/mail/abuse and live browser proof remain open in the [Player Access tracker](../implementation-tracking/player-access-and-session.md). Membership RPC and credential activation stay denied; the ring mount stays unpublished. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index ebbdeb133a..c7f1cba898 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -225,6 +225,7 @@ These are repository-recorded proofs, not a claim that the tracker consolidation - The accepted [ADR 0058](../../architecture/decisions/adr-0058-class-specific-redis-loss-outcomes.md) Redis-loss contract requires durable intent and class-specific rebuild/terminalization; current preflight and recovery evidence do not establish every class or measured `redis_unreplicated_write_window_slo_ms` value. - [ADR 0057](../../architecture/decisions/adr-0057-game-session-owned-reconciliation-with-isolated-workers.md) assigns isolated Game Session reconciliation workers; [ADR 0068](../../architecture/decisions/adr-0068-evidence-derived-bounded-tick-ledger-recovery.md) defines recovery SLOs; and [ADR 0076](../../architecture/decisions/adr-0076-failure-class-specific-durable-tick-retries.md) defines retry exhaustion and quarantine/disposition paths. Those controls and focused fault-injection proof remain runtime gaps rather than operational claims here. - [ADR 0073](../../architecture/decisions/adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) keeps bootstrap timing formulas separate from measured production safety settings; current operator/configuration surfaces do not yet prove evidence-calibrated values or the complete lease/cleanup health split. +- Account response-envelope ring delivery remains blocked at the authenticated handoff boundary. The local [source bootstrap](../../../dev-tools/deploy/bootstrap-account-response-envelope-ring.py) and [Secret materializer](../../../dev-tools/deploy/materialize-account-response-envelope-ring.py), with focused [materializer tests](../../../dev-tools/tests/test_account_response_envelope_materializer.py), cover protected-source generation/predecessor checks, authenticated Kubernetes username lookup, CAS create/replace, post-write Secret UID/resourceVersion readback, and the distinct typed `account-response-envelope-ring-materialization-v1` receipt. They do not implement or prove an authenticated owner publisher, durable content-addressed source/receipt store, or receipt publish/readback consumer; the local verifier explicitly checks structure and caller-supplied bindings, not transport or publisher authentication, and a Git projection is not that handoff. The current `operation` field also distinguishes `create`/`rotate` from invocation-local `retry`, changing the immutable receipt for the same transition, source generation, and Secret; the eventual channel must use stable transition semantics and exact stored-receipt readback so first-write, lost-ack, and concurrent same-transition retries converge on one tuple/digest without rematerializing or creating a Secret. Any actual Secret UID/resourceVersion change remains an exact mismatch, not a retry. Keep the ring mount unpublished and Account envelope purposes disabled until source custody, sole-writer enforcement, authenticated receipt publication/readback, deployment readback, and separate live freshness/readiness gates are proved. This receipt remains distinct from `jwt-signing-keys-jwks`; do not couple ring activation to JWT/JWKS evidence. ## To Discuss 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 f9abcc5dfc..236294f062 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,6 +32,10 @@ The in-progress #2873 tenant bridge now has a signed Game Design migration-manif The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. +The canonical Account-signed selected-target `gameplay-connect` profile and Gateway assertion require Account-resolved `realmId`, `playableStateNamespaceId`, `playableStateScope`, the exact selected-target authority evidence, and the conditional non-public lifecycle/generation pair. The latest local source checkpoint adds an Account fail-closed guard against cached or fresh connect success without complete evidence, a Gateway guard that rejects first-party context creation before replay-marker mutation when independent Ed25519 signing keys are unavailable, and a shared full-context codec with vectors; Game Session runtime parsing remains denied until key publication, canonical UUID mapping, and a real Account exchange/source-evidence proof are available. These guards and codec are not a live complete producer/consumer or admission path, and this local code checkpoint has not been validated here. Durable issuance, key publication/rotation, Gateway assertion mapping, Game Session consumption, and negative-proof coverage remain open. No `IssueConnectToken` RPC or changed credential-granting path is active under this target contract until the complete producer/consumer proof passes. + +Separately, hosted CI run `36703863842` on committed `b2a2f31b02e7ad48b0d42a9da7cf7b3acec2782e` executed 29 JOIN, 9 V35, and 9 V37 PostgreSQL cases; the Account and Game Session jobs passed, while the aggregate workflow remained red from inherited failures. These are storage/integration results on the committed head, not validation of the subsequent uncommitted connect-context guards/codec or proof of the complete credential producer/consumer path. + The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases passed in CI run `36289042648` on prior #2881 head `25626210c` and skipped locally without Docker; caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests failed on an earlier head because their helper still expected bare-LOGIN success. The corrected helper now asserts `AUTH_UNAVAILABLE` and no promotion for that attempt, then uses credential-bearing LOGIN for supported gameplay coverage; the dedicated negative fixture expects following `PLAY` to require login. Both affected Docker-backed classes skipped locally, so this is a corrected assertion, not executed WebSocket end-to-end proof or a working Account exchange. Positive first-party bare-LOGIN proof remains an explicit activation gate. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. @@ -184,7 +188,7 @@ For generic Telnet and WebSocket, reconnect uses current identity and current Ac Current durable reconnect rows remain game-instance-keyed, so namespace-key migration is partial. Redis may cache them but is not authoritative gameplay state. The connection-local TCP Proxy input buffer is distinct from durable context and supports only a still-established edge rebind; it is never durable replay of input, transport bytes, frames, or unsent transient output. Current implementation/proof of the bounded reconnect context and prompt behavior remains partial; the canonical continuity contract is [Reconnection](../../architecture/system-architecture-reconnection.md). -First-party `/ws/game/**` has a separate but partial authority path. Account exposes player bootstrap and connect-token issuance; Gateway validates and forwards signed connect context; Game Session consumes verified identity at bare first-party `LOGIN` and keeps `PLAY` as the binding step. A fresh first-party `PLAY` suppresses retained post-`LOGOUT` replay and requests fresh redraw in focused local proof, but the durable terminal episode/generation fence, delayed-race proof, resume-window enforcement, and hosted signed-context handoff remain incomplete. The authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +First-party `/ws/game/**` is currently fail-closed and is not a live selected-target authority path. The local Account checkpoint refuses cached or fresh connect success without complete selected-target evidence; Gateway refuses first-party context creation before replay-marker mutation unless its independent Ed25519 signing key is available; and Game Session runtime parsing remains denied until key publication, canonical Account-to-tenant UUID mapping, and a real Account exchange/source-evidence proof exist. These gates do not establish current Account issuance, Gateway forwarding, or verified bare first-party `LOGIN`. The local fresh-`PLAY` replay-trigger correction is not evidence that first-party `PLAY` is reachable or that its output contract passed. Durable terminal-episode/generation fencing, delayed-race proof, resume-window enforcement, and the hosted signed-context handoff remain incomplete. The authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Gateway owns the downstream `/ws/game/**` socket and a stable edge transport session id. Its custom bridge can rebind an upstream Game Session socket after bounded loss without immediately dropping the player socket, reusing that edge id. Focused proofs cover abrupt upstream loss, a Game Session-like process bounce with isolated Reactor resources, and post-restart Game Logic commands (`LOOK`, movement-derived room context, and communication inputs) against shared state. Edge-visible retry taxonomy is reserved for actual edge-route loss or exhausted rebind windows; this does not guarantee in-flight command or byte replay. @@ -210,9 +214,9 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ## Validation and Proof -The evidence records focused unit, controller, gRPC, WebSocket, cross-service, and restart/rebind proofs for text parsing and Telnet parity; real Account-backed login and authenticated `PLAY`; takeover, resume, logout, and replay cleanup; public-production membership idempotency; first-party handshake/reconnect; session-start IP ordering; malformed claim and positive-ID rejection; replay identity/payload mismatch; current REST/gRPC error envelopes; and Gateway upstream/process restart continuity. It does not yet prove the owner gRPC typed-result/non-OK classification across every adopter. The Telnet cross-service harness uses a lightweight Gateway stub only as a test fixture and has a successful `TelnetGatewayGameSessionCrossServiceIntegrationTest`; the maintained runtime path is not the stub. +The evidence records focused unit, controller, gRPC, WebSocket, cross-service, and restart/rebind proofs for text parsing and Telnet parity; credential-bearing Account-backed login and generic authenticated `PLAY`; takeover, resume, logout, and replay cleanup; public-production membership idempotency; session-start IP ordering; malformed claim and positive-ID rejection; replay identity/payload mismatch; current REST/gRPC error envelopes; and Gateway upstream/process restart continuity. It does not yet prove the owner gRPC typed-result/non-OK classification across every adopter or a positive first-party signed-context path against the current fail-closed guard. The Telnet cross-service harness uses a lightweight Gateway stub only as a test fixture and has a successful `TelnetGatewayGameSessionCrossServiceIntegrationTest`; the maintained runtime path is not the stub. -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. +The focused admission proofs cover fresh generic-path 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. Current first-party proof is limited to fail-closed behavior; the corrected bare-`LOGIN` denial assertion was not executed in its Docker-backed integration classes locally. Earlier positive fixtures using obsolete HMAC/incomplete context are historical and noncanonical, and do not count as first-party proof after the current guard. Required positive integration proof remains open for structured `WORLD_BROWSE`, `WHO`, and fresh-`PLAY` outputs, authored aliases, first-party policy redaction, and first-party source/scope/cutover/reconnect binding. Generic or internal tests do not substitute for those first-party cases. Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, REST denial of non-public admission from legacy grant rows, cross-tenant membership enforcement, and the contained export/deletion/recovery boundaries. `DeleteAccount` now denies before account or financial-row mutation rather than relying on a partial active-subscription guard. Explicit `JOIN`/`Join & Play` and its bounded readback worker are local, while PostgreSQL lost-acknowledgement/concurrency, the connect-token membership-authority-generation reread, lifecycle-qualified grant authority, and canonical tenant-role, lifecycle-state, and authority-generation follow-through remain partial or unproved. @@ -224,9 +228,10 @@ Account authority proof covers account-first tenantless bootstrap authentication - 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; 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 fresh-`PLAY` replay trigger no longer reads retained context solely because a connect token exists, but durable logout-episode/generation fencing and race/retry proof remain. Retained transcript storage is not reconnect eligibility and is not deleted merely to simulate a terminal fence. +- Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam currently accept parameterized credentials. Public first-party `/ws/game/**` admission is not currently usable: Gateway blocks context creation before replay mutation without an independent Ed25519 signing key, and Game Session denies context parsing until key publication, canonical UUID mapping, and real Account exchange/source proof are complete. Do not treat the target bare-`LOGIN` flow or earlier HMAC/incomplete-context positive fixtures as current behavior. +- Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect after its admission prerequisites are met, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. +- The local first-party fresh-`PLAY` replay trigger no longer reads retained context solely because a connect token exists, but it has no current successful first-party admission proof. Durable logout-episode/generation fencing and race/retry proof remain; retained transcript storage is not reconnect eligibility and is not deleted merely to simulate a terminal fence. +- Required Game Session first-party integration proof remains open for structured `WORLD_BROWSE`, `WHO`, and fresh-`PLAY` outputs, authored aliases, first-party policy redaction, and source/scope/cutover/reconnect binding against the canonical selected-target context. Generic/internal test coverage is not a replacement for these first-party cases. - 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 and shared gameplay-role predicates now ignore global roles and derive elevation only from explicit tenant-scoped grants, with focused claim/classifier/WHO unit proof. Account's actual tenant-role issuance and full admission handoff remain incomplete; no staff impersonation or hidden-observer mode is part of the target. 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 808378aaf8..f6008293b0 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, durable post-logout episode fencing, and broader client consumption are not yet proven. Focused local proof shows fresh first-party `PLAY` after deliberate `LOGOUT` does not replay retained context; concurrent and delayed replay still require durable episode-fence proof. +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 episode fencing, and broader client consumption are not yet proven. The prior positive first-party fresh-`PLAY`/logout suppression fixture depended on the now-removed HMAC context and is historical/noncanonical; under the current fail-closed context guard it does not prove reachable first-party replay behavior. Concurrent and delayed replay still require durable episode-fence proof. Current first-party positive-output and source/scope/cutover/reconnect proof is open; see the [Player Access and Session tracker](./player-access-and-session.md). 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,12 +22,12 @@ 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 now requires both effective prompt settings, with focused four-combination local proof; real structured-client consumption and complete reconnect proof remain open. 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; focused fresh first-party post-logout replay suppression is proved locally, but durable episode and race/retry proof remains absent. | [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 and fresh first-party `PLAY` after deliberate logout omit retained output; durable episode fencing and concurrent/delayed replay proof remain absent. 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; current first-party positive replay behavior is not proved because its prior HMAC-context fixture is removed and the canonical context path remains fail-closed. Durable episode and race/retry proof also remains absent. | [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 `PLAY` after deliberate logout omits retained output; the first-party positive output path remains unproved under the current guard. Durable episode fencing and concurrent/delayed replay proof remain absent. 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 role tests prove global `platformAdmin`, `support`, `billingAdmin`, legacy `god`, and `moderator` claims remain ordinary players, while only matching tenant-scoped gameplay grants elevate. Game Session removes legacy `HIDDEN_STAFF` from player command/output vocabulary and redacts legacy or unknown friend-presence entries; Account and Social profile-policy inputs still accept `HIDDEN_STAFF`, and player-facing payloads still expose disconnect disposition contrary to ADR 0046. This does not establish Account end-to-end admission. | [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) | Account end-to-end admission remains unproven. Remove `HIDDEN_STAFF` from Account and Social profile-policy inputs, 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. | | EA-2.4 Player blocking, reporting, and safety controls | `partial` - bounded internal report persistence and the live synchronous moderation-policy evaluation seam used at enforcement boundaries exist, but owner-local fixed-category restriction state, moderation cases, appeals, and caller-bound player submission remain incomplete; unsafe public administrative report persistence is disabled. | `drift-found` - focused tests prove the bounded internal gRPC persistence and live policy-evaluation seam, plus fail-closed absence of the former public route, not the canonical player-authenticated reporting boundary or target owner-local controls. | [Moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [Authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [ReportGrpcService.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java); [ReportServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImpl.java); [ModerationServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java); [report proto](../../../protos/logging-admin/v1/report_service.proto); [Logging & Admin V1__baseline.sql](../../../services/logging-admin-service/src/main/resources/db/migration/V1__baseline.sql) | [LoggingAdminApplicationIntegrationTest.java](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java); [ReportGrpcServiceTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java); [ModerationServiceImplTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java) | [PO-1.2](./platform-operations-and-delivery.md); [EA-2.1](./player-experience-commands-and-communication.md); [AA-1.3](./player-access-and-session.md) | The live `BLOCK` command is a combat action-state effect, not social blocking. Player block/mute/ignore and safety UI remain absent; reporting needs canonical administrative authorization/live reference checks before public operator ingress and a distinct player route deriving reporter and tenant identity from authenticated caller context. | -| EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, and an opt-in unprivileged static-host/preview-route slice is prepared but disabled; this is not an independently released player application. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. Opt-in Helm chart lint/render passed; no static image has been published, deployed, or browser-proved. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json); [static host Dockerfile](../../../web-client/Dockerfile); [preview frontend template](../../../k8s/helm/firemud/templates/frontend.yaml) | `npm run lint` and `npm run build` passed and emitted `dist/frontend-assets/`; opt-in Helm lint/render passed, but no image build, running-host checks, or deployed browser journey executed. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, enabled static-host deployment and public routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | +| EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, and an opt-in unprivileged static-host/preview-route slice is prepared but disabled; this is not an independently released player application. Native mobile is deferred pending a later product and compatibility decision. | `audited` - local/static `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. Opt-in Helm chart lint/render passed; no static image has been published, deployed, or browser-proved. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json); [static host Dockerfile](../../../web-client/Dockerfile); [preview frontend template](../../../k8s/helm/firemud/templates/frontend.yaml) | No focused executable proof: [`web-client/package.json`](../../../web-client/package.json) is audit context for the general `npm run lint` and `npm run build` scripts; existing local/static runs passed and emitted `dist/frontend-assets/`, and opt-in Helm lint/render passed. No image build, running-host checks, deployed browser journey, or end-to-end first-party gameplay proof is recorded. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, enabled static-host deployment and public routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | | EA-3.4 Shared navigation, accessibility, client state, and interaction foundations | `partial` - shared QueryClient, local feature state, and basic socket lifecycle are present. | `audited` - production scaffolding was inspected; no focused navigation, accessibility, or client-state executable proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [main.tsx](../../../web-client/src/main.tsx); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [websocket.ts](../../../web-client/src/websocket.ts); [App.tsx](../../../web-client/src/App.tsx) | No focused executable proof: the [web-client package](../../../web-client/package.json) exposes general lint, build, formatting, preview, and accessibility scripts, but no focused navigation, accessibility, or client-state test exists. | [EA-1.2](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Shared navigation, accessibility coverage, semantic structured gameplay client integration, reconnect/error state, and durable interaction foundations remain absent. | ## Canonical Design Sources @@ -53,16 +53,18 @@ Current text behavior exposes `WORLDS` as an optional pre-login public browse, t 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). +These current Account policy mappings do not establish successful selected-target issuance: Account currently fails closed on connect-token success when complete selected-target evidence is unavailable. Public-production discovery and explicit JOIN status are separate; see the [Player Access and Session tracker](./player-access-and-session.md) for current Account/Gateway/Game Session gates. + ### HELP, Settings, and Presentation - Current behavior: built-in `HELP` is filtered by effective optional command capability. A bounded game-authored topic path supports tenant/template-scoped published topics, normalized exact lookup, and platform fallback. `FEATURE_UNAVAILABLE` is returned for disabled direct optional commands. Communication, prompt, presentation, and reconnect settings have typed metadata and effective-settings readback across their owning services. - Current proof and gap: parser, registry, capability, HELP/history, rendering, prompt, WebSocket/Telnet parity, and settings tests cover these seams. Rich authoring UI, localization-aware help, fuzzy/semantic search, related-topic and stage-aware discovery, richer prompt composition, and broader smart-client presentation remain incomplete. -- Current behavior: `PlayerOutput` remains structured until rendering; Telnet and generic WebSocket receive renderer-owned text, while first-party WebSocket responses and recipient pushes use structured envelopes. `LOOK`, movement refresh, communication, prompt, and reconnect paths use typed output metadata. The current `web-client` only generically JSON-parses the WebSocket envelope as `unknown`, so semantic structured `PlayerOutput` consumption and compatibility proof remain absent. Fresh room reads are authoritative and prompts are excluded from replay; schema/projection contract status is linked in [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md). +- Current behavior: `PlayerOutput` remains structured until rendering; Telnet and generic WebSocket receive renderer-owned text, while the first-party WebSocket projector has a structured-envelope path. The current context guard prevents treating that path as a reachable first-party delivery proof. `LOOK`, movement refresh, communication, prompt, and reconnect paths use typed output metadata. The current `web-client` only generically JSON-parses the WebSocket envelope as `unknown`, so semantic structured `PlayerOutput` consumption and compatibility proof remain absent. Fresh room reads are authoritative and prompts are excluded from replay; schema/projection contract status is linked in [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md). ### 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; fresh first-party `PLAY` no longer replays retained rows solely because a connect token exists, but no durable terminal episode fence is enforced. 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. Focused fresh first-party post-logout replay suppression is covered locally; durable terminal episode fencing, concurrent/delayed replay proof, 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. `LOGOUT` clears live presence and reconnect eligibility in storage; the local fresh-first-party-`PLAY` replay trigger no longer selects retained rows solely because a connect token exists, but the current context guard prevents treating this as reachable first-party behavior. No durable terminal episode fence is enforced. 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 generic storage boundary. The former positive first-party post-logout fixture was removed with its HMAC context setup and is historical/noncanonical; current first-party replay/output behavior is not proved. Durable terminal episode fencing, concurrent/delayed replay proof, full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. Required first-party positive Game Session cases and their bindings are tracked in the [Player Access and Session tracker](./player-access-and-session.md). - 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 @@ -77,7 +79,7 @@ The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scop ### Validation and Proof -- **Confirmed:** Current link, Markdown, architecture-contract, allocation, ADR, implementation-tracking, authorization-matrix, and `git diff --check` gates passed as recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). `spotlessApply`, `./gradlew check lintMarkdown -x integrationTest -x crossServiceTest`, and web-client `npm run lint` and `npm run build` also passed; the frontend build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. `./gradlew :game-session-service:test` also passed, providing focused service proof for the implemented Game Session boundary. +- **Confirmed:** Current link, Markdown, architecture-contract, allocation, ADR, implementation-tracking, authorization-matrix, and `git diff --check` gates passed as recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). `spotlessApply`, `./gradlew check lintMarkdown -x integrationTest -x crossServiceTest`, and web-client `npm run lint` and `npm run build` also passed; the frontend build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. These npm checks are local/static evidence only and do not establish an admitted first-party gameplay path or browser journey. `./gradlew :game-session-service:test` also passed, providing focused service proof for the implemented Game Session boundary. - **Partial:** Capability rows marked `drift-found` or naming remaining proof gaps retain only the bounded evidence stated in those rows; neither that evidence nor the focused service test proves the unresolved cross-service or runtime boundary. - **Unrun:** Broader cross-service runtime, manual client gameplay, independently released static host/public-site routing, and hosted browser proof remain unrun. The unexcluded full `check` stopped at `common-saga:integrationTest` initialization only because this WSL environment has no Docker command/Testcontainers environment; this is an environment limitation, not a code failure, and it supplies no Docker runtime proof. @@ -91,7 +93,7 @@ The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scop - Presentation still lacks combat-state-driven brief-on-move behavior, richer configurable prompt composition, broader prompt scheduling, and broader smart-client presentation policy. - Presence and social surfaces have a bounded canonical runtime/read model, but broader activity-engine consumers, richer recent-presence policy, broader social consumers, and operator visibility and staff-capability enforcement remain incomplete. - The independently released first-party static artifact, unprivileged static asset-hosting boundary, independent rollback, and richer browser product surface remain incomplete under [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md). -- Manual QA still needs to confirm that normal Telnet and generic WebSocket clients follow the same optional-browse, `LOGIN`, `PLAY`, in-game progression and that the first-party browser reaches the same gameplay binding semantics. +- Manual QA still needs to confirm that normal Telnet and generic WebSocket clients follow the same optional-browse, `LOGIN`, `PLAY`, and in-game progression. First-party browser parity remains blocked by the current context guard; test its gameplay binding only after the source/scope/cutover prerequisites are met, as recorded in the [Player Access and Session tracker](./player-access-and-session.md). ## To Discuss 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 506061cd19..29c1e44a2a 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 @@ -1238,20 +1238,9 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR if (cachedReplay.isPresent()) { var replay = cachedReplay.orElseThrow(); if (replay.success()) { - RuntimeRealmTarget currentRealm = requireCurrentConnectScopeTarget(scopeContext); - if (!isPublicProductionRealm(currentRealm)) { - throw new AuthenticationException( - "REALM_ACCESS_DENIED", - "The selected non-public realm does not have an active access grant"); - } - logger.info( - "Replayed connect-token attempt for account {} tenant {} world {} realm {} requestId {}", - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.worldSlug(), - scopeContext.realmSlug(), - request.requestId()); - return replayedConnectTokenResult(replay.result()); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", + "The stored connect token lacks the complete Account-signed selected-target authority contract"); } logger.info( "Replayed failed connect-token attempt for account {} tenant {} world {} realm {} requestId {} code {}", @@ -1347,79 +1336,9 @@ private ConnectTokenResult issueConnectTokenFresh( "The selected non-public realm does not have an active access grant"); } - String jti = - stableId( - "gameplay-connect", - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.gameInstanceId(), - scopeContext.realmSlug(), - request.requestId()); - long issuedAt = System.currentTimeMillis(); - long expiresAt = issuedAt + tokenProperties.getConnectTokenExpirationMs(); - String connectToken = - mintToken( - String.valueOf(bootstrapContext.accountId()), - tokenProperties.getConnectTokenExpirationMs(), - Map.of( - "aud", - "gameplay-connect", - "accountId", - bootstrapContext.accountId(), - "tenantId", - scopeContext.tenantId(), - "gameInstanceId", - scopeContext.gameInstanceId(), - "pointerVersion", - scopeContext.pointerVersion(), - "realmSlug", - scopeContext.realmSlug(), - "worldSlug", - scopeContext.worldSlug(), - "connectScopeId", - request.connectScopeId(), - "requestId", - request.requestId(), - "jti", - jti)); - sessionService.storeSession( - scopeContext.tenantId(), - bootstrapContext.accountId(), - connectToken, - tokenProperties.getConnectTokenExpirationMs()); - ConnectTokenResult result = - new ConnectTokenResult( - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.gameInstanceId(), - scopeContext.realmSlug(), - request.connectScopeId(), - connectToken, - jti, - request.requestId(), - Instant.ofEpochMilli(issuedAt).toString(), - Instant.ofEpochMilli(expiresAt).toString(), - false); - sessionService.storeConnectTokenReplay( - scopeContext.tenantId(), - bootstrapContext.accountId(), - request.connectScopeId(), - request.requestId(), - new net.firedevops.firemud.accountservice.service.session.SessionService.ConnectTokenReplay( - true, result, "", ""), - Math.min( - tokenProperties.getConnectTokenExpirationMs(), - remainingConnectScopeReplayTtl(scopeContext))); - logger.info( - "Issued connect token for account {} tenant {} world {} realm {} gameInstance {} requestId {} jti {}", - bootstrapContext.accountId(), - scopeContext.tenantId(), - scopeContext.worldSlug(), - scopeContext.realmSlug(), - scopeContext.gameInstanceId(), - request.requestId(), - jti); - return result; + throw new AuthenticationException( + "AUTH_UNAVAILABLE", + "Account lacks the one-snapshot complete authority tuple, exact membership map, replay fence, and selected realm namespace/lifecycle evidence required to issue a gameplay-connect token"); } @Override 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 84c0cf780c..0d11463c9a 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 @@ -447,10 +447,13 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { 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")); + AuthenticationException onboardingTokenUnavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "first-play-after-join"))); assertTrue(first.success()); assertEquals("JOINED", first.outcomeCode()); @@ -458,7 +461,7 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { assertEquals(2L, first.membershipVersion()); assertTrue(retried.success()); assertTrue(retried.replayed()); - assertNotNull(onboardingToken.connectToken()); + assertEquals("AUTH_UNAVAILABLE", onboardingTokenUnavailable.getCode()); assertEquals(REALM_ID, retainedScope.get().realmId().toString()); assertEquals( first, @@ -1826,7 +1829,7 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { } @Test - void allAccountMintPathsUseCanonicalIssuerAndRetainTheirClaims() { + void accountJwtMintPathsRemainCanonicalAndConnectTokenFailsClosedWithoutAuthorityTuple() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1858,12 +1861,20 @@ void allAccountMintPathsUseCanonicalIssuerAndRetainTheirClaims() { when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) .thenReturn(Optional.of(membership(account, 7L))); - ConnectTokenResult connectToken = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "issuer-proof")); - assertCanonicalIssuerAndClaims(connectToken.connectToken(), "gameplay-connect", 11L); - assertEquals(7L, parseClaims(connectToken.connectToken()).get("tenantId", Long.class)); - assertEquals(17L, parseClaims(connectToken.connectToken()).get("pointerVersion", Long.class)); + AuthenticationException connectTokenUnavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "issuer-proof"))); + assertEquals("AUTH_UNAVAILABLE", connectTokenUnavailable.getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); Account otpAccount = new Account(); otpAccount.setId(12L); @@ -2674,7 +2685,7 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { } @Test - void issueConnectTokenReturnsShortLivedConnectToken() { + void issueConnectTokenFailsClosedWithoutCompleteSelectedTargetAuthorityEvidence() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -2694,32 +2705,28 @@ void issueConnectTokenReturnsShortLivedConnectToken() { String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - ConnectTokenResult result = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-3")); - - assertEquals(11L, result.accountId()); - assertEquals(7L, result.tenantId()); - assertEquals(44L, result.gameInstanceId()); - assertEquals(connectScopeId, result.connectScopeId()); - assertNotNull(result.connectToken()); - assertNotNull(result.jti()); - assertEquals("req-3", result.requestId()); - assertNotNull(result.issuedAt()); - assertNotNull(result.expiresAt()); - assertTrue(!result.replayed()); - var connectTokenClaims = - new JwtUtil("mysecretkey123456789012345678901", 30000L) - .parseToken(result.connectToken()) - .getPayload(); - assertEquals("gameplay-connect", connectTokenClaims.getAudience().iterator().next()); - assertEquals(17L, ((Number) connectTokenClaims.get("pointerVersion")).longValue()); - org.mockito.Mockito.verify(sessionService) - .storeSession( + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-3"))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( org.mockito.ArgumentMatchers.eq(7L), org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(connectScopeId), + org.mockito.ArgumentMatchers.eq("req-3"), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.eq(30000L)); + org.mockito.ArgumentMatchers.anyLong()); org.mockito.Mockito.verifyNoInteractions(accountRealmAccessGrantRepository); } @@ -2894,12 +2901,13 @@ void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFail !replay.success() && "ENTITLEMENT_UNAVAILABLE".equals(replay.errorCode())), org.mockito.ArgumentMatchers.anyLong()); - ConnectTokenResult retried = service.issueConnectToken(bootstrap.bootstrapToken(), request); + AuthenticationException contextUnavailable = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); - assertEquals("req-entitlement-retry", retried.requestId()); - assertNotNull(retried.connectToken()); - assertFalse(retried.replayed()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(1)) + assertEquals("AUTH_UNAVAILABLE", contextUnavailable.getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) .storeConnectTokenReplay( org.mockito.ArgumentMatchers.eq(7L), org.mockito.ArgumentMatchers.eq(11L), @@ -3077,62 +3085,33 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { } @Test - void issueConnectTokenReplaysSameTokenWhenPublicScopeStillMatchesPointer() { + void issueConnectTokenDoesNotReplayCachedLegacySuccess() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - ConnectTokenResult firstResult = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); - + ConnectTokenResult legacyCachedResult = + new ConnectTokenResult( + 11L, + 7L, + 44L, + "production", + connectScopeId, + "legacy-cached-token", + "legacy-jti", + "req-replay-1", + "2026-09-30T00:00:00Z", + "2026-09-30T00:00:30Z", + false); when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) - .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, firstResult, "", ""))); - - ConnectTokenResult replayed = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); - - assertEquals(firstResult.connectToken(), replayed.connectToken()); - assertEquals(firstResult.issuedAt(), replayed.issuedAt()); - assertEquals(firstResult.expiresAt(), replayed.expiresAt()); - assertEquals(firstResult.requestId(), replayed.requestId()); - assertTrue(replayed.replayed()); - - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("99") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); + Optional.of(new SessionService.ConnectTokenReplay(true, legacyCachedResult, "", ""))); AuthenticationException staleReplayException = assertThrows( @@ -3142,11 +3121,25 @@ void issueConnectTokenReplaysSameTokenWhenPublicScopeStillMatchesPointer() { bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1"))); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", staleReplayException.getCode()); + assertEquals("AUTH_UNAVAILABLE", staleReplayException.getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong()); } @Test - void issueConnectTokenRejectsCachedSuccessForNonPublicRealm() { + void issueConnectTokenRejectsCachedLegacySuccessForNonPublicRealm() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -3177,7 +3170,7 @@ void issueConnectTokenRejectsCachedSuccessForNonPublicRealm() { context.bootstrapToken(), new ConnectTokenRequest(context.connectScopeId(), "req-private-cached"))); - assertEquals("REALM_ACCESS_DENIED", exception.getCode()); + assertEquals("AUTH_UNAVAILABLE", exception.getCode()); org.mockito.Mockito.verify(accountRealmAccessGrantRepository, org.mockito.Mockito.never()) .existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug(11L, 7L, "demo", "preview"); } diff --git a/services/common-security/build.gradle.kts b/services/common-security/build.gradle.kts index 4109423d1f..b4ecc31ed5 100644 --- a/services/common-security/build.gradle.kts +++ b/services/common-security/build.gradle.kts @@ -7,6 +7,7 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") dependencies { api(project(":common-platform-core")) implementation(libs.jjwt.api) + implementation("com.fasterxml.jackson.core:jackson-databind") implementation(libs.spring.aop) implementation(libs.spring.boot.starter) compileOnly(libs.spring.boot.starter.web) @@ -17,4 +18,5 @@ dependencies { runtimeOnly(libs.jjwt.jackson) testImplementation(libs.spring.boot.starter.test) + testImplementation(testFixtures(project(":common-test-support"))) } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContext.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContext.java new file mode 100644 index 0000000000..04c0b6f072 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContext.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.common.security; + +import java.math.BigInteger; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** + * The exact Gateway-signed connect-context envelope after signature and semantic validation. + * + *

The compact envelope and its verified payload are retained verbatim so a later Account + * exchange can verify the original Gateway assertion instead of trusting a claims-only projection. + * Do not log this object or serialize it to a general-purpose diagnostic surface. + */ +public final class GatewayConnectContext { + private final String signedEnvelope; + private final byte[] signedPayload; + private final String kid; + private final Map claims; + + GatewayConnectContext( + String signedEnvelope, byte[] signedPayload, String kid, Map claims) { + this.signedEnvelope = Objects.requireNonNull(signedEnvelope, "signed envelope is required"); + this.signedPayload = + Objects.requireNonNull(signedPayload, "signed payload is required").clone(); + this.kid = Objects.requireNonNull(kid, "Gateway key identifier is required"); + this.claims = immutableObject(claims); + } + + /** Returns the exact compact JWS that was verified. */ + public String signedEnvelope() { + return signedEnvelope; + } + + /** Returns a defensive copy of the exact signed UTF-8 payload bytes. */ + public byte[] signedPayload() { + return signedPayload.clone(); + } + + public String kid() { + return kid; + } + + /** Returns an immutable, recursively copied view of every accepted payload field. */ + public Map claims() { + return immutableObject(claims); + } + + public String text(String name) { + Object value = claims.get(name); + return value instanceof String text ? text : null; + } + + public BigInteger integer(String name) { + Object value = claims.get(name); + return value instanceof BigInteger integer ? integer : null; + } + + @Override + public String toString() { + return "GatewayConnectContext[kid=" + kid + ", payloadBytes=" + signedPayload.length + "]"; + } + + private static Map immutableObject(Map source) { + Objects.requireNonNull(source, "context claims are required"); + Map result = new LinkedHashMap<>(); + source.forEach((key, value) -> result.put(key, immutableValue(value))); + return Collections.unmodifiableMap(result); + } + + private static Object immutableValue(Object value) { + if (value instanceof Map map) { + Map typed = new LinkedHashMap<>(); + map.forEach( + (key, nested) -> { + if (!(key instanceof String text)) { + throw new IllegalArgumentException("context object keys must be strings"); + } + typed.put(text, immutableValue(nested)); + }); + return Collections.unmodifiableMap(typed); + } + if (value instanceof java.util.List list) { + return list.stream().map(GatewayConnectContext::immutableValue).toList(); + } + if (value instanceof String + || value instanceof Boolean + || value instanceof BigInteger + || value == null) { + return value; + } + throw new IllegalArgumentException("unsupported decoded context value type"); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java new file mode 100644 index 0000000000..2a07401c0e --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java @@ -0,0 +1,607 @@ +package net.firedevops.firemud.common.security; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.math.BigInteger; +import java.time.Clock; +import java.time.Instant; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * Verifies and validates the registered Gateway-to-Game Session connect-context schema. + * + *

Signature verification deliberately precedes JSON parsing and semantic interpretation. This + * codec accepts only the canonical selected-target schema; it does not accept JWTs, aliases, + * partial routing claims, or legacy numeric identifiers. + */ +public final class GatewayConnectContextCodec { + public static final String AUDIENCE = "game-session"; + public static final String RECIPIENT = "game-session-service"; + public static final long MAX_CONTEXT_LIFETIME_SECONDS = 30L; + public static final long MAX_CLOCK_SKEW_SECONDS = 5L; + + private static final Set REQUIRED_FIELDS = + Set.of( + "accountId", + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "pointerVersion", + "catalogRevision", + "connectScopeId", + "connectRequestId", + "audience", + "recipient", + "authorityTuple", + "membershipVersion", + "replayAdmissionFence", + "connectTokenJti", + "issuedAt", + "verifiedAt", + "expiresAt", + "gatewayRequestId"); + private static final Set SOURCE_REQUIRED_FIELDS = + Set.of( + "iss", + "aud", + "iat", + "exp", + "jti", + "accountId", + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "pointerVersion", + "catalogRevision", + "connectScopeId", + "requestId", + "authorityTuple", + "membershipVersion", + "replayAdmissionFence"); + private static final Set CONDITIONAL_FIELDS = + Set.of("playtestLifecycleId", "playtestStateGeneration"); + private static final Set AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set TENANT_CUTOFF_FIELDS = + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"); + private static final Set PRIVATE_GRANT_FIELDS = + Set.of("tenantId", "worldSlug", "realmSlug", "playtestLifecycleId", "grantVersion"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS); + + private GatewayConnectContextCodec() {} + + /** + * Projects an already signature/profile-verified Account gameplay-connect claim map into the + * registered Gateway context shape. This method is not an Account JWT verifier or an + * authentication grant; callers must complete Account signature, issuer, audience, time, key, and + * profile verification before invoking it. It validates the closed source shape again, preserves + * all selected-target and authority evidence, maps only the registered claim names, and + * calculates a deadline that cannot outlive the source token. + */ + public static Map projectVerifiedAccountGameplayConnectClaims( + Map verifiedSourceClaims, long gatewayVerifiedAt, String gatewayRequestId) { + Map source = normalizeObject(verifiedSourceClaims, "Account claims"); + validateSourceClaims(source, gatewayVerifiedAt); + try { + Instant.ofEpochSecond(gatewayVerifiedAt); + } catch (java.time.DateTimeException ex) { + throw invalid("Gateway verification time is outside the supported epoch-second range"); + } + Map context = new LinkedHashMap<>(); + for (String field : + List.of( + "accountId", + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "pointerVersion", + "catalogRevision", + "connectScopeId", + "authorityTuple", + "membershipVersion", + "replayAdmissionFence")) { + context.put(field, source.get(field)); + } + if (source.containsKey("playtestLifecycleId")) { + context.put("playtestLifecycleId", source.get("playtestLifecycleId")); + context.put("playtestStateGeneration", source.get("playtestStateGeneration")); + } + context.put("connectRequestId", source.get("requestId")); + context.put("audience", AUDIENCE); + context.put("recipient", RECIPIENT); + context.put("connectTokenJti", source.get("jti")); + context.put("issuedAt", source.get("iat")); + context.put("verifiedAt", BigInteger.valueOf(gatewayVerifiedAt)); + context.put( + "expiresAt", + BigInteger.valueOf( + requireGatewayDeadline( + requirePositiveInteger(source, "iat").longValueExact(), + requirePositiveInteger(source, "exp").longValueExact(), + gatewayVerifiedAt))); + context.put("gatewayRequestId", gatewayRequestId); + validate(context, Instant.ofEpochSecond(gatewayVerifiedAt)); + return immutableObject(context); + } + + /** + * Verifies a compact Gateway Ed25519 JWS, then validates its complete semantic schema and time + * window. Expiration has no skew grace: skew cannot extend the signed lifetime. + */ + public static GatewayConnectContext verifyAndDecode( + String signedEnvelope, + Map gatewayVerificationKeys, + Clock clock) { + if (clock == null) { + throw new IllegalArgumentException("clock is required"); + } + GatewayConnectContextSignature.VerifiedContext verified = + GatewayConnectContextSignature.verify(signedEnvelope, gatewayVerificationKeys); + Map claims = parsePayload(verified.payload()); + validate(claims, clock.instant()); + return new GatewayConnectContext(signedEnvelope, verified.payload(), verified.kid(), claims); + } + + /** + * Computes the Gateway assertion deadline without changing the Account-issued time anchor. The + * caller must reject an already-expired source token; no configured skew is added here. + */ + public static long requireGatewayDeadline( + long sourceIssuedAt, long sourceExpiresAt, long gatewayVerifiedAt) { + if (sourceIssuedAt <= 0 || sourceExpiresAt <= sourceIssuedAt || gatewayVerifiedAt <= 0) { + throw invalid("invalid source connect-token lifetime"); + } + if (BigInteger.valueOf(sourceIssuedAt) + .subtract(BigInteger.valueOf(gatewayVerifiedAt)) + .compareTo(BigInteger.valueOf(MAX_CLOCK_SKEW_SECONDS)) + > 0) { + throw invalid("source connect-token issuedAt exceeds the permitted future clock skew"); + } + long lifetimeDeadline; + try { + lifetimeDeadline = Math.addExact(sourceIssuedAt, MAX_CONTEXT_LIFETIME_SECONDS); + } catch (ArithmeticException ex) { + throw invalid("source connect-token issuedAt is outside the supported range"); + } + if (sourceExpiresAt > lifetimeDeadline) { + throw invalid("source connect-token lifetime exceeds 30 seconds"); + } + long deadline = Math.min(sourceExpiresAt, lifetimeDeadline); + if (gatewayVerifiedAt >= deadline) { + throw invalid("source connect token is expired"); + } + return deadline; + } + + private static Map parsePayload(byte[] payload) { + try (var parser = JSON.getFactory().createParser(payload)) { + Object decoded = JSON.readValue(parser, Object.class); + if (parser.nextToken() != null || !(decoded instanceof Map rawObject)) { + throw invalid("Gateway context payload must be one JSON object"); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : rawObject.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalid("Gateway context object keys must be strings"); + } + result.put(key, entry.getValue()); + } + return result; + } catch (IOException ex) { + throw invalid("Gateway context payload is not valid JSON"); + } + } + + private static void validate(Map claims, Instant now) { + Set allowed = new java.util.HashSet<>(REQUIRED_FIELDS); + allowed.addAll(CONDITIONAL_FIELDS); + if (!allowed.containsAll(claims.keySet()) || !claims.keySet().containsAll(REQUIRED_FIELDS)) { + throw invalid("Gateway context fields do not match the registered schema"); + } + + requireUuid(claims, "accountId"); + String tenantId = requireUuid(claims, "tenantId"); + requireUuid(claims, "realmId"); + requireUuid(claims, "gameInstanceId"); + requireCanonicalSlug(claims, "worldSlug"); + requireCanonicalSlug(claims, "realmSlug"); + requireUuid(claims, "playableStateNamespaceId"); + requireOneOf( + claims, + "playableStateScope", + "PLAYABLE_STATE_SCOPE_SHARED", + "PLAYABLE_STATE_SCOPE_ISOLATED"); + requirePositiveInteger(claims, "pointerVersion"); + requirePositiveInteger(claims, "catalogRevision"); + requireText(claims, "connectScopeId"); + requireText(claims, "connectRequestId"); + requireText(claims, "connectTokenJti"); + requireText(claims, "gatewayRequestId"); + requireEqual(claims, "audience", AUDIENCE); + requireEqual(claims, "recipient", RECIPIENT); + + boolean hasLifecycle = claims.containsKey("playtestLifecycleId"); + boolean hasGeneration = claims.containsKey("playtestStateGeneration"); + if (hasLifecycle != hasGeneration) { + throw invalid("playtest lifecycle and generation must be present together"); + } + String lifecycleId = null; + if (hasLifecycle) { + lifecycleId = requireUuid(claims, "playtestLifecycleId"); + requirePositiveInteger(claims, "playtestStateGeneration"); + } + + Map tuple = requireObject(claims.get("authorityTuple"), "authorityTuple"); + validateAuthorityTuple(tuple, tenantId, claims, lifecycleId); + Map membershipVersion = + requireObject(claims.get("membershipVersion"), "membershipVersion"); + requireSingleTenantCounter(membershipVersion, tenantId, "membershipVersion"); + requirePositiveInteger(claims, "replayAdmissionFence"); + + BigInteger issuedAt = requirePositiveInteger(claims, "issuedAt"); + BigInteger verifiedAt = requirePositiveInteger(claims, "verifiedAt"); + BigInteger expiresAt = requirePositiveInteger(claims, "expiresAt"); + BigInteger maxLifetime = BigInteger.valueOf(MAX_CONTEXT_LIFETIME_SECONDS); + BigInteger duration = expiresAt.subtract(issuedAt); + if (duration.signum() <= 0 || duration.compareTo(maxLifetime) > 0) { + throw invalid("Gateway context lifetime must be positive and no longer than 30 seconds"); + } + if (verifiedAt.compareTo(expiresAt) >= 0 + || issuedAt.subtract(verifiedAt).compareTo(BigInteger.valueOf(MAX_CLOCK_SKEW_SECONDS)) + > 0) { + throw invalid("Gateway context verification time is outside its signed lifetime"); + } + BigInteger nowSeconds = BigInteger.valueOf(now.getEpochSecond()); + BigInteger latestAllowedVerification = + nowSeconds.add(BigInteger.valueOf(MAX_CLOCK_SKEW_SECONDS)); + if (verifiedAt.compareTo(latestAllowedVerification) > 0 + || issuedAt.compareTo(latestAllowedVerification) > 0) { + throw invalid("Gateway context time is too far in the future"); + } + if (expiresAt.compareTo(nowSeconds) <= 0) { + throw invalid("Gateway context is expired"); + } + try { + Instant.ofEpochSecond(issuedAt.longValueExact()); + Instant.ofEpochSecond(verifiedAt.longValueExact()); + Instant.ofEpochSecond(expiresAt.longValueExact()); + } catch (ArithmeticException | java.time.DateTimeException ex) { + throw invalid("Gateway context time is outside the supported epoch-second range"); + } + } + + private static void validateAuthorityTuple( + Map tuple, String tenantId, Map context, String lifecycleId) { + Set allowed = new java.util.HashSet<>(AUTHORITY_TUPLE_FIELDS); + allowed.add("accountSecurityCutoff"); + allowed.add("tenantBillingCutoff"); + if (!allowed.containsAll(tuple.keySet()) + || !tuple.keySet().containsAll(AUTHORITY_TUPLE_FIELDS)) { + throw invalid("authorityTuple fields do not match the canonical schema"); + } + requirePositiveInteger(tuple, "issuerAuthGeneration"); + requirePositiveInteger(tuple, "accountAuthorityGeneration"); + requireSingleTenantCounter( + requireObject( + tuple.get("tenantAuthorityGeneration"), "authorityTuple.tenantAuthorityGeneration"), + tenantId, + "authorityTuple.tenantAuthorityGeneration"); + requireSingleTenantCounter( + requireObject( + tuple.get("membershipAuthorityGeneration"), + "authorityTuple.membershipAuthorityGeneration"), + tenantId, + "authorityTuple.membershipAuthorityGeneration"); + + Object grantsValue = tuple.get("privateRealmGrantVersions"); + if (!(grantsValue instanceof List grants)) { + throw invalid("authorityTuple.privateRealmGrantVersions must be an array"); + } + boolean hasLifecycle = lifecycleId != null; + if (hasLifecycle && grants.size() != 1 || !hasLifecycle && !grants.isEmpty()) { + throw invalid("private-realm grant evidence does not match target lifecycle shape"); + } + if (hasLifecycle) { + Map grant = requireObject(grants.getFirst(), "private realm grant"); + requireExactFields(grant, PRIVATE_GRANT_FIELDS, "private realm grant"); + requireEqual(grant, "tenantId", tenantId); + requireEqual(grant, "worldSlug", requireText(context, "worldSlug")); + requireEqual(grant, "realmSlug", requireText(context, "realmSlug")); + requireEqual(grant, "playtestLifecycleId", lifecycleId); + requirePositiveInteger(grant, "grantVersion"); + } + + if (tuple.containsKey("accountSecurityCutoff")) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "authorityTuple.accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff"); + if (!requirePositiveInteger(cutoff, "accountAuthorityGeneration") + .equals(requirePositiveInteger(tuple, "accountAuthorityGeneration"))) { + throw invalid("accountSecurityCutoff generation does not match authorityTuple"); + } + requireEqual( + cutoff, + "outboxStreamKey", + "account:auth-authority:v1:account/" + requireUuid(context, "accountId")); + requirePositiveInteger(cutoff, "outboxSequence"); + } + if (tuple.containsKey("tenantBillingCutoff")) { + Map cutoffs = + requireObject(tuple.get("tenantBillingCutoff"), "authorityTuple.tenantBillingCutoff"); + if (cutoffs.size() != 1 || !cutoffs.containsKey(tenantId)) { + throw invalid("tenantBillingCutoff must contain only the selected tenant"); + } + Map cutoff = + requireObject(cutoffs.get(tenantId), "authorityTuple.tenantBillingCutoff entry"); + requireExactFields(cutoff, TENANT_CUTOFF_FIELDS, "tenantBillingCutoff entry"); + if (!requirePositiveInteger(cutoff, "tenantAuthorityGeneration") + .equals( + requirePositiveInteger( + requireObject( + tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"), + tenantId))) { + throw invalid("tenantBillingCutoff generation does not match authorityTuple"); + } + requireNonNegativeInteger(cutoff, "tenantBillingSequence"); + requireEqual(cutoff, "outboxStreamKey", "account:auth-authority:v1:tenant/" + tenantId); + requirePositiveInteger(cutoff, "outboxSequence"); + } + } + + private static void validateSourceClaims(Map source, long gatewayVerifiedAt) { + Set allowed = new java.util.HashSet<>(SOURCE_REQUIRED_FIELDS); + allowed.addAll(CONDITIONAL_FIELDS); + if (!allowed.containsAll(source.keySet()) + || !source.keySet().containsAll(SOURCE_REQUIRED_FIELDS)) { + throw invalid("Account gameplay-connect fields do not match the registered source schema"); + } + requireText(source, "iss"); + requireEqual(source, "aud", "gameplay-connect"); + requireUuid(source, "accountId"); + String tenantId = requireUuid(source, "tenantId"); + requireUuid(source, "realmId"); + requireUuid(source, "gameInstanceId"); + requireCanonicalSlug(source, "worldSlug"); + requireCanonicalSlug(source, "realmSlug"); + requireUuid(source, "playableStateNamespaceId"); + requireOneOf( + source, + "playableStateScope", + "PLAYABLE_STATE_SCOPE_SHARED", + "PLAYABLE_STATE_SCOPE_ISOLATED"); + requirePositiveInteger(source, "pointerVersion"); + requirePositiveInteger(source, "catalogRevision"); + requireText(source, "connectScopeId"); + requireText(source, "requestId"); + requireText(source, "jti"); + + boolean hasLifecycle = source.containsKey("playtestLifecycleId"); + boolean hasGeneration = source.containsKey("playtestStateGeneration"); + if (hasLifecycle != hasGeneration) { + throw invalid("Account playtest lifecycle and generation must be present together"); + } + String lifecycleId = null; + if (hasLifecycle) { + lifecycleId = requireUuid(source, "playtestLifecycleId"); + requirePositiveInteger(source, "playtestStateGeneration"); + } + + validateAuthorityTuple( + requireObject(source.get("authorityTuple"), "authorityTuple"), + tenantId, + source, + lifecycleId); + requireSingleTenantCounter( + requireObject(source.get("membershipVersion"), "membershipVersion"), + tenantId, + "membershipVersion"); + requirePositiveInteger(source, "replayAdmissionFence"); + BigInteger issuedAt = requirePositiveInteger(source, "iat"); + BigInteger expiresAt = requirePositiveInteger(source, "exp"); + try { + requireGatewayDeadline( + issuedAt.longValueExact(), expiresAt.longValueExact(), gatewayVerifiedAt); + } catch (ArithmeticException ex) { + throw invalid("Account gameplay-connect time is outside the supported epoch-second range"); + } + } + + private static Map normalizeObject(Map source, String name) { + if (source == null) { + throw invalid(name + " are required"); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : ((Map) source).entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalid(name + " keys must be strings"); + } + result.put(key, normalizeJsonValue(entry.getValue())); + } + return result; + } + + private static Object normalizeJsonValue(Object value) { + if (value instanceof BigInteger integer) { + return integer; + } + if (value instanceof Byte + || value instanceof Short + || value instanceof Integer + || value instanceof Long) { + return BigInteger.valueOf(((Number) value).longValue()); + } + if (value instanceof Map rawObject) { + Map nested = new LinkedHashMap<>(); + rawObject.forEach( + (key, nestedValue) -> { + if (!(key instanceof String text)) { + throw invalid("Account gameplay-connect object keys must be strings"); + } + nested.put(text, normalizeJsonValue(nestedValue)); + }); + return nested; + } + if (value instanceof List list) { + return list.stream().map(GatewayConnectContextCodec::normalizeJsonValue).toList(); + } + if (value instanceof String || value instanceof Boolean || value == null) { + return value; + } + throw invalid("Account gameplay-connect claims contain a non-JSON or non-integral value"); + } + + private static void requireSingleTenantCounter( + Map counters, String tenantId, String field) { + if (counters.size() != 1 || !counters.containsKey(tenantId)) { + throw invalid(field + " must contain exactly the selected tenant"); + } + requirePositiveInteger(counters, tenantId); + } + + private static String requireUuid(Map object, String name) { + String value = requireText(object, name); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw invalid(name + " must be a canonical UUID"); + } + } catch (IllegalArgumentException ex) { + throw invalid(name + " must be a canonical UUID"); + } + return value; + } + + private static String requireCanonicalSlug(Map object, String name) { + String value = requireText(object, name); + GameplayRoutingBundleValidator.requireCanonicalSlug(value, name); + return value; + } + + private static String requireText(Map object, String name) { + Object value = object.get(name); + if (!(value instanceof String text) + || text.isEmpty() + || text.length() > 512 + || !text.equals(text.strip()) + || text.chars().anyMatch(Character::isISOControl)) { + throw invalid(name + " must be non-empty bounded text"); + } + return text; + } + + private static String requireOneOf( + Map object, String name, String first, String second) { + String value = requireText(object, name); + if (!first.equals(value) && !second.equals(value)) { + throw invalid(name + " has an unsupported value"); + } + return value; + } + + private static void requireEqual(Map object, String name, String expected) { + if (!expected.equals(requireText(object, name))) { + throw invalid(name + " does not match its registered value"); + } + } + + private static BigInteger requirePositiveInteger(Map object, String name) { + BigInteger value = requireInteger(object, name); + if (value.signum() <= 0) { + throw invalid(name + " must be positive"); + } + return value; + } + + private static BigInteger requireNonNegativeInteger(Map object, String name) { + BigInteger value = requireInteger(object, name); + if (value.signum() < 0) { + throw invalid(name + " must not be negative"); + } + return value; + } + + private static BigInteger requireInteger(Map object, String name) { + Object value = object.get(name); + if (!(value instanceof BigInteger integer)) { + throw invalid(name + " must be an exact JSON integer"); + } + return integer; + } + + private static Map requireObject(Object value, String name) { + if (!(value instanceof Map rawObject)) { + throw invalid(name + " must be a JSON object"); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : rawObject.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalid(name + " keys must be strings"); + } + result.put(key, entry.getValue()); + } + return result; + } + + private static void requireExactFields( + Map object, Set fields, String name) { + if (!object.keySet().equals(fields)) { + throw invalid(name + " fields do not match the canonical schema"); + } + } + + private static Map immutableObject(Map source) { + Map result = new LinkedHashMap<>(); + source.forEach((key, value) -> result.put(key, immutableValue(value))); + return Collections.unmodifiableMap(result); + } + + private static Object immutableValue(Object value) { + if (value instanceof Map rawObject) { + Map nested = new LinkedHashMap<>(); + rawObject.forEach((key, child) -> nested.put((String) key, immutableValue(child))); + return Collections.unmodifiableMap(nested); + } + if (value instanceof List list) { + return list.stream().map(GatewayConnectContextCodec::immutableValue).toList(); + } + return value; + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java new file mode 100644 index 0000000000..35fa22b348 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java @@ -0,0 +1,436 @@ +package unit.net.firedevops.firemud.common.security; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.security.GatewayConnectContext; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.test.SelectedTargetConnectContextTestVectors; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class GatewayConnectContextCodecTest { + private static final String KID = SelectedTargetConnectContextTestVectors.GATEWAY_KID; + private static final Instant NOW = + Instant.ofEpochSecond(SelectedTargetConnectContextTestVectors.NOW_EPOCH_SECONDS); + + private final ObjectMapper json = new ObjectMapper(); + private KeyPair keyPair; + private Clock clock; + + @BeforeEach + void setUp() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("Ed25519"); + keyPair = generator.generateKeyPair(); + clock = Clock.fixed(NOW, ZoneOffset.UTC); + } + + @Test + void verifiesRealEd25519ContextAndPreservesExactEnvelopeAndEveryAcceptedField() throws Exception { + byte[] payload = json.writeValueAsBytes(validContext()); + String envelope = GatewayConnectContextSignature.sign(payload, KID, keyPair.getPrivate()); + + GatewayConnectContext context = verify(envelope); + + assertEquals(envelope, context.signedEnvelope()); + assertArrayEquals(payload, context.signedPayload()); + Map source = SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + assertEquals("game-session", context.text("audience")); + assertEquals("game-session-service", context.text("recipient")); + assertEquals(source.get("tenantId"), context.text("tenantId")); + assertEquals(source.get("requestId"), context.text("connectRequestId")); + assertEquals(source.get("jti"), context.text("connectTokenJti")); + assertEquals(source.get("iat"), context.integer("issuedAt")); + long sourceDeadline = + GatewayConnectContextCodec.requireGatewayDeadline( + ((BigInteger) source.get("iat")).longValueExact(), + ((BigInteger) source.get("exp")).longValueExact(), + context.integer("verifiedAt").longValueExact()); + assertEquals(SelectedTargetConnectContextTestVectors.SOURCE_EXPIRES_AT, sourceDeadline); + assertEquals(BigInteger.valueOf(sourceDeadline), context.integer("expiresAt")); + assertTrue(context.integer("expiresAt").longValueExact() <= sourceDeadline); + assertEquals( + SelectedTargetConnectContextTestVectors.LARGE_COUNTER, + context.integer("replayAdmissionFence")); + assertEquals( + SelectedTargetConnectContextTestVectors.LARGE_COUNTER, + nested( + context.claims(), + "authorityTuple", + "membershipAuthorityGeneration", + SelectedTargetConnectContextTestVectors.TENANT_ID)); + assertEquals(validContext().keySet(), context.claims().keySet()); + assertThrows( + UnsupportedOperationException.class, () -> context.claims().put("audience", "other")); + } + + @Test + void rejectsDuplicateKeysUnknownContextFieldsAndTrailingJsonAfterSignatureVerification() + throws Exception { + String validJson = json.writeValueAsString(validContext()); + String duplicateAudience = + validJson.replace( + "\"audience\":\"game-session\"", + "\"audience\":\"game-session\",\"audience\":\"game-session\""); + String duplicateKeyEnvelope = + GatewayConnectContextSignature.sign( + duplicateAudience.getBytes(StandardCharsets.UTF_8), KID, keyPair.getPrivate()); + assertThrows(IllegalArgumentException.class, () -> verify(duplicateKeyEnvelope)); + + Map unknownField = validContext(); + unknownField.put("unregisteredContextField", "not-accepted"); + assertRejected(unknownField); + + String trailingJsonEnvelope = + GatewayConnectContextSignature.sign( + (validJson + " {} ").getBytes(StandardCharsets.UTF_8), KID, keyPair.getPrivate()); + assertThrows(IllegalArgumentException.class, () -> verify(trailingJsonEnvelope)); + } + + @Test + void returnedAuthorityClaimsAreRecursivelyImmutableAndPayloadBytesAreDefensiveCopies() + throws Exception { + byte[] originalPayload = json.writeValueAsBytes(validContext()); + String envelope = + GatewayConnectContextSignature.sign(originalPayload, KID, keyPair.getPrivate()); + GatewayConnectContext context = verify(envelope); + + byte[] exposedPayload = context.signedPayload(); + exposedPayload[0] ^= 1; + assertArrayEquals(originalPayload, context.signedPayload()); + assertEquals(envelope, context.signedEnvelope()); + + Map claims = context.claims(); + @SuppressWarnings("unchecked") + Map authorityTuple = (Map) claims.get("authorityTuple"); + assertThrows( + UnsupportedOperationException.class, + () -> authorityTuple.put("accountAuthorityGeneration", BigInteger.ZERO)); + @SuppressWarnings("unchecked") + Map tenantGenerations = + (Map) authorityTuple.get("tenantAuthorityGeneration"); + assertThrows( + UnsupportedOperationException.class, + () -> + tenantGenerations.put( + SelectedTargetConnectContextTestVectors.TENANT_ID, BigInteger.ZERO)); + assertEquals( + SelectedTargetConnectContextTestVectors.LARGE_COUNTER, + nested( + context.claims(), + "authorityTuple", + "membershipAuthorityGeneration", + SelectedTargetConnectContextTestVectors.TENANT_ID)); + assertArrayEquals(originalPayload, context.signedPayload()); + + Map privateClaims = + projectContext(SelectedTargetConnectContextTestVectors.privateSourceConnectTokenClaims()); + GatewayConnectContext privateContext = verify(sign(privateClaims)); + @SuppressWarnings("unchecked") + Map privateAuthorityTuple = + (Map) privateContext.claims().get("authorityTuple"); + @SuppressWarnings("unchecked") + List grants = (List) privateAuthorityTuple.get("privateRealmGrantVersions"); + assertThrows(UnsupportedOperationException.class, () -> grants.add(Map.of())); + @SuppressWarnings("unchecked") + Map grant = (Map) grants.getFirst(); + assertThrows( + UnsupportedOperationException.class, () -> grant.put("grantVersion", BigInteger.ZERO)); + assertEquals(privateClaims, privateContext.claims()); + } + + @Test + void rejectsMissingOrChangedTargetAndWrongReceiverBindings() throws Exception { + Map missingTarget = validContext(); + missingTarget.remove("realmId"); + assertRejected(missingTarget); + + Map changedTarget = validContext(); + changedTarget.put("tenantId", "018f8f0a-8c1d-7f9a-ad6a-bf4a312c0d8e"); + assertRejected(changedTarget); + + Map wrongAudience = validContext(); + wrongAudience.put("audience", "account-service"); + assertRejected(wrongAudience); + + Map wrongRecipient = validContext(); + wrongRecipient.put("recipient", "another-service"); + assertRejected(wrongRecipient); + } + + @Test + void rejectsMalformedMapsAndNonCanonicalCounters() throws Exception { + Map missingMembership = validContext(); + missingMembership.put("membershipVersion", Map.of()); + assertRejected(missingMembership); + + Map malformedAuthority = validContext(); + @SuppressWarnings("unchecked") + Map tuple = + new LinkedHashMap<>((Map) malformedAuthority.get("authorityTuple")); + tuple.put( + "membershipAuthorityGeneration", + Map.of(SelectedTargetConnectContextTestVectors.TENANT_ID, "7")); + malformedAuthority.put("authorityTuple", tuple); + assertRejected(malformedAuthority); + + Map fractionalCounter = validContext(); + fractionalCounter.put("replayAdmissionFence", 1.5d); + assertRejected(fractionalCounter); + + Map numericLegacyIdentity = validContext(); + numericLegacyIdentity.put("accountId", 42); + assertRejected(numericLegacyIdentity); + + Map stringLegacyInstanceId = validContext(); + stringLegacyInstanceId.put("gameInstanceId", "9"); + assertRejected(stringLegacyInstanceId); + + Map opaqueLegacyNamespace = validContext(); + opaqueLegacyNamespace.put("playableStateNamespaceId", "namespace-9"); + assertRejected(opaqueLegacyNamespace); + } + + @Test + void validatesConditionalNonPublicLifecycleAndExactGrantShape() throws Exception { + Map privateContext = + projectContext(SelectedTargetConnectContextTestVectors.privateSourceConnectTokenClaims()); + GatewayConnectContext verified = verify(sign(privateContext)); + assertEquals("preview", verified.text("realmSlug")); + assertEquals("018f8f0a-7ac1-7f79-be6a-bf4a312c0d8e", verified.text("playtestLifecycleId")); + + Map missingGeneration = + projectContext(SelectedTargetConnectContextTestVectors.privateSourceConnectTokenClaims()); + missingGeneration.remove("playtestStateGeneration"); + assertRejected(missingGeneration); + + Map wrongGrantLifecycle = + projectContext(SelectedTargetConnectContextTestVectors.privateSourceConnectTokenClaims()); + @SuppressWarnings("unchecked") + Map tuple = + new LinkedHashMap<>((Map) wrongGrantLifecycle.get("authorityTuple")); + @SuppressWarnings("unchecked") + List> grants = + (List>) tuple.get("privateRealmGrantVersions"); + Map grant = new LinkedHashMap<>(grants.getFirst()); + grant.put("playtestLifecycleId", "018f8f0a-8c1d-7f9a-ad6a-bf4a312c0d8e"); + tuple.put("privateRealmGrantVersions", List.of(grant)); + wrongGrantLifecycle.put("authorityTuple", tuple); + assertRejected(wrongGrantLifecycle); + } + + @Test + void acceptsZeroTenantBillingBaselineButRequiresPositiveOutboxSequence() throws Exception { + Map withBillingCutoff = validContext(); + @SuppressWarnings("unchecked") + Map tuple = + new LinkedHashMap<>((Map) withBillingCutoff.get("authorityTuple")); + tuple.put( + "tenantBillingCutoff", + Map.of( + SelectedTargetConnectContextTestVectors.TENANT_ID, + Map.of( + "tenantAuthorityGeneration", + BigInteger.valueOf(13), + "tenantBillingSequence", + BigInteger.ZERO, + "outboxStreamKey", + "account:auth-authority:v1:tenant/" + + SelectedTargetConnectContextTestVectors.TENANT_ID, + "outboxSequence", + BigInteger.ONE))); + withBillingCutoff.put("authorityTuple", tuple); + assertEquals("production", verify(sign(withBillingCutoff)).text("realmSlug")); + + Map zeroOutboxSequence = validContext(); + @SuppressWarnings("unchecked") + Map badTuple = + new LinkedHashMap<>((Map) zeroOutboxSequence.get("authorityTuple")); + badTuple.put( + "tenantBillingCutoff", + Map.of( + SelectedTargetConnectContextTestVectors.TENANT_ID, + Map.of( + "tenantAuthorityGeneration", + BigInteger.valueOf(13), + "tenantBillingSequence", + BigInteger.ZERO, + "outboxStreamKey", + "account:auth-authority:v1:tenant/" + + SelectedTargetConnectContextTestVectors.TENANT_ID, + "outboxSequence", + BigInteger.ZERO))); + zeroOutboxSequence.put("authorityTuple", badTuple); + assertRejected(zeroOutboxSequence); + } + + @Test + void projectsSourceExpiryWithoutExtendingItAndDoesNotMutateVerifiedClaims() throws Exception { + Map source = SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + String originalSource = json.writeValueAsString(source); + Map projected = projectContext(source); + assertEquals(originalSource, json.writeValueAsString(source)); + assertEquals(source.get("requestId"), projected.get("connectRequestId")); + assertEquals(source.get("jti"), projected.get("connectTokenJti")); + assertEquals(source.get("iat"), projected.get("issuedAt")); + assertEquals(source.get("authorityTuple"), projected.get("authorityTuple")); + assertEquals(source.get("membershipVersion"), projected.get("membershipVersion")); + assertEquals(source.get("replayAdmissionFence"), projected.get("replayAdmissionFence")); + assertEquals( + SelectedTargetConnectContextTestVectors.SOURCE_EXPIRES_AT, + ((BigInteger) projected.get("expiresAt")).longValueExact()); + assertEquals(false, projected.containsKey("requestId")); + assertEquals(false, projected.containsKey("exp")); + + Map shorterSource = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + long sourceIssuedAt = SelectedTargetConnectContextTestVectors.SOURCE_ISSUED_AT; + shorterSource.put("exp", BigInteger.valueOf(sourceIssuedAt + 10L)); + Map shorterContext = projectContext(shorterSource); + assertEquals( + sourceIssuedAt + 10L, ((BigInteger) shorterContext.get("expiresAt")).longValueExact()); + + Map futureIssuedSource = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + long gatewayVerifiedAt = SelectedTargetConnectContextTestVectors.NOW_EPOCH_SECONDS; + futureIssuedSource.put("iat", BigInteger.valueOf(gatewayVerifiedAt + 3L)); + futureIssuedSource.put("exp", BigInteger.valueOf(gatewayVerifiedAt + 15L)); + Map futureIssuedContext = projectContext(futureIssuedSource, gatewayVerifiedAt); + assertEquals(BigInteger.valueOf(gatewayVerifiedAt + 3L), futureIssuedContext.get("issuedAt")); + assertEquals(BigInteger.valueOf(gatewayVerifiedAt + 15L), futureIssuedContext.get("expiresAt")); + verify(sign(futureIssuedContext)); + + Map excessiveFutureIssuedSource = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + excessiveFutureIssuedSource.put("iat", BigInteger.valueOf(gatewayVerifiedAt + 6L)); + excessiveFutureIssuedSource.put("exp", BigInteger.valueOf(gatewayVerifiedAt + 20L)); + assertThrows( + IllegalArgumentException.class, + () -> projectContext(excessiveFutureIssuedSource, gatewayVerifiedAt)); + + Map overlongSource = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + overlongSource.put("exp", BigInteger.valueOf(sourceIssuedAt + 31L)); + assertThrows(IllegalArgumentException.class, () -> projectContext(overlongSource)); + + Map unknownSourceClaim = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + unknownSourceClaim.put("sub", SelectedTargetConnectContextTestVectors.ACCOUNT_ID); + assertThrows(IllegalArgumentException.class, () -> projectContext(unknownSourceClaim)); + } + + @Test + void rejectsMillisecondTimesExpiredContextAndClockSkewLifetimeExtension() throws Exception { + Map milliseconds = validContext(); + milliseconds.put("issuedAt", 1_700_000_000_000L); + milliseconds.put("verifiedAt", 1_700_000_000_000L); + milliseconds.put("expiresAt", 1_700_000_000_030L); + assertRejected(milliseconds); + + Map expired = validContext(); + expired.put("expiresAt", NOW.getEpochSecond()); + assertRejected(expired); + + Map extendsLifetimeWithSkew = validContext(); + extendsLifetimeWithSkew.put("expiresAt", NOW.getEpochSecond() + 31L); + assertRejected(extendsLifetimeWithSkew); + } + + @Test + void rejectsUnknownGatewayKeyAndWrongSignature() throws Exception { + String envelope = sign(validContext()); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.verifyAndDecode( + envelope, Map.of("another-key", keyPair.getPublic()), clock)); + + String[] parts = envelope.split("\\."); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + signature[0] ^= 1; + String wrongSignature = + parts[0] + + "." + + parts[1] + + "." + + Base64.getUrlEncoder().withoutPadding().encodeToString(signature); + assertThrows(IllegalArgumentException.class, () -> verify(wrongSignature)); + } + + @Test + void gatewayDeadlineUsesOriginalIssuedAtAndCapsAtSourceExpiration() { + long issuedAt = NOW.getEpochSecond() - 2; + assertEquals( + issuedAt + GatewayConnectContextCodec.MAX_CONTEXT_LIFETIME_SECONDS, + GatewayConnectContextCodec.requireGatewayDeadline( + issuedAt, + issuedAt + GatewayConnectContextCodec.MAX_CONTEXT_LIFETIME_SECONDS, + issuedAt + 1)); + assertEquals( + issuedAt + 10, + GatewayConnectContextCodec.requireGatewayDeadline(issuedAt, issuedAt + 10, issuedAt + 1)); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.requireGatewayDeadline( + issuedAt, issuedAt + 31, issuedAt + 1)); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.requireGatewayDeadline( + issuedAt, issuedAt + 10, issuedAt + 10)); + } + + private GatewayConnectContext verify(String envelope) { + return GatewayConnectContextCodec.verifyAndDecode( + envelope, Map.of(KID, keyPair.getPublic()), clock); + } + + private String sign(Map claims) throws Exception { + return GatewayConnectContextSignature.sign( + json.writeValueAsBytes(claims), KID, keyPair.getPrivate()); + } + + private void assertRejected(Map claims) throws Exception { + assertThrows(IllegalArgumentException.class, () -> verify(sign(claims))); + } + + private static BigInteger nested( + Map claims, String object, String nestedObject, String key) { + @SuppressWarnings("unchecked") + Map first = (Map) claims.get(object); + @SuppressWarnings("unchecked") + Map second = (Map) first.get(nestedObject); + return (BigInteger) second.get(key); + } + + private static Map validContext() { + return projectContext(SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims()); + } + + private static Map projectContext(Map source) { + return projectContext(source, SelectedTargetConnectContextTestVectors.GATEWAY_VERIFIED_AT); + } + + private static Map projectContext( + Map source, long gatewayVerifiedAt) { + return new LinkedHashMap<>( + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + source, gatewayVerifiedAt, "gateway-request-42")); + } +} diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/SelectedTargetConnectContextTestVectors.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/SelectedTargetConnectContextTestVectors.java new file mode 100644 index 0000000000..ee57feff63 --- /dev/null +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/SelectedTargetConnectContextTestVectors.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.test; + +import java.math.BigInteger; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Canonical Account gameplay-connect claim values shared by focused boundary tests. */ +public final class SelectedTargetConnectContextTestVectors { + public static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + public static final String TENANT_ID = "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f"; + public static final String REALM_ID = "018f8f0a-4d9e-7c46-be37-8c1d0e9f7a5b"; + public static final String NAMESPACE_ID = "018f8f0a-5eaf-7d57-9c48-9d2e1f0a8b6c"; + public static final String GAME_INSTANCE_ID = "018f8f0a-6fb0-7e68-ad59-ae3f201b9c7d"; + public static final String GATEWAY_KID = "gateway-context-key-2026-01"; + public static final long NOW_EPOCH_SECONDS = 1_700_000_000L; + public static final long SOURCE_ISSUED_AT = NOW_EPOCH_SECONDS - 2L; + public static final long SOURCE_EXPIRES_AT = SOURCE_ISSUED_AT + 30L; + public static final long GATEWAY_VERIFIED_AT = NOW_EPOCH_SECONDS - 1L; + public static final BigInteger LARGE_COUNTER = + new BigInteger("999999999999999999999999999999999999"); + + private SelectedTargetConnectContextTestVectors() {} + + /** A complete public-production Account JWT claim set before Gateway projection. */ + public static Map sourceConnectTokenClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("aud", "gameplay-connect"); + claims.put("accountId", ACCOUNT_ID); + claims.put("tenantId", TENANT_ID); + claims.put("realmId", REALM_ID); + claims.put("worldSlug", "demo-world"); + claims.put("realmSlug", "production"); + claims.put("playableStateNamespaceId", NAMESPACE_ID); + claims.put("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED"); + claims.put("gameInstanceId", GAME_INSTANCE_ID); + claims.put("pointerVersion", BigInteger.valueOf(17)); + claims.put("catalogRevision", BigInteger.valueOf(42)); + claims.put("connectScopeId", "connect-scope-17"); + claims.put("requestId", "connect-request-42"); + claims.put("authorityTuple", authorityTuple()); + claims.put("membershipVersion", Map.of(TENANT_ID, LARGE_COUNTER)); + claims.put("replayAdmissionFence", LARGE_COUNTER); + claims.put("jti", "connect-token-jti-42"); + claims.put("iat", BigInteger.valueOf(SOURCE_ISSUED_AT)); + claims.put("exp", BigInteger.valueOf(SOURCE_EXPIRES_AT)); + return claims; + } + + /** A private-realm source vector with matching lifecycle and exact grant evidence. */ + public static Map privateSourceConnectTokenClaims() { + Map claims = sourceConnectTokenClaims(); + claims.put("realmSlug", "preview"); + claims.put("playtestLifecycleId", "018f8f0a-7ac1-7f79-be6a-bf4a312c0d8e"); + claims.put("playtestStateGeneration", BigInteger.valueOf(3)); + @SuppressWarnings("unchecked") + Map tuple = + new LinkedHashMap<>((Map) claims.get("authorityTuple")); + tuple.put( + "privateRealmGrantVersions", + List.of( + Map.of( + "tenantId", + TENANT_ID, + "worldSlug", + "demo-world", + "realmSlug", + "preview", + "playtestLifecycleId", + claims.get("playtestLifecycleId"), + "grantVersion", + BigInteger.valueOf(5)))); + claims.put("authorityTuple", tuple); + return claims; + } + + private static Map authorityTuple() { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", BigInteger.TEN); + tuple.put("accountAuthorityGeneration", BigInteger.valueOf(12)); + tuple.put("tenantAuthorityGeneration", Map.of(TENANT_ID, BigInteger.valueOf(13))); + tuple.put("membershipAuthorityGeneration", Map.of(TENANT_ID, LARGE_COUNTER)); + tuple.put("privateRealmGrantVersions", List.of()); + return tuple; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java deleted file mode 100644 index 33defe407a..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.firedevops.firemud.gamesession.config; - -import net.firedevops.firemud.common.security.JwtUtil; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; - -@Configuration -public class FirstPartyConnectContextConfig { - - @Bean - @Qualifier("firstPartyConnectContextJwtUtil") - public JwtUtil firstPartyConnectContextJwtUtil(FirstPartyConnectContextProperties properties) { - String secret = properties.getJwtSecret(); - if (!StringUtils.hasText(secret)) { - secret = "missing-first-party-connect-context-secret"; - } - return new JwtUtil(secret, properties.getTtlMs()); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java index 715bc11f80..0f3ce06439 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java @@ -6,6 +6,6 @@ @Data @ConfigurationProperties(prefix = "firemud.gateway.connect-context") public class FirstPartyConnectContextProperties { - private String jwtSecret; + /** Local retention bound for an admitted context; this is not a signing or verification key. */ private long ttlMs = 30_000L; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java index 5882a8ed83..8f0c9bec70 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java @@ -1,69 +1,41 @@ package net.firedevops.firemud.gamesession.service; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.JwtException; +import java.security.PublicKey; +import java.time.Clock; +import java.util.Map; import java.util.Optional; -import net.firedevops.firemud.common.security.JwtClaims; -import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.gamesession.config.FirstPartyConnectContextProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Qualifier; +import net.firedevops.firemud.common.security.GatewayConnectContext; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; +/** Receives complete Gateway-signed contexts; no Account-JWT or shared-secret fallback exists. */ @Component -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected configuration properties are framework-managed singletons") public class FirstPartyConnectContextService { - private static final Logger logger = - LoggerFactory.getLogger(FirstPartyConnectContextService.class); - private final FirstPartyConnectContextProperties properties; - private final JwtUtil jwtUtil; - - public FirstPartyConnectContextService( - FirstPartyConnectContextProperties properties, - @Qualifier("firstPartyConnectContextJwtUtil") JwtUtil jwtUtil) { - this.properties = properties; - this.jwtUtil = jwtUtil; - } - - public Optional parse(String token) { - if (!StringUtils.hasText(token) || !StringUtils.hasText(properties.getJwtSecret())) { - return Optional.empty(); - } + /** + * Validates a context against the explicitly supplied Gateway public-key ring. + * + *

The Gateway key-publication source is not yet wired into the runtime. Callers must not + * replace the empty runtime key set with an Account JWT key or a test/default key. + */ + public Optional parseVerified( + String signedEnvelope, + Map gatewayVerificationKeys, + Clock clock) { try { - Claims claims = jwtUtil.parseToken(token).getPayload(); - JwtClaims.SignedGameplayRoutingClaims routingClaims = - JwtClaims.requireSignedGameplayRoutingClaims( - claims, "first-party connect context account subject mismatch"); return Optional.of( - new FirstPartyConnectContext( - routingClaims.accountId(), - routingClaims.tenantId(), - routingClaims.worldSlug(), - routingClaims.realmSlug(), - routingClaims.gameInstanceId(), - routingClaims.pointerVersion(), - requiredTextClaim(claims, "connectScopeId"), - stringClaim(claims, "connectTokenJti"), - requiredTextClaim(claims, "connectRequestId"), - stringClaim(claims, "gatewayRequestId"))); - } catch (IllegalArgumentException | JwtException ex) { - logger.warn("Rejecting invalid first-party connect context", ex); + GatewayConnectContextCodec.verifyAndDecode( + signedEnvelope, gatewayVerificationKeys, clock)); + } catch (IllegalArgumentException ex) { return Optional.empty(); } } - private static String stringClaim(Claims claims, String key) { - Object value = claims.get(key); - return value == null ? null : value.toString(); - } - - private static String requiredTextClaim(Claims claims, String key) { - return JwtClaims.requireText(claims.get(key), key); + /** + * Runtime admission remains closed until the independently published Gateway key set is wired. + * The legacy numeric Game Session carrier cannot be populated from canonical UUID target IDs. + */ + public Optional parse(String signedEnvelope) { + return Optional.empty(); } } diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index b080edd672..8cf95022ce 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -2,17 +2,14 @@ import static org.assertj.core.api.Assertions.assertThat; -import com.fasterxml.jackson.databind.JsonNode; import java.net.URI; import java.time.Duration; import java.util.List; -import java.util.Map; import net.firedevops.firemud.gamesession.test.ChatTestFixtures; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayCrossServiceStack; import net.firedevops.firemud.gamesession.testsupport.GameplayEntityAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplaySocialAssertions; -import net.firedevops.firemud.gamesession.testsupport.GameplayStructuredCommandAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; import net.firedevops.firemud.socialgroups.v1.ChatType; @@ -36,7 +33,6 @@ class CommunicationWebSocketCrossServiceTest { private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; - private static final String FIRST_PARTY_CONNECT_SECRET = "cross-service-connect-context-secret"; private static final String SORA_EMAIL = "sora@example.com"; private static final String NYX_EMAIL = "nyx@example.com"; @@ -300,9 +296,8 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc } @Test - void websocketFriendsMissingPolicyRedactsPresenceWithoutDisconnecting() throws Exception { + void websocketFriendsDetailRedactsMissingPolicyPresenceWithoutDisconnecting() throws Exception { ensureTestServicesStarted(); - long sessionId = prepareGameInstance(); FriendPresenceEntry missingPolicyPresence = FriendPresenceEntry.newBuilder() .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) @@ -318,37 +313,7 @@ void websocketFriendsMissingPolicyRedactsPresenceWithoutDisconnecting() throws E .setRealmDisplayName("Live Realm") .setActivityState(FriendPresenceActivityState.FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK) .build(); - socialStub().setFriendPresenceEntries(List.of(missingPolicyPresence)); - - try (GameplayWebSocketDriver client = - openFirstPartyGameplayClient("friends-missing-policy-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS"); - JsonNode friends = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode friendsPayload = requirePayload(friends, "friends_view"); - assertThat(friendsPayload.path("friends")).hasSize(1); - JsonNode entry = friendsPayload.path("friends").get(0); - assertThat(entry.path("friendAccountId").asLong()).isEqualTo(SORA_ACCOUNT_ID); - assertThat(entry.path("displayName").asText()).isEqualTo("Friend #" + SORA_ACCOUNT_ID); - for (String field : - List.of( - "online", - "worldSlug", - "worldDisplayName", - "realmSlug", - "realmDisplayName", - "characterName", - "playableStateScope", - "pointerVersion", - "activityState", - "lastSeenAtEpochMs", - "recentDisposition", - "visibilityPolicy")) { - assertThat(entry.has(field)).as("redacted field %s", field).isFalse(); - } - } - - sessionId = prepareGameInstance(); + long sessionId = prepareGameInstance(); socialStub().setFriendPresenceEntries(List.of(missingPolicyPresence)); try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-missing-policy-detail")) { @@ -496,300 +461,6 @@ void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } - @Test - void websocketFirstPartyBareLoginFailsClosedBeforeGameplayAdmission() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyClient("bare-login-unavailable")) { - client.send("LOGIN"); - JsonNode login = awaitStructuredCommand(client, 0, "LOGIN"); - GameplayStructuredCommandAssertions.requireStructuredCommand( - login, "LOGIN", "login", "META", "SESSION"); - assertThat(login.path("accepted").asBoolean()).isFalse(); - assertThat(login.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); - - int baseline = client.responses().size(); - client.send("PLAY demo"); - JsonNode play = awaitStructuredCommand(client, baseline, "PLAY"); - assertThat(play.path("accepted").asBoolean()).isFalse(); - assertThat(play.path("errorCode").asText()).isEqualTo("LOGIN_REQUIRED"); - } - } - - @Test - void websocketFirstPartySayUsesStructuredCommunicationMetadata() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("say-first-party")) { - int baseline = client.responses().size(); - client.send("SAY hello travelers"); - JsonNode say = awaitStructuredCommand(client, baseline, "SAY"); - GameplayStructuredCommandAssertions.requireStructuredCommand( - say, "SAY", "say", "SOCIAL", "COMMUNICATION"); - assertThat(say.path("accepted").asBoolean()).isTrue(); - } - } - - @Test - void websocketFirstPartyConfiguredAuthoredAliasDoesNotBypassAdmittedDefinitions() - throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("authored-first-party")) { - int baseline = client.responses().size(); - client.send("SALUTE captain"); - JsonNode unknown = awaitStructuredCommand(client, baseline, "UNKNOWN"); - assertThat(unknown.path("accepted").asBoolean()).isFalse(); - assertThat(unknown.path("errorCode").asText()).isEqualTo("UNKNOWN_COMMAND"); - } - } - - @Test - void websocketFirstPartyFriendsViewsUseStructuredCanonicalPayloads() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("friends-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS"); - JsonNode friends = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode friendsPayload = requirePayload(friends, "friends_view"); - assertThat(friends.path("accepted").asBoolean()).isTrue(); - assertThat(friendsPayload.path("filter").asText()).isEqualTo("ALL"); - assertThat(friendsPayload.path("friends").get(0).path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); - assertThat(friendsPayload.path("friends").get(0).path("playableStateScope").asText()) - .isEqualTo("SHARED"); - - baseline = client.responses().size(); - client.send("FRIENDS SHOW #1"); - JsonNode detail = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode detailPayload = requirePayload(detail, "friend_detail_view"); - assertThat(detailPayload.path("friend").path("ordinal").asInt()).isEqualTo(1); - assertThat(detailPayload.path("friend").path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); - - baseline = client.responses().size(); - client.send("FRIENDS SUMMARY"); - JsonNode summary = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode summaryPayload = requirePayload(summary, "friend_roster_summary_view"); - assertThat(summaryPayload.path("totalCount").asInt()).isEqualTo(1); - assertThat(summaryPayload.path("onlineCount").asInt()).isEqualTo(1); - assertThat(summaryPayload.path("sharedCount").asInt()).isEqualTo(1); - } - } - - @Test - void websocketFirstPartyFriendsVisibilityUsesStructuredPolicyPayloads() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = - openFirstPartyGameplayClient("friends-visibility-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS VISIBILITY"); - JsonNode visibility = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode visibilityPayload = requirePayload(visibility, "friend_presence_policy_view"); - assertThat(visibilityPayload.path("currentPolicy").asText()).isEqualTo("FRIENDS_ONLY"); - - baseline = client.responses().size(); - client.send("FRIENDS VISIBILITY PRIVATE"); - JsonNode updated = awaitStructuredCommand(client, baseline, "FRIENDS"); - requirePayload(updated, "notice"); - JsonNode updatedPolicy = requirePayload(updated, "friend_presence_policy_view"); - assertThat(updatedPolicy.path("currentPolicy").asText()).isEqualTo("PRIVATE"); - } - - GameplaySocialAssertions.assertGetVisibilityRequest( - socialStub().lastGetVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID)); - GameplaySocialAssertions.assertUpdateVisibilityRequest( - socialStub().lastUpdateVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); - } - - @Test - void websocketFirstPartyFriendsMutationsUseStructuredCanonicalPayloads() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("friends-add-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS ADD 77"); - JsonNode added = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode addPayload = requirePayload(added, "friend_mutation_result"); - assertThat(addPayload.path("action").asText()).isEqualTo("ADD"); - assertThat(addPayload.path("friendAccountId").asLong()).isEqualTo(77L); - assertThat(addPayload.path("displayName").asText()).isEqualTo("Friend #77"); - } - - prepareGameInstance(); - try (GameplayWebSocketDriver client = - openFirstPartyGameplayClient("friends-remove-name-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS REMOVE Sora"); - JsonNode removedByName = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode removeByNamePayload = requirePayload(removedByName, "friend_mutation_result"); - assertThat(removeByNamePayload.path("action").asText()).isEqualTo("REMOVE"); - assertThat(removeByNamePayload.path("friendAccountId").asLong()).isEqualTo(SORA_ACCOUNT_ID); - assertThat(removeByNamePayload.path("displayName").asText()).isEqualTo("Sora"); - assertThat(removeByNamePayload.path("characterName").asText()).isEqualTo("Sora"); - } - - prepareGameInstance(); - try (GameplayWebSocketDriver client = - openFirstPartyGameplayClient("friends-remove-ordinal-first-party")) { - int baseline = client.responses().size(); - client.send("FRIENDS REMOVE #1"); - JsonNode removedByOrdinal = awaitStructuredCommand(client, baseline, "FRIENDS"); - JsonNode removeByOrdinalPayload = requirePayload(removedByOrdinal, "friend_mutation_result"); - assertThat(removeByOrdinalPayload.path("action").asText()).isEqualTo("REMOVE"); - assertThat(removeByOrdinalPayload.path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); - assertThat(removeByOrdinalPayload.path("ordinal").asInt()).isEqualTo(1); - } - } - - @Test - void websocketFirstPartyInventoryViewsExposeTypedItemMetadata() throws Exception { - ensureTestServicesStarted(); - prepareGameInstance(); - - try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("inventory-first-party")) { - int baseline = client.responses().size(); - client.send("GET Torch"); - JsonNode pickup = awaitStructuredCommand(client, baseline, "GET"); - assertThat(pickup.path("accepted").asBoolean()) - .withFailMessage(pickup.toPrettyString()) - .isTrue(); - JsonNode pickupMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(pickupMutation.path("action").asText()).isEqualTo("GET"); - assertThat(pickupMutation.path("item").path("visibleRef").asText()).isEqualTo("torch#1"); - assertThat(pickupMutation.path("source").path("kind").asText()).isEqualTo("ROOM_GROUND"); - assertThat(pickupMutation.path("target").path("kind").asText()).isEqualTo("INVENTORY"); - List pickupViews = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayloads( - client, baseline, "inventory_view", 2); - assertThat(pickupViews).hasSize(2); - JsonNode carriedInventory = requireInventoryViewBySource(pickupViews, "INVENTORY"); - assertThat(carriedInventory.path("entries")).hasSize(3); - JsonNode pickedUpTorch = requireInventoryEntryByVisibleRef(carriedInventory, "torch#1"); - assertThat(pickedUpTorch.path("itemName").asText()).isEqualTo("Torch"); - JsonNode roomGroundInventory = requireInventoryViewBySource(pickupViews, "ROOM_GROUND"); - assertThat(roomGroundInventory.path("entries")).hasSize(1); - assertThat(roomGroundInventory.path("entries").get(0).path("visibleRef").asText()) - .isEqualTo("backpack#1"); - assertThat(roomGroundInventory.path("entries").get(0).path("itemName").asText()) - .isEqualTo("Backpack"); - - baseline = client.responses().size(); - client.send("CONTAINER Backpack"); - JsonNode container = awaitStructuredCommand(client, baseline, "CONTAINER"); - assertThat(container.path("accepted").asBoolean()) - .withFailMessage(container.toPrettyString()) - .isTrue(); - JsonNode containerPayload = requirePayload(container, "inventory_view"); - assertThat(containerPayload.path("source").asText()).isEqualTo("CONTAINER"); - assertThat(containerPayload.path("context").path("displayName").asText()) - .isEqualTo("Backpack"); - assertThat(containerPayload.path("context").path("containerInstanceId").asText()) - .isEqualTo("container-backpack-1"); - assertThat(containerPayload.path("entries")).hasSize(1); - assertThat(containerPayload.path("entries").get(0).path("itemName").asText()) - .isEqualTo("Ration"); - assertThat(containerPayload.path("entries").get(0).path("visibleRef").asText()) - .isEqualTo("ration#1"); - - baseline = client.responses().size(); - client.send("PUT Torch INTO Backpack"); - JsonNode put = awaitStructuredCommand(client, baseline, "PUT"); - assertThat(put.path("accepted").asBoolean()).withFailMessage(put.toPrettyString()).isTrue(); - JsonNode putMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(putMutation.path("action").asText()).isEqualTo("PUT"); - assertThat(putMutation.path("item").path("visibleRef").asText()).isEqualTo("torch#1"); - assertThat(putMutation.path("source").path("kind").asText()).isEqualTo("INVENTORY"); - assertThat(putMutation.path("target").path("kind").asText()).isEqualTo("CONTAINER"); - assertThat(putMutation.path("target").path("containerInstanceId").asText()) - .isEqualTo("container-backpack-1"); - assertThat(putMutation.path("target").path("visibleRef").asText()).isEqualTo("backpack#1"); - - baseline = client.responses().size(); - client.send("TAKE Torch FROM Backpack"); - JsonNode take = awaitStructuredCommand(client, baseline, "TAKE"); - assertThat(take.path("accepted").asBoolean()).withFailMessage(take.toPrettyString()).isTrue(); - JsonNode takeMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(takeMutation.path("action").asText()).isEqualTo("TAKE"); - assertThat(takeMutation.path("item").path("visibleRef").asText()).isEqualTo("torch#1"); - assertThat(takeMutation.path("source").path("kind").asText()).isEqualTo("CONTAINER"); - assertThat(takeMutation.path("source").path("containerInstanceId").asText()) - .isEqualTo("container-backpack-1"); - assertThat(takeMutation.path("source").path("visibleRef").asText()).isEqualTo("backpack#1"); - assertThat(takeMutation.path("target").path("kind").asText()).isEqualTo("INVENTORY"); - - baseline = client.responses().size(); - client.send("DROP Torch"); - JsonNode drop = awaitStructuredCommand(client, baseline, "DROP"); - assertThat(drop.path("accepted").asBoolean()).withFailMessage(drop.toPrettyString()).isTrue(); - JsonNode dropMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(dropMutation.path("action").asText()).isEqualTo("DROP"); - assertThat(dropMutation.path("item").path("visibleRef").asText()).isEqualTo("torch#1"); - assertThat(dropMutation.path("source").path("kind").asText()).isEqualTo("INVENTORY"); - assertThat(dropMutation.path("target").path("kind").asText()).isEqualTo("ROOM_GROUND"); - - baseline = client.responses().size(); - client.send("WEAR Leather Cap"); - JsonNode wear = awaitStructuredCommand(client, baseline, "WEAR"); - assertThat(wear.path("accepted").asBoolean()).withFailMessage(wear.toPrettyString()).isTrue(); - JsonNode wearMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(wearMutation.path("action").asText()).isEqualTo("WEAR"); - assertThat(wearMutation.path("item").path("visibleRef").asText()).isEqualTo("cap#1"); - assertThat(wearMutation.path("source").path("kind").asText()).isEqualTo("INVENTORY"); - assertThat(wearMutation.path("target").path("kind").asText()).isEqualTo("EQUIPMENT"); - assertThat(wearMutation.path("target").path("slot").asText()).isEqualTo("HEAD"); - - baseline = client.responses().size(); - client.send("REMOVE HEAD"); - JsonNode remove = awaitStructuredCommand(client, baseline, "REMOVE"); - assertThat(remove.path("accepted").asBoolean()) - .withFailMessage(remove.toPrettyString()) - .isTrue(); - JsonNode removeMutation = - GameplayStructuredCommandAssertions.awaitFirstPartyPlayerOutputPayload( - client, baseline, "item_mutation_result"); - assertThat(removeMutation.path("action").asText()).isEqualTo("REMOVE"); - assertThat(removeMutation.path("item").path("visibleRef").asText()).isEqualTo("cap#1"); - assertThat(removeMutation.path("source").path("kind").asText()).isEqualTo("EQUIPMENT"); - assertThat(removeMutation.path("source").path("slot").asText()).isEqualTo("HEAD"); - assertThat(removeMutation.path("target").path("kind").asText()).isEqualTo("INVENTORY"); - - baseline = client.responses().size(); - client.send("EQUIPMENT"); - JsonNode equipment = awaitStructuredCommand(client, baseline, "EQUIPMENT"); - assertThat(equipment.path("accepted").asBoolean()) - .withFailMessage(equipment.toPrettyString()) - .isTrue(); - JsonNode equipmentPayload = requirePayload(equipment, "inventory_view"); - assertThat(equipmentPayload.path("source").asText()).isEqualTo("EQUIPMENT"); - assertThat(equipmentPayload.path("entries")).isEmpty(); - } - } - @Test void websocketWhisperPushesTargetAndObserverViewsToLiveRecipients() throws Exception { ensureTestServicesStarted(); @@ -973,8 +644,6 @@ private static synchronized void ensureTestServicesStarted() throws Exception { .mapAccountId("sora@example.com", SORA_ACCOUNT_ID) .withInitialRoomEntities(ChatTestFixtures.sampleEntities()) .withSocialEnabled(true) - .withGameSessionProps( - Map.of("firemud.gateway.connect-context.jwt-secret", FIRST_PARTY_CONNECT_SECRET)) .withInitialFriendPresenceResponse( net.firedevops.firemud.socialgroups.v1.ListFriendPresenceResponse.newBuilder() .addPresences( @@ -1064,103 +733,10 @@ private GameplayWebSocketDriver openReadySessionClient(long sessionId, String pr READY_LOOK_TEXT); } - private GameplayWebSocketDriver openFirstPartyGameplayClient(String transportSessionId) - throws Exception { - GameplayWebSocketDriver client = openFirstPartyClient(transportSessionId); - client.send("LOGIN"); - JsonNode login = awaitStructuredCommand(client, 0, "LOGIN"); - GameplayStructuredCommandAssertions.requireStructuredCommand( - login, "LOGIN", "login", "META", "SESSION"); - assertThat(login.path("accepted").asBoolean()).isFalse(); - assertThat(login.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); - - client.send("LOGIN emberline@example.com swordfish"); - JsonNode credentialLogin = awaitStructuredCommand(client, 1, "LOGIN"); - GameplayStructuredCommandAssertions.requireStructuredCommand( - credentialLogin, "LOGIN", "login", "META", "SESSION"); - assertThat(credentialLogin.path("accepted").asBoolean()) - .withFailMessage(credentialLogin.toPrettyString()) - .isTrue(); - client.send("PLAY demo"); - JsonNode play = awaitStructuredCommand(client, 2, "PLAY"); - GameplayStructuredCommandAssertions.requireStructuredCommand( - play, "PLAY", "play", "META", "SESSION"); - assertThat(play.path("accepted").asBoolean()).withFailMessage(play.toPrettyString()).isTrue(); - int readinessBaseline = client.responses().size(); - client.send("LOOK"); - JsonNode look = awaitStructuredCommand(client, readinessBaseline, "LOOK"); - assertThat(look.path("accepted").asBoolean()).withFailMessage(look.toPrettyString()).isTrue(); - return client; - } - private URI gameSessionWebSocketUrl() { return URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); } - private GameplayWebSocketDriver openFirstPartyClient(String transportSessionId) { - return GameplayWebSocketDriver.connectFirstPartyWeb( - URI.create("ws://localhost:" + gameSession().port() + "/ws/game"), - COMMAND_WAIT, - transportSessionId, - FIRST_PARTY_CONNECT_SECRET, - Long.toString(ACCOUNT_ID), - Map.of( - "accountId", - Long.toString(ACCOUNT_ID), - "tenantId", - Long.toString(TENANT_ID), - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - Long.toString(DEMO_WORLD_INSTANCE_ID), - "pointerVersion", - "1", - "connectScopeId", - "scope-" + transportSessionId, - "connectTokenJti", - "connect-jti-" + transportSessionId, - "connectRequestId", - "connect-req-" + transportSessionId, - "gatewayRequestId", - "gateway-req-" + transportSessionId)); - } - - private JsonNode awaitStructuredCommand( - GameplayWebSocketDriver client, int responseBaseline, String commandType) throws Exception { - return GameplayStructuredCommandAssertions.awaitStructuredCommand( - client, responseBaseline, commandType); - } - - private JsonNode requirePayload(JsonNode envelope, String payloadType) { - return GameplayStructuredCommandAssertions.requirePayload(envelope, payloadType); - } - - private List requirePayloads(JsonNode envelope, String payloadType) { - return GameplayStructuredCommandAssertions.requirePayloads(envelope, payloadType); - } - - private JsonNode requireInventoryViewBySource(List payloads, String source) { - return payloads.stream() - .filter(payload -> source.equals(payload.path("source").asText())) - .findFirst() - .orElseThrow( - () -> - new AssertionError( - "Missing inventory_view source=" + source + " in payloads: " + payloads)); - } - - private JsonNode requireInventoryEntryByVisibleRef(JsonNode inventory, String visibleRef) { - for (JsonNode entry : inventory.path("entries")) { - if (visibleRef.equals(entry.path("visibleRef").asText())) { - return entry; - } - } - throw new AssertionError( - "Missing inventory entry visibleRef=" + visibleRef + " in view: " + inventory); - } - private static CrossServiceAppHarness.GameSessionHolder gameSession() { return STACK.gameSession(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index fb5beab359..519d0b31ba 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -10,8 +10,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; +import java.security.KeyPair; +import java.security.KeyPairGenerator; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -22,6 +24,8 @@ import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.cache.LookCacheService; import net.firedevops.firemud.cache.ScreenBufferService; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamelogic.v1.LookResult; @@ -45,7 +49,6 @@ import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; -import net.firedevops.firemud.gamesession.testsupport.GameplayStructuredCommandAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; import net.firedevops.firemud.gamesession.testsupport.InMemorySessionContextTestConfiguration; @@ -53,6 +56,7 @@ import net.firedevops.firemud.shared.v1.RoomInstanceRef; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.SelectedTargetConnectContextTestVectors; import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; import net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; @@ -68,7 +72,6 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; -import org.springframework.data.redis.core.ValueOperations; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.DynamicPropertyRegistry; @@ -93,7 +96,6 @@ "spring.application.name=game-session-service", "spring.grpc.server.port=0", "spring.flyway.enabled=true", - "firemud.gateway.connect-context.jwt-secret=testsecretkeytestsecretkeytest1234", "firemud.gameplay.catalog.worlds[0].slug=demo", "firemud.gameplay.catalog.worlds[0].display-name=Demo World", "firemud.gameplay.catalog.worlds[0].realms[0].slug=production", @@ -157,8 +159,6 @@ static void registerProperties(DynamicPropertyRegistry registry) { @MockitoBean private RedisTemplate redisTemplate; - @MockitoBean private ValueOperations redisValueOperations; - @MockitoBean private SetOperations redisSetOperations; @Autowired private SessionContextService sessionContextService; @@ -175,40 +175,18 @@ static void registerProperties(DynamicPropertyRegistry registry) { @Autowired private GameplayAdmissionPointerEventRepository gameplayAdmissionPointerEventRepository; - private final ConcurrentMap firstPartyConnectStore = new ConcurrentHashMap<>(); private final ConcurrentMap> redisSetStore = new ConcurrentHashMap<>(); @BeforeEach void setUp() { - firstPartyConnectStore.clear(); redisSetStore.clear(); sessionContextService.deleteBySessionId(22L, 41L); sessionContextService.deleteBySessionId(22L, 42L); sessionContextService.deleteBySessionId(22L, 1L); sessionContextService.deleteBySessionId(22L, 2L); resetAdmissionPointers(); - when(redisTemplate.opsForValue()).thenReturn(redisValueOperations); when(redisTemplate.opsForSet()).thenReturn(redisSetOperations); - when(redisValueOperations.get(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> firstPartyConnectStore.get(invocation.getArgument(0))); - org.mockito.Mockito.doAnswer( - invocation -> { - firstPartyConnectStore.put(invocation.getArgument(0), invocation.getArgument(1)); - return null; - }) - .when(redisValueOperations) - .set( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any(java.time.Duration.class)); - org.mockito.Mockito.doAnswer( - invocation -> { - firstPartyConnectStore.remove(invocation.getArgument(0)); - return null; - }) - .when(redisTemplate) - .delete(org.mockito.ArgumentMatchers.anyString()); when(gameInstanceRepository.save(org.mockito.ArgumentMatchers.any(GameInstance.class))) .thenAnswer(invocation -> invocation.getArgument(0)); org.mockito.Mockito.doAnswer( @@ -790,47 +768,6 @@ void websocketMoveEnqueuesDurableCommandAfterPlay() throws Exception { .hasValueSatisfying(context -> assertThat(context.roomInstanceId()).isEqualTo("R-1021")); } - @Test - void websocketFirstPartyBareLoginFailsClosedWithoutPromotingBootstrapShell() throws Exception { - List payloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - payloads = client.responses(); - } - - JsonNode loginFailure = json(payloads.get(0)); - GameplayStructuredCommandAssertions.requireStructuredCommand( - loginFailure, "LOGIN", "login", "META", "SESSION"); - assertThat(loginFailure.path("accepted").asBoolean()).isFalse(); - assertThat(loginFailure.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); - assertThat(payloads) - .anyMatch( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload, "PLAY", "play", "META", "SESSION") - && !json(payload).path("accepted").asBoolean() - && "LOGIN_REQUIRED".equals(json(payload).path("errorCode").asText())); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)) - .hasValueSatisfying( - context -> { - assertThat(context.accountId()).isZero(); - assertThat(context.gameInstanceId()).isZero(); - assertThat(context.characterId()).isZero(); - assertThat(context.bootstrapGameInstanceId()).isEqualTo(1L); - }); - verify(accountClient, never()) - .getTenantMembershipForRuntime( - org.mockito.ArgumentMatchers.any( - net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); - verify(commandService, never()).enqueue(eq("1"), eq("LOGIN"), eq(false)); - } - @Test void websocketLoginCanBrowseRealmsWhileCharactersFailClosed() throws Exception { List payloads; @@ -874,266 +811,6 @@ void websocketLoginCanBrowseRealmsWhileCharactersFailClosed() throws Exception { org.mockito.ArgumentMatchers.any(PlayableStateScope.class)); } - @Test - void websocketFirstPartyStructuredLobbyBrowseFailsClosedForCharacters() throws Exception { - List payloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "browse-1"))) { - loginFirstPartyWithCredentials(client); - client.send("REALMS demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "REALMS"), "structured REALMS result"); - client.send("CHARS demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "CHARS"), "structured CHARS result"); - payloads = client.responses(); - } - - assertThat(payloads) - .anyMatch( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload, "LOGIN", "login", "META", "SESSION")); - JsonNode realmsResult = - payloads.stream() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .filter( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload.toString(), "REALMS", "realms", "META", "WORLD_BROWSE", "UI")) - .findFirst() - .orElseThrow(); - GameplayStructuredCommandAssertions.requireStructuredCommand( - realmsResult, "REALMS", "realms", "META", "WORLD_BROWSE", "UI"); - assertThat(realmsResult.path("accepted").asBoolean()).isTrue(); - assertThat(realmsResult.path("outputs").get(0).path("payloadType").asText()) - .isEqualTo("realms_view"); - assertThat(realmsResult.path("outputs").get(0).path("payload").path("worldSlug").asText()) - .isEqualTo("demo"); - assertThat(realmsResult.path("outputs").get(0).path("payload").path("realms")).hasSize(1); - assertThat( - realmsResult - .path("outputs") - .get(0) - .path("payload") - .path("realms") - .get(0) - .path("stateScope") - .asText()) - .isEqualTo("SHARED"); - assertThat( - realmsResult - .path("outputs") - .get(0) - .path("payload") - .path("realms") - .get(0) - .path("characterCreationPolicy") - .asText()) - .isEqualTo("ALLOW_NEW"); - - JsonNode charsResult = - payloads.stream() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .filter( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload.toString(), "CHARS", "chars", "META", "WORLD_BROWSE", "UI")) - .findFirst() - .orElseThrow(); - GameplayStructuredCommandAssertions.requireStructuredCommand( - charsResult, "CHARS", "chars", "META", "WORLD_BROWSE", "UI"); - assertThat(charsResult.path("accepted").asBoolean()).isFalse(); - assertThat(charsResult.path("errorCode").asText()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); - verify(entityManagementClient, never()) - .listCharactersByAccount( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(PlayableStateScope.class)); - } - - @Test - void websocketFirstPartyStructuredWhoIncludesActivityState() throws Exception { - List payloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "who-1"))) { - loginFirstPartyWithCredentials(client); - client.send("PLAY demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.send("AFK"); - GameplayAsyncAssertions.assertEventually( - "AFK gameplay presence update", - java.time.Duration.ofSeconds(5), - () -> - gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() - .filter(entry -> entry.sessionId() == 1L) - .findFirst() - .orElseThrow() - .explicitAfkSinceEpochMs() - != null); - client.send("WHO"); - client.awaitMatching(payload -> isStructuredCommand(payload, "WHO"), "structured WHO result"); - payloads = client.responses(); - } - - JsonNode whoResult = - payloads.stream() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .filter( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload.toString(), "WHO", "who", "META", "SOCIAL_PRESENCE", "UI")) - .findFirst() - .orElseThrow(); - GameplayStructuredCommandAssertions.requireStructuredCommand( - whoResult, "WHO", "who", "META", "SOCIAL_PRESENCE", "UI"); - assertThat(whoResult.path("accepted").asBoolean()).isTrue(); - assertThat(whoResult.path("outputs").get(0).path("payloadType").asText()).isEqualTo("who_view"); - assertThat(whoResult.path("outputs").get(0).path("payload").path("players")).hasSize(1); - assertThat( - whoResult - .path("outputs") - .get(0) - .path("payload") - .path("players") - .get(0) - .path("activityState") - .asText()) - .isEqualTo("EXPLICIT_AFK"); - } - - @Test - void websocketFirstPartyFreshPlayDoesNotReplayBufferedScreenAndPerformsFreshLook() - throws Exception { - when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) - .thenReturn( - Optional.of( - new ScreenBufferService.BufferedScreen( - java.util.List.of( - ScreenBufferService.BufferedEntry.fromText("Recent combat line\n"), - ScreenBufferService.BufferedEntry.fromText("Second recent line\n")), - 2, - 2, - 32L))); - - List payloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "2"))) { - loginFirstPartyWithCredentials(client); - client.send("PLAY demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.awaitMatching( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "VIEW"), - "fresh view output"); - client.awaitMatching( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "PROMPT"), - "fresh prompt output"); - payloads = client.responses(); - } - - assertThat( - GameplayStructuredCommandAssertions.isStructuredCommand( - payloads.get(0), "LOGIN", "login", "META", "SESSION")) - .isTrue(); - assertThat(payloads) - .anyMatch( - payload -> - GameplayStructuredCommandAssertions.isStructuredCommand( - payload, "PLAY", "play", "META", "SESSION")); - assertThat(payloads) - .noneMatch( - payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && (payload.contains("Recent combat line") - || payload.contains("Second recent line"))); - assertThat(payloads) - .anyMatch( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "VIEW")); - assertThat(payloads) - .anyMatch( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "PROMPT")); - } - - @Test - void websocketFirstPartyLogoutRetainsReplayStateButSuppressesReplayForFreshReconnect() - throws Exception { - when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) - .thenReturn( - Optional.of( - new ScreenBufferService.BufferedScreen( - java.util.List.of( - ScreenBufferService.BufferedEntry.fromText("First-party replay\n")), - 1, - 1, - 44L))); - - GameplayWebSocketDriver.CloseEvent firstCloseEvent; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "logout-1"))) { - loginFirstPartyWithCredentials(client); - client.send("PLAY demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.send("LOGOUT"); - firstCloseEvent = client.awaitClosed(); - } - - assertThat(firstCloseEvent.reason()).isEqualTo("logout"); - verify(screenBufferService, never()).clear(22L, 1L, 123L); - GameplayAsyncAssertions.assertPresenceCountEventually( - gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(123L))).containsKey(123L); - - java.util.List secondPayloads; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "logout-2"))) { - loginFirstPartyWithCredentials(client); - client.send("PLAY demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.awaitMatching( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "VIEW"), - "fresh view output"); - client.awaitMatching( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "PROMPT"), - "fresh prompt output"); - secondPayloads = client.responses(); - } - - assertThat(secondPayloads).anyMatch(payload -> isStructuredCommand(payload, "LOGIN")); - assertThat(secondPayloads).anyMatch(payload -> isStructuredCommand(payload, "PLAY")); - assertThat(secondPayloads) - .noneMatch( - payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("First-party replay")); - assertThat(secondPayloads) - .anyMatch( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "VIEW")); - assertThat(secondPayloads) - .anyMatch( - payload -> - "player_output".equals(json(payload).path("eventType").asText()) - && containsKind(json(payload), "PROMPT")); - } - @Test void websocketFreshPlayDoesNotReplayBufferedLookFromOldSession() throws Exception { when(screenBufferService.get(eq(22L), eq(41L), eq(123L))) @@ -1281,7 +958,19 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots } @Test - void websocketFirstPartyInvalidConnectContextClosesImmediately() throws Exception { + void websocketFirstPartySignedCompleteContextFailsClosedWithoutMutation() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("Ed25519"); + KeyPair gatewayKeyPair = generator.generateKeyPair(); + java.util.Map contextClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(), + SelectedTargetConnectContextTestVectors.GATEWAY_VERIFIED_AT, + "gateway-request-runtime-disabled"); + String signedContext = + GatewayConnectContextSignature.sign( + new ObjectMapper().writeValueAsBytes(contextClaims), + SelectedTargetConnectContextTestVectors.GATEWAY_KID, + gatewayKeyPair.getPrivate()); GameplayWebSocketDriver.CloseEvent closeEvent; try (GameplayWebSocketDriver client = GameplayWebSocketDriver.connect( @@ -1289,235 +978,15 @@ void websocketFirstPartyInvalidConnectContextClosesImmediately() throws Exceptio java.time.Duration.ofSeconds(10), java.util.Map.of( "X-Firemud-Connection-Mode", "first_party_web", - "X-Firemud-Connect-Context", "not-a-valid-context"))) { + "X-Firemud-Transport-Session-Id", "41", + "X-Firemud-Connect-Context", signedContext))) { closeEvent = client.awaitClosed(); } assertThat(closeEvent.statusCode()).isEqualTo(1008); assertThat(closeEvent.reason()).isEqualTo("CONNECT_CONTEXT_INVALID"); - } - - @Test - void websocketFirstPartyLoginRejectsScopeMismatchAndClosesTransport() throws Exception { - List payloads; - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "mismatch"))) { - bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - closeEvent = client.awaitClosed(); - payloads = client.responses(); - } - - JsonNode loginFailure = json(payloads.get(0)); - GameplayStructuredCommandAssertions.requireStructuredCommand( - loginFailure, "LOGIN", "login", "META", "SESSION"); - assertThat(loginFailure.path("accepted").asBoolean()).isFalse(); - assertThat(loginFailure.path("errorCode").asText()).isEqualTo("CONNECT_SCOPE_MISMATCH"); - assertThat(closeEvent.statusCode()).isEqualTo(1008); - assertThat(closeEvent.reason()).isEqualTo("policy_violation"); - } - - @Test - void websocketFirstPartyLoginRejectsStalePointerAfterCutover() throws Exception { - bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); - - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver client = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "stale-login"))) { - closeEvent = client.awaitClosed(); - } - - assertThat(closeEvent.statusCode()).isEqualTo(1013); - assertThat(closeEvent.reason()).isEqualTo("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE"); - } - - @Test - void websocketFirstPartyReconnectAfterCutoverFailsClosedWithoutLeakingOldGameplayBinding() - throws Exception { - try (GameplayWebSocketDriver first = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "resume-before-cutover"))) { - loginFirstPartyWithCredentials(first); - first.send("PLAY demo"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - first.send("LOOK"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - } - - bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); - - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver reconnecting = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "resume-after-cutover"))) { - closeEvent = reconnecting.awaitClosed(); - } - - assertThat(closeEvent.statusCode()).isEqualTo(1013); - assertThat(closeEvent.reason()).isEqualTo("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE"); - } - - @Test - void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelogin() - throws Exception { - try (GameplayWebSocketDriver first = - openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "route-a"))) { - loginFirstPartyWithCredentials(first); - first.send("PLAY demo"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - first.send("LOOK"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - } - - List payloads; - try (GameplayWebSocketDriver second = - openFirstPartyDriver("2", firstPartyClaims("sandbox", "production", "2", "1", "route-b"))) { - loginFirstPartyWithCredentials(second); - second.send("LOOK"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - second.send("REALMS sandbox"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "REALMS"), "structured REALMS result"); - payloads = second.responses(); - } - - JsonNode loginSuccess = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "LOGIN")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); - - JsonNode lookFailure = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "LOOK")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(lookFailure.path("accepted").asBoolean()).isFalse(); - assertThat(lookFailure.path("errorCode").asText()).isEqualTo("PLAY_REQUIRED"); - - JsonNode realmsSuccess = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "REALMS")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(realmsSuccess.path("accepted").asBoolean()).isTrue(); - assertThat(realmsSuccess.path("outputs").get(0).path("payload").path("worldSlug").asText()) - .isEqualTo("sandbox"); - - assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) - .hasValueSatisfying( - context -> { - assertThat(context.accountId()).isEqualTo(123L); - assertThat(context.gameInstanceId()).isZero(); - assertThat(context.characterId()).isZero(); - assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); - assertThat(context.worldSlug()).isEqualTo("sandbox"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isNull(); - assertThat(context.connectRequestId()).isNull(); - }); - } - - @Test - void websocketFirstPartyPlayRejectsCutoverAfterLogin() throws Exception { - List payloads; - GameplayWebSocketDriver.CloseEvent closeEvent; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "stale-play"))) { - loginFirstPartyWithCredentials(client); - bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); - client.send("PLAY demo"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - closeEvent = client.awaitClosed(); - payloads = client.responses(); - } - - JsonNode loginSuccess = json(payloads.getFirst()); - GameplayStructuredCommandAssertions.requireStructuredCommand( - loginSuccess, "LOGIN", "login", "META", "SESSION"); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); - - JsonNode playFailure = json(payloads.getLast()); - GameplayStructuredCommandAssertions.requireStructuredCommand( - playFailure, "PLAY", "play", "META", "SESSION"); - assertThat(playFailure.path("accepted").asBoolean()).isFalse(); - assertThat(playFailure.path("errorCode").asText()).isEqualTo("CONNECT_SCOPE_MISMATCH"); - assertThat(closeEvent.statusCode()).isEqualTo(1008); - assertThat(closeEvent.reason()).isEqualTo("policy_violation"); - } - - @Test - void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRelogin() - throws Exception { - try (GameplayWebSocketDriver first = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "scope-selector-a"))) { - loginFirstPartyWithCredentials(first); - first.send("PLAY demo"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - first.send("LOOK"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - } - - List payloads; - try (GameplayWebSocketDriver second = - openFirstPartyDriver( - "2", firstPartyClaims("demo", "production", "1", "1", "scope-selector-b"))) { - second.send("LOOK"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - loginFirstPartyWithCredentials(second); - payloads = second.responses(); - } - - JsonNode lookFailure = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "LOOK")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(lookFailure.path("accepted").asBoolean()).isFalse(); - assertThat(lookFailure.path("errorCode").asText()).isEqualTo("LOGIN_REQUIRED"); - - JsonNode loginSuccess = - payloads.stream() - .filter(payload -> isStructuredCommand(payload, "LOGIN")) - .findFirst() - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .orElseThrow(); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); - - assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) - .hasValueSatisfying( - context -> { - assertThat(context.accountId()).isEqualTo(123L); - assertThat(context.gameInstanceId()).isZero(); - assertThat(context.characterId()).isZero(); - assertThat(context.bootstrapGameInstanceId()).isEqualTo(1L); - assertThat(context.worldSlug()).isEqualTo("demo"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isNull(); - assertThat(context.connectRequestId()).isNull(); - }); - assertThat(gameplayPresenceService.findConnectedBySessionId(2L)).isEmpty(); + assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isEmpty(); + assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); } private GameplayWebSocketDriver openGameplayDriver(String sessionId) { @@ -1548,58 +1017,6 @@ private GameplayWebSocketDriver openGameplayDriver( websocketUri(), java.time.Duration.ofSeconds(10), headers); } - private GameplayWebSocketDriver openFirstPartyDriver( - String transportSessionId, java.util.Map connectClaims) { - return GameplayWebSocketDriver.connectFirstPartyWeb( - websocketUri(), - java.time.Duration.ofSeconds(10), - transportSessionId, - "testsecretkeytestsecretkeytest1234", - connectClaims); - } - - private void loginFirstPartyWithCredentials(GameplayWebSocketDriver client) throws Exception { - client.send("LOGIN demo@example.com swordfish"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured credential LOGIN result"); - JsonNode login = - client.responses().stream() - .filter(payload -> isStructuredCommand(payload, "LOGIN")) - .map(GameSessionWebSocketHandlerIntegrationTest::json) - .reduce((first, second) -> second) - .orElseThrow(); - assertThat(login.path("accepted").asBoolean()).isTrue(); - } - - private java.util.Map firstPartyClaims( - String worldSlug, - String realmSlug, - String gameInstanceId, - String pointerVersion, - String suffix) { - return java.util.Map.of( - "accountId", - "123", - "tenantId", - "22", - "worldSlug", - worldSlug, - "realmSlug", - realmSlug, - "gameInstanceId", - gameInstanceId, - "pointerVersion", - pointerVersion, - "connectScopeId", - "scope-" + suffix, - "connectTokenJti", - "connect-jti-" + suffix, - "connectRequestId", - "connect-req-" + suffix, - "gatewayRequestId", - "gateway-req-" + suffix); - } - private WebSocketHttpHeaders gameplayHeaders(String sessionId) { WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); headers.add("X-Game-Instance-Id", "1"); @@ -1693,18 +1110,6 @@ private void resetAdmissionPointers() { null)); } - private static JsonNode json(String payload) { - return GameplayStructuredCommandAssertions.parseStructuredResponse(payload); - } - - private static boolean isStructuredCommand(String payload, String commandType) { - return GameplayStructuredCommandAssertions.isStructuredCommand(payload, commandType); - } - - private static boolean containsKind(JsonNode envelope, String kind) { - return GameplayStructuredCommandAssertions.containsKind(envelope, kind); - } - private static boolean matchesContext( net.firedevops.firemud.gamesession.service.SessionContext context, long tenantId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java index 72d832d5da..5dbc692bec 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java @@ -1,374 +1,86 @@ -package net.firedevops.firemud.gamesession.service; +package unit.net.firedevops.firemud.gamesession.service; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jws; -import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.gamesession.config.FirstPartyConnectContextProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Map; +import net.firedevops.firemud.common.security.GatewayConnectContext; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextService; +import net.firedevops.firemud.test.SelectedTargetConnectContextTestVectors; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class FirstPartyConnectContextServiceTest { - - @Test - void parseRejectsContextWhenVerifierSecretIsNotConfigured() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - JwtUtil jwtUtil = mock(JwtUtil.class); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("signed-context").isEmpty()); - verifyNoInteractions(jwtUtil); - } - - @Test - void parseReadsJwtClaimsThroughInjectedUtil() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isPresent()); - FirstPartyConnectContext context = service.parse("token").orElseThrow(); - assertEquals(42L, context.accountId()); - assertEquals(7L, context.tenantId()); - assertEquals("demo", context.worldSlug()); - assertEquals("production", context.realmSlug()); - assertEquals(9L, context.gameInstanceId()); - assertEquals(17L, context.pointerVersion()); - assertEquals("scope-1", context.connectScopeId()); - assertEquals("jti", context.connectTokenJti()); - assertEquals("request-connect-1", context.connectRequestId()); - assertEquals("request-1", context.gatewayRequestId()); - } - - @Test - void parseRejectsMalformedAccountSubjectClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("bad-number"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsZeroAccountClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("0"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsAccountSubjectMismatch() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("41"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsMalformedTenantClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn("not-a-number"); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsMissingTenantClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(null); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsMissingWorldSlugClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn(""); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + private static final String KID = SelectedTargetConnectContextTestVectors.GATEWAY_KID; + private static final String TENANT_ID = SelectedTargetConnectContextTestVectors.TENANT_ID; + private static final Instant NOW = + Instant.ofEpochSecond(SelectedTargetConnectContextTestVectors.NOW_EPOCH_SECONDS); + + private final ObjectMapper json = new ObjectMapper(); + private KeyPair keyPair; + private Clock clock; + private FirstPartyConnectContextService service; + + @BeforeEach + void setUp() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("Ed25519"); + keyPair = generator.generateKeyPair(); + clock = Clock.fixed(NOW, ZoneOffset.UTC); + service = new FirstPartyConnectContextService(); } @Test - void parseRejectsMissingRealmSlugClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn(""); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + void runtimeParserFailsClosedWithoutPublishedGatewayVerificationKeys() { + assertTrue(service.parse("untrusted-context").isEmpty()); } @Test - void parseRejectsMissingConnectScopeIdClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn(" "); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + void verifiesRealEd25519ContextAndRetainsOriginalEnvelopeAndSelectedTarget() throws Exception { + byte[] payload = json.writeValueAsBytes(validContext()); + String envelope = GatewayConnectContextSignature.sign(payload, KID, keyPair.getPrivate()); + + GatewayConnectContext context = + service.parseVerified(envelope, Map.of(KID, keyPair.getPublic()), clock).orElseThrow(); + + Map source = SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + assertEquals(envelope, context.signedEnvelope()); + assertArrayEquals(payload, context.signedPayload()); + assertEquals("game-session-service", context.text("recipient")); + assertEquals(TENANT_ID, context.text("tenantId")); + assertEquals(source.get("requestId"), context.text("connectRequestId")); + assertEquals(source.get("jti"), context.text("connectTokenJti")); + assertEquals(source.get("iat"), context.integer("issuedAt")); + assertEquals("018f8f0a-4d9e-7c46-be37-8c1d0e9f7a5b", context.text("realmId")); + assertEquals("018f8f0a-5eaf-7d57-9c48-9d2e1f0a8b6c", context.text("playableStateNamespaceId")); + assertEquals("PLAYABLE_STATE_SCOPE_SHARED", context.text("playableStateScope")); + assertEquals( + SelectedTargetConnectContextTestVectors.LARGE_COUNTER, + context.integer("replayAdmissionFence")); } @Test - void parseRejectsMissingConnectRequestIdClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(17L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn(""); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); + void rejectsContextWhenOnlyAnUnknownGatewayKeyIsProvided() throws Exception { + String envelope = + GatewayConnectContextSignature.sign( + json.writeValueAsBytes(validContext()), KID, keyPair.getPrivate()); - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + assertTrue( + service.parseVerified(envelope, Map.of("other-kid", keyPair.getPublic()), clock).isEmpty()); } - @Test - void parseRejectsMissingPointerVersionClaim() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(0L); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); - } - - @Test - void parseRejectsMissingPointerVersionClaimWhenNotPresent() { - FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); - properties.setJwtSecret("secret"); - JwtUtil jwtUtil = mock(JwtUtil.class); - @SuppressWarnings("unchecked") - Jws jws = mock(Jws.class); - Claims claims = mock(Claims.class); - when(jwtUtil.parseToken("token")).thenReturn(jws); - when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); - when(claims.get("tenantId")).thenReturn(7L); - when(claims.get("worldSlug")).thenReturn("demo"); - when(claims.get("realmSlug")).thenReturn("production"); - when(claims.get("gameInstanceId")).thenReturn("9"); - when(claims.get("pointerVersion")).thenReturn(null); - when(claims.get("connectScopeId")).thenReturn("scope-1"); - when(claims.get("connectTokenJti")).thenReturn("jti"); - when(claims.get("connectRequestId")).thenReturn("request-connect-1"); - when(claims.get("gatewayRequestId")).thenReturn("request-1"); - - FirstPartyConnectContextService service = - new FirstPartyConnectContextService(properties, jwtUtil); - - assertTrue(service.parse("token").isEmpty()); + private static Map validContext() { + return GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(), + SelectedTargetConnectContextTestVectors.GATEWAY_VERIFIED_AT, + "gateway-request-42"); } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java index 3a5946fdf7..0697810ea4 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java @@ -10,10 +10,8 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; -import java.time.Instant; import java.util.Arrays; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.common.runtime.RuntimeIdentity; @@ -179,84 +177,22 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { JwtClaims.SignedGameplayRoutingClaims routingClaims = JwtClaims.requireSignedGameplayRoutingClaims( payload, "Connect token account subject mismatch"); - String accountId = Long.toString(routingClaims.accountId()); RoutingBundle routingBundle = parseRuntimeRoutingBundleFromClaims(routingClaims); String tenantId = Long.toString(routingClaims.tenantId()); String gameInstanceId = Long.toString(routingClaims.gameInstanceId()); - String connectScopeId = requiredClaim(payload, "connectScopeId"); - String requestId = requiredClaim(payload, "requestId"); - String jti = requiredClaim(payload, "jti"); - return recordReplayOrReject(jti, payload.getExpiration().getTime()) - .then( - Mono.defer( - () -> { - if (mismatched(exchange, "X-Tenant-Id", tenantId) - || mismatched(exchange, "X-Game-Instance-Id", gameInstanceId) - || mismatchedRoutingBundle(exchange, routingBundle)) { - return reject(exchange, CONNECT_SCOPE_MISMATCH, "connect scope mismatch"); - } - - Instant verifiedAt = Instant.now(); - String connectContext = - jwtUtil.generateToken( - accountId, - Map.ofEntries( - Map.entry("accountId", accountId), - Map.entry("tenantId", tenantId), - Map.entry("worldSlug", routingBundle.worldSlug()), - Map.entry("realmSlug", routingBundle.realmSlug()), - Map.entry("gameInstanceId", gameInstanceId), - Map.entry("pointerVersion", routingBundle.pointerVersion()), - Map.entry("connectScopeId", connectScopeId), - Map.entry("connectTokenJti", jti), - Map.entry("connectRequestId", requestId), - Map.entry("verifiedAt", verifiedAt.toEpochMilli()), - Map.entry("expiresAt", payload.getExpiration().getTime()), - Map.entry("gatewayRequestId", exchange.getRequest().getId()))); - - return chain.filter( - mutate( - exchange, - headers -> { - headers.remove(CONNECT_TOKEN_HEADER); - removeConnectTokenCookie(headers); - headers.remove(HANDSHAKE_ERROR_CLASS_HEADER); - headers.remove(HANDSHAKE_ERROR_REASON_HEADER); - headers.set(CONNECT_CONTEXT_HEADER, connectContext); - headers.set(CONNECTION_MODE_HEADER, CONNECTION_MODE_FIRST_PARTY_WEB); - headers.set( - TRANSPORT_SESSION_HEADER, - Long.toUnsignedString( - stablePositiveLong(exchange.getRequest().getId()))); - headers.set("X-Tenant-Id", tenantId); - headers.set("X-Game-Instance-Id", gameInstanceId); - headers.set(WORLD_SLUG_HEADER, routingBundle.worldSlug()); - headers.set(REALM_SLUG_HEADER, routingBundle.realmSlug()); - headers.set(POINTER_VERSION_HEADER, routingBundle.pointerVersion()); - })); - })) - .onErrorResume( - ReplayRejectedException.class, - ex -> { - return reject(exchange, CONNECT_TOKEN_REPLAYED, "connect token replayed"); - }) - .onErrorResume( - ReplayProtectionUnavailableException.class, - ex -> { - return reject( - exchange, - CONNECT_REPLAY_PROTECTION_UNAVAILABLE, - "connect replay protection unavailable"); - }) - .onErrorResume( - IllegalArgumentException.class, - ex -> { - return reject( - exchange, - CONNECT_TOKEN_REJECTED, - CONNECT_TOKEN_INVALID_CONTENT, - "connect token rejected"); - }); + requiredClaim(payload, "connectScopeId"); + requiredClaim(payload, "requestId"); + requiredClaim(payload, "jti"); + if (mismatched(exchange, "X-Tenant-Id", tenantId) + || mismatched(exchange, "X-Game-Instance-Id", gameInstanceId) + || mismatchedRoutingBundle(exchange, routingBundle)) { + return reject(exchange, CONNECT_SCOPE_MISMATCH, "connect scope mismatch"); + } + + // No independently published Gateway Ed25519 signing key/provider is wired yet. The old + // JwtUtil/HMAC context was not a valid substitute, so valid first-party tokens remain denied + // before replay state is mutated until that owner boundary is available. + return reject(exchange, "POLICY_DENY", "connect context signing keys are unavailable"); } catch (ExpiredJwtException ex) { return reject(exchange, CONNECT_TOKEN_EXPIRED, "connect token expired"); } catch (JwtException ex) { diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java index 71abccd271..391e9ac1c9 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java @@ -1,12 +1,10 @@ package net.firedevops.firemud.springcloudgateway.filter; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import io.jsonwebtoken.Claims; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.net.InetSocketAddress; import java.time.Instant; @@ -421,7 +419,7 @@ void rejectsScopeMismatchWhenRequestHeadersDisagreeWithTokenClaims() { } @Test - void promotesFirstPartyHandshakeWithCookieCarrier() { + void deniesFirstPartyHandshakeUntilGatewayContextSignerIsProvisioned() { GameplayHandshakeFilter filter = new GameplayHandshakeFilter( new JwtUtil(SECRET, 30_000L), @@ -451,18 +449,19 @@ void promotesFirstPartyHandshakeWithCookieCarrier() { .header("Cookie", "duplicate=second") .build(); - ServerWebExchange mutatedExchange = - filterThroughChain(filter, MockServerWebExchange.from(request)); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + filter.filter(exchange, e -> Mono.empty()).block(); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connection-Mode")) - .isEqualTo(GameplayHandshakeFilter.CONNECTION_MODE_FIRST_PARTY_WEB); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Tenant-Id")).isEqualTo("1"); - assertThat(mutatedExchange.getRequest().getHeaders().get("Cookie")) - .containsExactly("session=\"quoted%20value\"; duplicate=first", "duplicate=second"); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) + .isEqualTo("POLICY_DENY"); + assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) + .isNull(); + assertThat(exchange.getRequest().getHeaders().getFirst("X-Firemud-Connect-Context")).isNull(); } @Test - void removesConnectTokenFromMalformedQuotedCookiePair() { + void deniesBeforeMutatingMalformedCookieCarrierWithoutGatewayContextSigner() { GameplayHandshakeFilter filter = new GameplayHandshakeFilter( new JwtUtil(SECRET, 30_000L), @@ -491,11 +490,12 @@ void removesConnectTokenFromMalformedQuotedCookiePair() { .header("Cookie", "unmatched=\"unterminated; Firemud-Connect-Token=shadow") .build(); - ServerWebExchange mutatedExchange = - filterThroughChain(filter, MockServerWebExchange.from(request)); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + filter.filter(exchange, e -> Mono.empty()).block(); - assertThat(mutatedExchange.getRequest().getHeaders().get("Cookie")) - .containsExactly("unmatched=\"unterminated"); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) + .isEqualTo("POLICY_DENY"); } @Test @@ -563,7 +563,7 @@ void rejectsPublicHeaderCarrierOnExactGameplayRouteAsUnsupported() { } @Test - void promotesFirstPartyHandshakeWithValidToken() { + void deniesValidFirstPartyTokenBeforeContextForwardingWithoutGatewaySigner() { GameplayHandshakeFilter filter = new GameplayHandshakeFilter( new JwtUtil(SECRET, 30_000L), @@ -593,63 +593,16 @@ void promotesFirstPartyHandshakeWithValidToken() { .header(GameplayHandshakeFilter.HANDSHAKE_ERROR_REASON_HEADER, "stale-reason") .build(); - ServerWebExchange mutatedExchange = - filterThroughChain(filter, MockServerWebExchange.from(request)); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + filter.filter(exchange, e -> Mono.empty()).block(); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connection-Mode")) - .isEqualTo(GameplayHandshakeFilter.CONNECTION_MODE_FIRST_PARTY_WEB); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.HANDSHAKE_ERROR_CLASS_HEADER)) - .isNull(); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.HANDSHAKE_ERROR_REASON_HEADER)) + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) + .isEqualTo("POLICY_DENY"); + assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) .isNull(); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Tenant-Id")).isEqualTo("1"); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Game-Instance-Id")) - .isEqualTo("42"); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.WORLD_SLUG_HEADER)) - .isEqualTo("demo"); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.REALM_SLUG_HEADER)) - .isEqualTo("production"); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.POINTER_VERSION_HEADER)) - .isEqualTo("18"); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connect-Context")) - .isNotBlank(); - Claims connectContextClaims = - new JwtUtil(SECRET, 30_000L) - .parseToken( - mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connect-Context")) - .getPayload(); - assertThat(connectContextClaims.get("worldSlug")).isEqualTo("demo"); - assertThat(connectContextClaims.get("realmSlug")).isEqualTo("production"); - assertThat(connectContextClaims.get("pointerVersion")).isEqualTo("18"); - assertThat(connectContextClaims.get("connectScopeId")).isEqualTo("scope-2"); - assertThat(connectContextClaims.get("connectRequestId")).isEqualTo("req-2"); - assertThat( - mutatedExchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.TRANSPORT_SESSION_HEADER)) - .matches("\\d+"); - assertThat(mutatedExchange.getRequest().getHeaders().getFirst("Cookie")).isNull(); + assertThat(exchange.getRequest().getHeaders().getFirst("X-Firemud-Connect-Context")).isNull(); + assertThat(exchange.getRequest().getHeaders().getFirst("X-Firemud-Connection-Mode")).isNull(); } @Test @@ -1040,14 +993,11 @@ void rejectsExpiredConnectToken() { } @Test - void rejectsReplayedConnectToken() { + void deniesBeforeReplayMutationUntilGatewayContextSignerIsProvisioned() { ReactiveStringRedisTemplate redisTemplate = mock(ReactiveStringRedisTemplate.class); @SuppressWarnings("unchecked") ReactiveValueOperations valueOps = mock(ReactiveValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOps); - when(valueOps.setIfAbsent( - eq("gateway:connect-token:jti:jti-replay"), eq("1"), any(java.time.Duration.class))) - .thenReturn(Mono.just(true), Mono.just(false)); GameplayHandshakeFilter filter = new GameplayHandshakeFilter( new JwtUtil(SECRET, 30_000L), @@ -1084,13 +1034,17 @@ void rejectsReplayedConnectToken() { filter.filter(first, e -> Mono.empty()).block(); filter.filter(second, e -> Mono.empty()).block(); + assertThat(first.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(second.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(first.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) + .isEqualTo("POLICY_DENY"); assertThat(second.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REPLAYED); + .isEqualTo("POLICY_DENY"); + verifyNoInteractions(redisTemplate, valueOps); } @Test - void rejectsWhenReplayProtectionStorageIsMissingOutsideDevOrTest() { + void deniesBeforeReplayStorageCheckUntilGatewayContextSignerIsProvisioned() { GameplayHandshakeFilter filter = new GameplayHandshakeFilter( new JwtUtil(SECRET, 30_000L), @@ -1123,7 +1077,9 @@ void rejectsWhenReplayProtectionStorageIsMissingOutsideDevOrTest() { assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) - .isEqualTo(GameplayHandshakeFilter.CONNECT_REPLAY_PROTECTION_UNAVAILABLE); + .isEqualTo("POLICY_DENY"); + assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Reason")) + .isNull(); } private ServerWebExchange filterThroughChain(WebFilter filter, ServerWebExchange exchange) { From b7cb7fd2a8a66ee9f479bcc08cd141886a0a7361 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 01:52:20 +1300 Subject: [PATCH 31/46] Keep Account ring receipts stable across exact materialization retry --- .../design-alignment/README.md | 2 +- .../platform-operations-and-delivery.md | 2 +- ...erialize-account-response-envelope-ring.py | 61 +++----- ..._account_response_envelope_materializer.py | 147 +++++++++++------- 4 files changed, 113 insertions(+), 99 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 2c2285fc41..0bb07841a4 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work was rebuilt into #2826 Schema, the dependen | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2881](https://github.com/benhook1013/FireMUD/pull/2881) | Earlier discovery and train pre-review did not complete the section. The tail contains JOIN recovery, retained tenant mapping, durable pair authority, authenticated snapshot preparation, purpose-separated envelopes and one-use exchange storage. Exact #2881 `b2a2f31b0` [CI 36703863842](https://github.com/benhook1013/FireMUD/actions/runs/36703863842) executed 29 JOIN, 9 connect-issuance and 9 bare-LOGIN storage PostgreSQL cases without skips or failures; Account and Game Session jobs passed, while aggregate CI remains red on recorded inherited failures. These are storage/snapshot proofs, not end-to-end credential issuance or live admission. Required Account connect/delegation producers, full authority/consumer proof, fresh Game Design tenant handoff, signed-context convergence, protected ring delivery, durable reconnect, HTTPS/mail/abuse and live browser proof remain open in the [Player Access tracker](../implementation-tracking/player-access-and-session.md). Membership RPC and credential activation stay denied; the ring mount stays unpublished. | +| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2881](https://github.com/benhook1013/FireMUD/pull/2881) → [#2911](https://github.com/benhook1013/FireMUD/pull/2911) | Earlier discovery and train pre-review did not complete the section. The tail contains JOIN recovery, retained tenant mapping, durable pair authority, authenticated snapshot preparation, purpose-separated envelopes and one-use exchange storage. Exact #2881 `b2a2f31b0` [CI 36703863842](https://github.com/benhook1013/FireMUD/actions/runs/36703863842) executed 29 JOIN, 9 connect-issuance and 9 bare-LOGIN storage PostgreSQL cases without skips or failures; Account and Game Session jobs passed, while aggregate CI remains red on recorded inherited failures. These are storage/snapshot proofs, not end-to-end credential issuance or live admission. #2911 converges the complete selected-target contract and shared signed-context component proof while denying obsolete incomplete/HMAC first-party issuance and admission; it does not enable the producer/consumer path. Required Account connect/delegation producers, full authority/consumer proof, fresh Game Design tenant handoff, protected ring delivery, durable reconnect, HTTPS/mail/abuse and live browser proof remain open in the [Player Access tracker](../implementation-tracking/player-access-and-session.md). Membership RPC and credential activation stay denied; the ring mount stays unpublished. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index c7f1cba898..b0970e9d6f 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -225,7 +225,7 @@ These are repository-recorded proofs, not a claim that the tracker consolidation - The accepted [ADR 0058](../../architecture/decisions/adr-0058-class-specific-redis-loss-outcomes.md) Redis-loss contract requires durable intent and class-specific rebuild/terminalization; current preflight and recovery evidence do not establish every class or measured `redis_unreplicated_write_window_slo_ms` value. - [ADR 0057](../../architecture/decisions/adr-0057-game-session-owned-reconciliation-with-isolated-workers.md) assigns isolated Game Session reconciliation workers; [ADR 0068](../../architecture/decisions/adr-0068-evidence-derived-bounded-tick-ledger-recovery.md) defines recovery SLOs; and [ADR 0076](../../architecture/decisions/adr-0076-failure-class-specific-durable-tick-retries.md) defines retry exhaustion and quarantine/disposition paths. Those controls and focused fault-injection proof remain runtime gaps rather than operational claims here. - [ADR 0073](../../architecture/decisions/adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) keeps bootstrap timing formulas separate from measured production safety settings; current operator/configuration surfaces do not yet prove evidence-calibrated values or the complete lease/cleanup health split. -- Account response-envelope ring delivery remains blocked at the authenticated handoff boundary. The local [source bootstrap](../../../dev-tools/deploy/bootstrap-account-response-envelope-ring.py) and [Secret materializer](../../../dev-tools/deploy/materialize-account-response-envelope-ring.py), with focused [materializer tests](../../../dev-tools/tests/test_account_response_envelope_materializer.py), cover protected-source generation/predecessor checks, authenticated Kubernetes username lookup, CAS create/replace, post-write Secret UID/resourceVersion readback, and the distinct typed `account-response-envelope-ring-materialization-v1` receipt. They do not implement or prove an authenticated owner publisher, durable content-addressed source/receipt store, or receipt publish/readback consumer; the local verifier explicitly checks structure and caller-supplied bindings, not transport or publisher authentication, and a Git projection is not that handoff. The current `operation` field also distinguishes `create`/`rotate` from invocation-local `retry`, changing the immutable receipt for the same transition, source generation, and Secret; the eventual channel must use stable transition semantics and exact stored-receipt readback so first-write, lost-ack, and concurrent same-transition retries converge on one tuple/digest without rematerializing or creating a Secret. Any actual Secret UID/resourceVersion change remains an exact mismatch, not a retry. Keep the ring mount unpublished and Account envelope purposes disabled until source custody, sole-writer enforcement, authenticated receipt publication/readback, deployment readback, and separate live freshness/readiness gates are proved. This receipt remains distinct from `jwt-signing-keys-jwks`; do not couple ring activation to JWT/JWKS evidence. +- Account response-envelope ring delivery remains blocked at the authenticated handoff boundary. The local [source bootstrap](../../../dev-tools/deploy/bootstrap-account-response-envelope-ring.py) and [Secret materializer](../../../dev-tools/deploy/materialize-account-response-envelope-ring.py), with focused [materializer tests](../../../dev-tools/tests/test_account_response_envelope_materializer.py), cover protected-source generation/predecessor checks, authenticated Kubernetes username lookup, CAS create/replace, post-write Secret UID/resourceVersion readback, and the distinct typed `account-response-envelope-ring-materialization-v1` receipt. They do not implement or prove an authenticated owner publisher, durable content-addressed source/receipt store, or receipt publish/readback consumer; the local verifier checks structure and caller-supplied bindings, not transport or publisher authentication, and a Git projection is not that handoff. The local receipt operation now identifies only the source transition (`create` for a null predecessor, `rotate` otherwise); invocation-local retry no longer changes canonical receipt bytes/digest, and the strict verifier rejects retry and operation/predecessor mismatch. Focused tests assert create/retry, rotate/retry, and lost-result retry equality with no second Secret write. These equalities apply only to unchanged exact source generation, predecessor, manifest, authenticated materializer, Secret UID/resourceVersion, and freshness annotations; an actual changed readback remains a mismatch, not retry authorization. Keep the ring mount unpublished and Account envelope purposes disabled until source custody, sole-writer enforcement, authenticated receipt publication/readback, deployment readback, and separate live freshness/readiness gates are proved. This receipt remains distinct from `jwt-signing-keys-jwks`; do not couple ring activation to JWT/JWKS evidence. ## To Discuss diff --git a/dev-tools/deploy/materialize-account-response-envelope-ring.py b/dev-tools/deploy/materialize-account-response-envelope-ring.py index 45c1b895ff..e75480b945 100644 --- a/dev-tools/deploy/materialize-account-response-envelope-ring.py +++ b/dev-tools/deploy/materialize-account-response-envelope-ring.py @@ -60,9 +60,7 @@ ) KEY_ID_PATTERN = re.compile(r"[A-Za-z0-9_-]{1,64}\Z") KEY_BYTES_PATTERN = re.compile(rb"[A-Za-z0-9_-]{43}\Z") -RFC3339_UTC_PATTERN = re.compile( - r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z\Z" -) +RFC3339_UTC_PATTERN = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z\Z") KUBERNETES_METADATA_VALUE_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\Z") SERVICE_ACCOUNT_NAME_PATTERN = re.compile( r"[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)*\Z" @@ -205,9 +203,7 @@ def validate_environment_id(value: str) -> str: def validate_namespace(value: str) -> str: - if not isinstance(value, str) or len(value) > 63 or not re.fullmatch( - r"[a-z0-9]([-a-z0-9]*[a-z0-9])?", value - ): + if not isinstance(value, str) or len(value) > 63 or not re.fullmatch(r"[a-z0-9]([-a-z0-9]*[a-z0-9])?", value): raise MaterializationError("target namespace must be a Kubernetes namespace name") return value @@ -316,9 +312,7 @@ def read_source_record(path: Path) -> SourceRecord: raise MaterializationError("source record targetNamespace must be a string") if not isinstance(record["materializerUsername"], str): raise MaterializationError("source record materializerUsername must be a string") - if record["previousSourceGeneration"] is not None and not isinstance( - record["previousSourceGeneration"], str - ): + if record["previousSourceGeneration"] is not None and not isinstance(record["previousSourceGeneration"], str): raise MaterializationError("source record previousSourceGeneration must be a string or null") try: canonical_record = ( @@ -340,9 +334,7 @@ def read_source_record(path: Path) -> SourceRecord: source_generation = validate_source_generation(record["sourceGeneration"]) environment_id = validate_environment_id(record["environmentId"]) target_namespace = validate_namespace(record["targetNamespace"]) - materializer_username = validate_materializer_username( - record["materializerUsername"], target_namespace - ) + materializer_username = validate_materializer_username(record["materializerUsername"], target_namespace) previous_source_generation = record["previousSourceGeneration"] if previous_source_generation is not None: previous_source_generation = validate_source_generation(previous_source_generation) @@ -441,9 +433,7 @@ def _decode_secret_manifest(secret: dict[str, Any], namespace: str) -> tuple[byt return manifest_bytes, metadata -def _load_existing_secret( - secret: dict[str, Any], namespace: str, expected_environment_id: str -) -> ExistingSecret: +def _load_existing_secret(secret: dict[str, Any], namespace: str, expected_environment_id: str) -> ExistingSecret: manifest_bytes, metadata = _decode_secret_manifest(secret, namespace) parsed_manifest = parse_manifest(manifest_bytes) annotations = metadata.get("annotations") @@ -461,9 +451,7 @@ def _load_existing_secret( target_namespace = validate_namespace(annotations[ANNOTATION_TARGET_NAMESPACE]) previous_generation_text = annotations[ANNOTATION_PREVIOUS_SOURCE_GENERATION] previous_generation = ( - None - if previous_generation_text == "" - else validate_source_generation(previous_generation_text) + None if previous_generation_text == "" else validate_source_generation(previous_generation_text) ) if environment_id != expected_environment_id or target_namespace != namespace: raise MaterializationError("existing Secret environment or target namespace is inconsistent") @@ -564,9 +552,7 @@ def _read_secret(kubectl: str, namespace: str) -> dict[str, Any] | None: return secret -def _bounded_expiry( - source_expires_at: dt.datetime, materialized_at: dt.datetime, max_age_seconds: int -) -> dt.datetime: +def _bounded_expiry(source_expires_at: dt.datetime, materialized_at: dt.datetime, max_age_seconds: int) -> dt.datetime: return min(source_expires_at, _class_age_deadline(materialized_at, max_age_seconds)) @@ -712,11 +698,7 @@ def verify_materialization_receipt( raise MaterializationError("materialization receipt version is unsupported") if record["receiptType"] != RECEIPT_TYPE: raise MaterializationError("materialization receipt type is not the Account ring format") - if not isinstance(record["operation"], str) or record["operation"] not in { - "create", - "rotate", - "retry", - }: + if not isinstance(record["operation"], str) or record["operation"] not in {"create", "rotate"}: raise MaterializationError("materialization receipt operation is invalid") source = record["source"] @@ -750,6 +732,9 @@ def verify_materialization_receipt( validate_source_generation(source["predecessorGeneration"]) except (MaterializationError, AttributeError) as exc: raise MaterializationError("materialization receipt source or target binding is invalid") from exc + expected_operation = "create" if source["predecessorGeneration"] is None else "rotate" + if record["operation"] != expected_operation: + raise MaterializationError("materialization receipt operation does not match source predecessor") if not isinstance(source["manifestDigest"], str) or not re.fullmatch( r"sha256:[0-9a-f]{64}", source["manifestDigest"] ): @@ -828,23 +813,19 @@ def verify_materialization_receipt( def _materialization_receipt( *, changed: bool, - operation: str, source: SourceRecord, source_manifest_digest: str, authenticated_materializer_username: str, current: ExistingSecret, ) -> MaterializationReceipt: - if operation not in {"create", "rotate", "retry"}: - raise MaterializationError("materialization receipt operation is invalid") + operation = "create" if source.previous_source_generation is None else "rotate" if current.source_generation != source.source_generation: raise MaterializationError("materialization receipt source generation is inconsistent") if current.previous_source_generation != source.previous_source_generation: raise MaterializationError("materialization receipt predecessor is inconsistent") if current.environment_id != source.environment_id or current.target_namespace != source.target_namespace: raise MaterializationError("materialization receipt environment binding is inconsistent") - freshness_annotations = { - annotation: current.annotations[annotation] for annotation in REQUIRED_ANNOTATIONS - } + freshness_annotations = {annotation: current.annotations[annotation] for annotation in REQUIRED_ANNOTATIONS} record: dict[str, Any] = { "version": RECEIPT_VERSION, "receiptType": RECEIPT_TYPE, @@ -896,9 +877,7 @@ def materialize( raise MaterializationError("source record environment ID does not match the expected environment") if source_record.target_namespace != namespace: raise MaterializationError("source record target namespace does not match the expected namespace") - authenticated_materializer_username = _verify_materializer_identity( - kubectl, source_record.materializer_username - ) + authenticated_materializer_username = _verify_materializer_identity(kubectl, source_record.materializer_username) source_generation = source_record.source_generation source_expires_at = source_record.source_expires_at source_created_at = source_record.source_created_at @@ -934,7 +913,6 @@ def materialize( raise MaterializationError("same source generation has different manifest bytes") return _materialization_receipt( changed=False, - operation="retry", source=source_record, source_manifest_digest=_sha256_digest(source_bytes), authenticated_materializer_username=authenticated_materializer_username, @@ -974,7 +952,15 @@ def materialize( ) expected_annotations = dict(manifest_object["metadata"]["annotations"]) expected_labels = dict(manifest_object["metadata"].get("labels", {})) - write_command = [kubectl, "create" if existing is None else "replace", "--namespace", namespace, "--filename", "-", "--output=json"] + write_command = [ + kubectl, + "create" if existing is None else "replace", + "--namespace", + namespace, + "--filename", + "-", + "--output=json", + ] _run_kubectl(write_command, manifest_object) readback = _read_secret(kubectl, namespace) readback_secret = _verify_readback( @@ -992,7 +978,6 @@ def materialize( ) return _materialization_receipt( changed=True, - operation="create" if existing is None else "rotate", source=source_record, source_manifest_digest=_sha256_digest(source_bytes), authenticated_materializer_username=authenticated_materializer_username, diff --git a/dev-tools/tests/test_account_response_envelope_materializer.py b/dev-tools/tests/test_account_response_envelope_materializer.py index 4a2da5be25..42f4aaaa35 100644 --- a/dev-tools/tests/test_account_response_envelope_materializer.py +++ b/dev-tools/tests/test_account_response_envelope_materializer.py @@ -15,11 +15,7 @@ from types import SimpleNamespace from unittest.mock import patch -SCRIPT_PATH = ( - Path(__file__).resolve().parents[1] - / "deploy" - / "materialize-account-response-envelope-ring.py" -) +SCRIPT_PATH = Path(__file__).resolve().parents[1] / "deploy" / "materialize-account-response-envelope-ring.py" SPEC = importlib.util.spec_from_file_location("account_response_envelope_materializer", SCRIPT_PATH) assert SPEC is not None and SPEC.loader is not None MATERIALIZER = importlib.util.module_from_spec(SPEC) @@ -34,9 +30,7 @@ MAX_AGE_SECONDS = 86_400 ENVIRONMENT_ID = "player-facing-prod" TARGET_NAMESPACE = "account-prod" -MATERIALIZER_USERNAME = ( - "system:serviceaccount:account-prod:firemud-secret-materializer" -) +MATERIALIZER_USERNAME = "system:serviceaccount:account-prod:firemud-secret-materializer" UNSET = object() @@ -88,6 +82,7 @@ def __init__(self) -> None: self.reads = 0 self.mutate_readback = False self.fail_operation: str | None = None + self.lose_response_after_operation: str | None = None self.raise_timeout = False self.raise_unicode_error = False self.identity_username = MATERIALIZER_USERNAME @@ -103,9 +98,7 @@ def __call__(self, command: list[str], **kwargs) -> SimpleNamespace: self.commands.append(operation) self.timeouts.append(kwargs.get("timeout")) if self.raise_timeout: - raise MATERIALIZER.subprocess.TimeoutExpired( - command, kwargs.get("timeout"), output="sensitive output" - ) + raise MATERIALIZER.subprocess.TimeoutExpired(command, kwargs.get("timeout"), output="sensitive output") if self.raise_unicode_error: raise UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid test output") if operation == "auth": @@ -114,9 +107,7 @@ def __call__(self, command: list[str], **kwargs) -> SimpleNamespace: returncode=self.identity_returncode, stdout=self.identity_output if self.identity_output is not None - else json.dumps( - {"status": {"userInfo": {"username": self.identity_username}}} - ), + else json.dumps({"status": {"userInfo": {"username": self.identity_username}}}), stderr="identity provider error", ) self.operations.append(operation) @@ -151,6 +142,13 @@ def __call__(self, command: list[str], **kwargs) -> SimpleNamespace: request_object["metadata"]["uid"] = self.secret["metadata"]["uid"] request_object["metadata"]["resourceVersion"] = resource_version self.secret = request_object + if self.lose_response_after_operation == operation: + self.lose_response_after_operation = None + return SimpleNamespace( + returncode=1, + stdout="", + stderr="connection lost after accepted mutation", + ) if self.mutate_readback: self.secret["data"][MATERIALIZER.SECRET_KEY] = base64.b64encode(b"tampered").decode("ascii") if self.readback_uid is not None: @@ -175,9 +173,7 @@ def setUp(self) -> None: self.previous_generation: str | None = None self.write_source_record() self.fake_kubectl = FakeKubectl() - self.kubectl_patch = patch.object( - MATERIALIZER.subprocess, "run", side_effect=self.fake_kubectl - ) + self.kubectl_patch = patch.object(MATERIALIZER.subprocess, "run", side_effect=self.fake_kubectl) self.kubectl_patch.start() self.addCleanup(self.kubectl_patch.stop) @@ -271,7 +267,9 @@ def test_create_then_exact_retry_preserves_bytes_and_timestamps_without_write(se self.assertEqual(["create"], [operation for operation, _ in self.fake_kubectl.mutations]) self.assertEqual(created, self.fake_kubectl.secret) self.assertEqual("create", created_receipt["operation"]) - self.assertEqual("retry", retry_receipt["operation"]) + self.assertEqual("create", retry_receipt["operation"]) + self.assertEqual(created_receipt.canonical_bytes, retry_receipt.canonical_bytes) + self.assertEqual(created_receipt.content_digest, retry_receipt.content_digest) self.assertEqual( created_receipt["source"]["generation"], retry_receipt["source"]["generation"], @@ -280,6 +278,27 @@ def test_create_then_exact_retry_preserves_bytes_and_timestamps_without_write(se self.assertEqual(created["metadata"]["resourceVersion"], retry_receipt["secret"]["resourceVersion"]) self.assertNotIn(self.source_manifest.decode("ascii"), json.dumps(retry_receipt.as_dict())) + def test_lost_create_result_retry_returns_same_receipt_without_second_write(self) -> None: + expected_kubectl = FakeKubectl() + with patch.object(MATERIALIZER.subprocess, "run", side_effect=expected_kubectl): + expected_receipt = self.run_materializer() + + self.fake_kubectl.lose_response_after_operation = "create" + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "Kubernetes operation failed"): + self.run_materializer() + + self.assertEqual(["create"], [operation for operation, _ in self.fake_kubectl.mutations]) + self.assertIsNotNone(self.fake_kubectl.secret) + lost_result_secret = copy.deepcopy(self.fake_kubectl.secret) + + retry_receipt = self.run_materializer(now=NOW + dt.timedelta(minutes=1)) + + self.assertFalse(retry_receipt) + self.assertEqual(["create"], [operation for operation, _ in self.fake_kubectl.mutations]) + self.assertEqual(lost_result_secret, self.fake_kubectl.secret) + self.assertEqual(expected_receipt.canonical_bytes, retry_receipt.canonical_bytes) + self.assertEqual(expected_receipt.content_digest, retry_receipt.content_digest) + def test_exact_retry_receipt_is_stable_and_canonical_digest_changes_with_a_field(self) -> None: self.run_materializer() first_retry = self.run_materializer(now=NOW + dt.timedelta(minutes=1)) @@ -324,9 +343,7 @@ def verify_receipt(self, receipt_bytes: bytes, **expected_overrides) -> dict: @staticmethod def canonical_receipt(record: dict) -> bytes: record["immutableArtifactId"] = MATERIALIZER.canonical_evidence_digest(record) - return ( - json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" - ).encode("utf-8") + return (json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") def test_read_side_receipt_verifier_accepts_exact_canonical_receipt(self) -> None: receipt = self.run_materializer() @@ -349,19 +366,43 @@ def test_read_side_receipt_verifier_rejects_duplicate_wrong_shape_and_jwt_shape( jwt_shape, ) for evidence in malformed: - with self.subTest(evidence=evidence[:48]), self.assertRaises( - MATERIALIZER.MaterializationError - ): + with self.subTest(evidence=evidence[:48]), self.assertRaises(MATERIALIZER.MaterializationError): self.verify_receipt(evidence) + def test_read_side_receipt_verifier_rejects_retry_and_operation_predecessor_mismatch(self) -> None: + created_receipt = self.run_materializer() + retry_shape = created_receipt.as_dict() + retry_shape["operation"] = "retry" + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "operation is invalid"): + self.verify_receipt(self.canonical_receipt(retry_shape)) + + wrong_create_operation = created_receipt.as_dict() + wrong_create_operation["operation"] = "rotate" + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "operation does not match source predecessor"): + self.verify_receipt(self.canonical_receipt(wrong_create_operation)) + + self.write_source_record( + manifest=manifest_for(active="k2", ids=("k1", "k2")), + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + rotated_receipt = self.run_materializer(now=NOW + dt.timedelta(hours=2)) + wrong_rotate_operation = rotated_receipt.as_dict() + wrong_rotate_operation["operation"] = "create" + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "operation does not match source predecessor"): + self.verify_receipt( + self.canonical_receipt(wrong_rotate_operation), + expected_source_generation="custody-generation-2", + expected_predecessor_generation="custody-generation-1", + ) + def test_read_side_receipt_verifier_rejects_tampered_digest_and_noncanonical_bytes(self) -> None: receipt = self.run_materializer() tampered = receipt.as_dict() tampered["secret"]["resourceVersion"] = "999" with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "digest does not match"): - self.verify_receipt( - json.dumps(tampered, sort_keys=True, separators=(",", ":")).encode("utf-8") - ) + self.verify_receipt(json.dumps(tampered, sort_keys=True, separators=(",", ":")).encode("utf-8")) with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "not canonical"): self.verify_receipt(receipt.canonical_bytes + b" ") @@ -424,9 +465,7 @@ def test_read_side_receipt_verifier_rejects_matching_malformed_expected_bindings lambda changed, value: ( changed.update(targetNamespace=value), changed["secret"].update(namespace=value), - changed["freshnessAnnotations"].update( - {MATERIALIZER.ANNOTATION_TARGET_NAMESPACE: value} - ), + changed["freshnessAnnotations"].update({MATERIALIZER.ANNOTATION_TARGET_NAMESPACE: value}), ), ), ( @@ -435,9 +474,7 @@ def test_read_side_receipt_verifier_rejects_matching_malformed_expected_bindings "predecessor\ninvalid", lambda changed, value: ( changed["source"].update(predecessorGeneration=value), - changed["freshnessAnnotations"].update( - {MATERIALIZER.ANNOTATION_PREVIOUS_SOURCE_GENERATION: value} - ), + changed["freshnessAnnotations"].update({MATERIALIZER.ANNOTATION_PREVIOUS_SOURCE_GENERATION: value}), ), ), ) @@ -513,9 +550,7 @@ def test_rotation_rejects_secret_identity_or_resource_version_mismatch_after_wri self.fake_kubectl.attempts.clear() self.fake_kubectl.readback_resource_version = prior_resource_version - with self.assertRaisesRegex( - MATERIALIZER.MaterializationError, "resource version did not advance" - ): + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "resource version did not advance"): self.run_materializer(now=NOW + dt.timedelta(hours=2)) self.assertEqual(prior_uid, self.fake_kubectl.uid) @@ -552,14 +587,10 @@ def test_wrong_target_namespace_record_is_rejected_before_kubernetes_access(self def test_malformed_bound_materializer_username_is_rejected_before_kubernetes_access(self) -> None: self.write_source_record( - materializer_username=( - "system:serviceaccount:account-preview:firemud-secret-materializer" - ) + materializer_username=("system:serviceaccount:account-preview:firemud-secret-materializer") ) - with self.assertRaisesRegex( - MATERIALIZER.MaterializationError, "service-account username" - ): + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "service-account username"): self.run_materializer() self.assertEqual([], self.fake_kubectl.commands) @@ -598,9 +629,7 @@ def test_missing_malformed_or_failed_whoami_fails_before_secret_access(self) -> self.fake_kubectl.identity_output = response self.fake_kubectl.identity_returncode = returncode - with self.assertRaisesRegex( - MATERIALIZER.MaterializationError, expected_message - ): + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, expected_message): self.run_materializer() self.assertEqual(["auth"], self.fake_kubectl.commands) @@ -701,7 +730,10 @@ def test_rotation_uses_resource_version_and_retains_prior_ids_and_material(self) replacement = self.fake_kubectl.mutations[-1][1] self.assertEqual(previous["metadata"]["resourceVersion"], replacement["metadata"]["resourceVersion"]) self.assertEqual({"k1", "k2"}, MATERIALIZER.parse_manifest(self.source_manifest).key_ids) - self.assertEqual("custody-generation-2", self.fake_kubectl.secret["metadata"]["annotations"][MATERIALIZER.ANNOTATION_SOURCE_GENERATION]) + self.assertEqual( + "custody-generation-2", + self.fake_kubectl.secret["metadata"]["annotations"][MATERIALIZER.ANNOTATION_SOURCE_GENERATION], + ) self.assertEqual("rotate", rotation_receipt["operation"]) self.assertEqual("custody-generation-1", rotation_receipt["source"]["predecessorGeneration"]) self.assertEqual(self.fake_kubectl.secret["metadata"]["uid"], rotation_receipt["secret"]["uid"]) @@ -713,7 +745,9 @@ def test_rotation_uses_resource_version_and_retains_prior_ids_and_material(self) retry_receipt = self.run_materializer(now=NOW + dt.timedelta(hours=3)) self.assertFalse(retry_receipt) - self.assertEqual("retry", retry_receipt["operation"]) + self.assertEqual("rotate", retry_receipt["operation"]) + self.assertEqual(rotation_receipt.canonical_bytes, retry_receipt.canonical_bytes) + self.assertEqual(rotation_receipt.content_digest, retry_receipt.content_digest) self.assertEqual(2, len(self.fake_kubectl.mutations)) self.assertEqual(rotated, self.fake_kubectl.secret) @@ -770,7 +804,9 @@ def test_rotation_cannot_change_retained_key_bytes(self) -> None: def test_same_generation_metadata_mismatch_fails_closed(self) -> None: self.run_materializer() - self.fake_kubectl.secret["metadata"]["annotations"][MATERIALIZER.ANNOTATION_MATERIALIZED_AT] = "2026-09-27T10:00:00Z" + self.fake_kubectl.secret["metadata"]["annotations"][MATERIALIZER.ANNOTATION_MATERIALIZED_AT] = ( + "2026-09-27T10:00:00Z" + ) with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "freshness metadata"): self.run_materializer() @@ -798,9 +834,7 @@ def test_failed_create_does_not_delete_retry_or_change_source_bytes(self) -> Non self.assertEqual(["get", "create"], self.fake_kubectl.operations) self.assertNotIn("delete", self.fake_kubectl.operations) self.assertEqual(1, len(self.fake_kubectl.attempts)) - attempted_manifest = base64.b64decode( - self.fake_kubectl.attempts[0][1]["data"][MATERIALIZER.SECRET_KEY] - ) + attempted_manifest = base64.b64decode(self.fake_kubectl.attempts[0][1]["data"][MATERIALIZER.SECRET_KEY]) self.assertEqual(self.source_manifest, attempted_manifest) self.assertEqual(source_record_bytes, self.source_path.read_bytes()) @@ -821,9 +855,7 @@ def test_failed_replace_does_not_delete_retry_or_change_source_bytes(self) -> No self.assertEqual(["get", "create", "get", "get", "replace"], self.fake_kubectl.operations) self.assertNotIn("delete", self.fake_kubectl.operations) self.assertEqual(["create", "replace"], [operation for operation, _ in self.fake_kubectl.attempts]) - attempted_manifest = base64.b64decode( - self.fake_kubectl.attempts[-1][1]["data"][MATERIALIZER.SECRET_KEY] - ) + attempted_manifest = base64.b64decode(self.fake_kubectl.attempts[-1][1]["data"][MATERIALIZER.SECRET_KEY]) self.assertEqual(replacement_bytes, attempted_manifest) self.assertEqual(replacement_bytes, self.source_manifest) @@ -862,9 +894,7 @@ def test_missing_source_fails_before_kubernetes_access(self) -> None: def test_source_record_rejects_duplicate_metadata_fields(self) -> None: encoded_manifest = base64.b64encode(self.source_manifest).decode("ascii") raw_record = ( - '{"version":1,"manifestBase64":"' - + encoded_manifest - + '","sourceGeneration":"custody-generation-1",' + '{"version":1,"manifestBase64":"' + encoded_manifest + '","sourceGeneration":"custody-generation-1",' '"sourceGeneration":"custody-generation-2",' '"environmentId":"player-facing-prod",' '"targetNamespace":"account-prod",' @@ -892,8 +922,7 @@ def test_source_record_rejects_contradictory_version(self) -> None: "previousSourceGeneration": self.previous_generation, } raw_record = ( - json.dumps(source_record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) - + "\n" + json.dumps(source_record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" ).encode("utf-8") self.write_source_record(raw=raw_record) From 9800f26ec43d18a3c51c5effbf12fb66c5c4d5c9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 02:19:21 +1300 Subject: [PATCH 32/46] Restore shared presence fixtures and prove exact source-context correspondence --- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 12 +- .../security/GatewayConnectContextCodec.java | 47 ++++++ .../GatewayConnectContextCodecTest.java | 140 ++++++++++++++++++ ...essionWebSocketHandlerIntegrationTest.java | 22 +++ 5 files changed, 220 insertions(+), 6 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 7bd20f9d59..76086ba037 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -151,3 +151,8 @@ Entry format: - Context: a #2881 push yielded asynchronously and later returned a generic remote rejection. Dependent PR-body and CI operations were issued before consuming that result, so CI run `36703184951` targeted the old published head instead of the prepared correction. - Observation: the rejection's cause was not reported. Fresh remote readback confirmed no head change; a non-force retry then published the correction. The stale-head run was explicitly cancelled and excluded from proof. - Expected pattern: finish the push, verify the exact published SHA, and only then describe it as published or dispatch its CI. Independent operations may run concurrently; operations depending on publication must remain ordered even when tool calls yield. + +- `2026-10-01`: Fixture names do not establish exclusive ownership + - Context: #2911 removed unreachable legacy HMAC first-party success fixtures. A Redis value store named for first-party context also served normal gameplay presence; its mock/stubs were removed with the obsolete cases. + - Observation: local Docker-backed integration cases skipped, so compilation and module checks did not expose the lost shared support. Exact-head CI ran the cases and all 16 WebSocket scenarios failed at a null value-operations collaborator, before the intended assertions. The fixture support was restored without restoring HMAC admission; executed correction proof remains required. + - Expected pattern: trace every consumer of a shared fixture before removing it, use neutral names for shared support, and preserve an exact executed integration gate when cleanup affects skipped local tests. A green compiled/skipped gate is not proof that fixture dependencies were retained. 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 236294f062..38abd6693f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,7 +24,7 @@ Account runtime admission reads remain a capability/proof blocker. `GetTenantMem The #2876 draft adds Account V31 durable issuer, Account UUID, tenant UUID, and membership generations plus an account-local issuance fence. New global registration initializes its persisted Account UUID pair; startup enrolls the exact issuer; approved retained-tenant association enrolls the canonical tenant generation; V34 enrolls retained Account UUID pairs without resetting advanced values and aborts on a half-pair. V33 adds immutable independently sequenced authority events and a shared strict `account-auth-authority-event/v1` Account/Game Session codec with executed positive/negative, ordering, and large-counter vectors. The first-JOIN candidate composes approved retained tenant UUID, V31 membership generation/fence, version-bound roles, V33 event, receipt, audit, and terminal operation in one Account transaction. Replay and abandoned-`PENDING` reconciliation require exact event readback; retained inactive reactivation remains fail-closed without a canonical INACTIVE writer/event. V35 and V36 migrated in hosted PostgreSQL CI; all four V36 repository cases passed in the earlier run, while two V35 timestamp-bind and two JOIN transaction-diagnostic cases failed among 80 Account integration cases. The corrected exact-head Account job subsequently ran `:account-service:integrationTest` and passed, but its success artifact did not include per-test XML, so exact case and skip counts cannot be independently read back for that run; local Docker remains unavailable. Event delivery, Redis projections, Account runtime response, Game Session consumer, fresh-tenant UUID handoff, mixed-version issuer cutover, and complete token issuance remain open. No issued token or runtime response consumes the new state; the membership RPC stays denied and Unit 1B remains provisional. -The same draft now includes a bounded Ed25519 compact-JWS signing and verification primitive for the dedicated Gateway connect-context key namespace. It is not wired to Gateway issuance, Game Session or Account verification, key publication/rotation, or the complete context-field checks; the current HMAC context path remains partial implementation drift. The primitive's local unit proof is not a signed-context handoff or gameplay admission proof. +The tail now includes the shared Ed25519 compact-JWS primitive and #2911's complete-context component codec for the dedicated Gateway key namespace. The codec preserves exact signed envelope/payload bytes and checks registered receiver, target, lifecycle, authority-map and timestamp shapes; a separate original-source comparison checks Account-to-Gateway correspondence, not current authority or authorization. Gateway runtime issuance and Game Session runtime parsing remain denied: no HMAC/default-key fallback is accepted. Independent key publication/rotation, complete Account issuance/readback and authenticated producer/consumer wiring remain open. Local component proof is not a working signed-context handoff or gameplay admission proof. Account V32 holds version-bound tenant-role snapshots without backfilling retained memberships. First explicit public JOIN writes `player` with the membership and audit transaction; active membership and abandoned-`PENDING` reconciliation require exact current role and authority-event readback. The earlier reactivation role-update code is not a proved capability: it now fails closed before mutation unless a canonical current INACTIVE event exists, and no such writer is implemented. Prior CI executed 12 PostgreSQL JOIN cases and V32 migration; the corrected-head Account integration task passed, though its success artifact lacks per-test XML for exact method-level counts. Account runtime snapshot and Game Session consumption remain open. @@ -32,9 +32,9 @@ The in-progress #2873 tenant bridge now has a signed Game Design migration-manif The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. -The canonical Account-signed selected-target `gameplay-connect` profile and Gateway assertion require Account-resolved `realmId`, `playableStateNamespaceId`, `playableStateScope`, the exact selected-target authority evidence, and the conditional non-public lifecycle/generation pair. The latest local source checkpoint adds an Account fail-closed guard against cached or fresh connect success without complete evidence, a Gateway guard that rejects first-party context creation before replay-marker mutation when independent Ed25519 signing keys are unavailable, and a shared full-context codec with vectors; Game Session runtime parsing remains denied until key publication, canonical UUID mapping, and a real Account exchange/source-evidence proof are available. These guards and codec are not a live complete producer/consumer or admission path, and this local code checkpoint has not been validated here. Durable issuance, key publication/rotation, Gateway assertion mapping, Game Session consumption, and negative-proof coverage remain open. No `IssueConnectToken` RPC or changed credential-granting path is active under this target contract until the complete producer/consumer proof passes. +The canonical Account-signed selected-target `gameplay-connect` profile and Gateway assertion remain owned by [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema). #2911 adds the fail-closed Account/Gateway guards and shared [context codec](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java) with [signed vectors and source-correspondence tests](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java). Local affected-module checks passed; most Docker-backed cases skipped. Initial exact-head CI passed Account/Gateway but exposed a shared Redis fixture regression in 16 Game Session integration cases; its fixture restoration still requires executed correction proof. Game Session runtime parsing remains denied until key publication, canonical UUID mapping and real Account exchange/source-evidence proof are available. These components are not a live complete producer/consumer or admission path. Durable issuance, key publication/rotation, Account signature verification, current-authority comparison, runtime consumer wiring and complete negative-proof coverage remain open. No credential-granting path is activated by this checkpoint. -Separately, hosted CI run `36703863842` on committed `b2a2f31b02e7ad48b0d42a9da7cf7b3acec2782e` executed 29 JOIN, 9 V35, and 9 V37 PostgreSQL cases; the Account and Game Session jobs passed, while the aggregate workflow remained red from inherited failures. These are storage/integration results on the committed head, not validation of the subsequent uncommitted connect-context guards/codec or proof of the complete credential producer/consumer path. +Separately, hosted CI run `36703863842` on committed #2881 `b2a2f31b02e7ad48b0d42a9da7cf7b3acec2782e` executed 29 JOIN, 9 V35, and 9 V37 PostgreSQL cases; the Account and Game Session jobs passed, while the aggregate workflow remained red from inherited failures. These are exact-parent storage/integration results, not validation of #2911's new context path or proof of the complete credential producer/consumer flow. The approved first-party bare-`LOGIN` private-delegation exchange is not live. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases passed in CI run `36289042648` on prior #2881 head `25626210c` and skipped locally without Docker; caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. A forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. @@ -85,9 +85,9 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | --- | --- | --- | | Incorrect currently reachable Game Session behavior | Unit 1B #2857 | This draft removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests run; composed validation below remains red and the correction is not merge-ready. | | Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | -| First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | The hosted values do not supply Game Session's dedicated context-verifier secret; an unset secret makes the current parser reject before using claims. Gateway currently signs with its generic auth JWT utility, while the consumer does not yet enforce the complete target audience, recipient, lifetime, authority tuple, realm/namespace and claim-equality schema. The current Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, provision and prove matching protected signing/verification material, complete producer/consumer schema and negative predicates, and execute a hosted handshake through admission; a signed partial context or local Compose key match is not proof. | -| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | -| Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after logout, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | +| First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | #2911 supplies the complete shared verification/source-correspondence component but denies Gateway runtime signing and Game Session runtime parsing pending independent protected key publication and complete Account source/exchange proof. The obsolete shared-HMAC path is removed, not an unset-secret activation option. Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, prove matching purpose-specific protected material, complete producer/consumer negative predicates and an executed handshake through admission; component vectors are not that end-to-end proof. | +| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | #2911 refuses cached incomplete success and fresh incomplete issuance with transient `AUTH_UNAVAILABLE`; it does not mint or extend a credential. The target exact-retry path must recover the original durable issuance/result without reminting and separately prove its current-authority and ambiguous-ack rules. The guard does not supply the missing immutable selected-target baseline or establish current authorization. | +| Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | The first-party path is denied, so historical HMAC fresh-`PLAY` fixtures do not prove reachable logout/replay behavior. Durable terminal `resumeContextGeneration` fencing, a measured disconnected-resume horizon and namespace-scoped atomic takeover/old-input fencing remain open. Disabled Account admission reads contain new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | | Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Exact code-head CI run `36006632988` executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green; all 27 WebSocket integration cases passed, clearing the seven #2857-owned failures from the preceding run. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures repeated and block the full Validation Gate. This executed proof does not activate typed Account admission or the remaining successor contracts. | diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java index 2a07401c0e..1b1a3728ce 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java @@ -158,6 +158,53 @@ public static Map projectVerifiedAccountGameplayConnectClaims( return immutableObject(context); } + /** + * Requires exact correspondence between already-verified Account gameplay-connect claims and an + * already signature-verified immutable Gateway context. This is only an original-assertion + * correspondence check: callers must verify the Account JWT signature/profile before passing its + * claims, and must separately enforce current time, current Account authority, durable operation, + * and retry/recovery policy. This method neither verifies a JWT nor grants Account authorization. + * + *

The Account claim map is copied and validated at the Gateway context's original {@code + * verifiedAt}; neither input is normalized in place. Gateway may choose an earlier {@code + * expiresAt} than the maximum source-bounded deadline, but may not extend it. + */ + public static void requireVerifiedAccountSourceMatchesGatewayContext( + Map verifiedSourceClaims, GatewayConnectContext verifiedGatewayContext) { + if (verifiedGatewayContext == null) { + throw invalid("verified Gateway context is required"); + } + + Map context = verifiedGatewayContext.claims(); + BigInteger verifiedAt = requirePositiveInteger(context, "verifiedAt"); + long gatewayVerifiedAt; + try { + gatewayVerifiedAt = verifiedAt.longValueExact(); + Instant originalVerificationTime = Instant.ofEpochSecond(gatewayVerifiedAt); + validate(context, originalVerificationTime); + Map expected = + new LinkedHashMap<>( + projectVerifiedAccountGameplayConnectClaims( + verifiedSourceClaims, + gatewayVerifiedAt, + requireText(context, "gatewayRequestId"))); + + BigInteger latestPermittedExpiry = requirePositiveInteger(expected, "expiresAt"); + if (requirePositiveInteger(context, "expiresAt").compareTo(latestPermittedExpiry) > 0) { + throw invalid("Gateway context expiry extends beyond the Account source token"); + } + // Compare the complete registered projection, not a second field allowlist that could miss + // a future source-carried field. Only the independently shortened Gateway deadline differs. + expected.put("expiresAt", context.get("expiresAt")); + if (!expected.equals(context)) { + throw invalid("Gateway context does not exactly preserve the Account source evidence"); + } + } catch (ArithmeticException | java.time.DateTimeException ex) { + throw invalid( + "Gateway context verification time is outside the supported epoch-second range"); + } + } + /** * Verifies a compact Gateway Ed25519 JWS, then validates its complete semantic schema and time * window. Expiration has no skew grace: skew cannot extend the signed lifetime. diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java index 35fa22b348..4611b393cf 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java @@ -334,6 +334,137 @@ void projectsSourceExpiryWithoutExtendingItAndDoesNotMutateVerifiedClaims() thro assertThrows(IllegalArgumentException.class, () -> projectContext(unknownSourceClaim)); } + @Test + void matchesPublicAndPrivateSourceExactlyAndAllowsShorterGatewayExpiry() throws Exception { + Map publicSource = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + String publicSourceBefore = json.writeValueAsString(publicSource); + Map publicPayload = projectContext(publicSource); + publicPayload.put( + "expiresAt", + BigInteger.valueOf(SelectedTargetConnectContextTestVectors.SOURCE_ISSUED_AT + 20L)); + String publicEnvelope = sign(publicPayload); + GatewayConnectContext publicContext = verify(publicEnvelope); + String publicClaimsBefore = json.writeValueAsString(publicContext.claims()); + byte[] publicSignedPayloadBefore = publicContext.signedPayload(); + + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesGatewayContext( + publicSource, publicContext); + + assertEquals(publicSourceBefore, json.writeValueAsString(publicSource)); + assertEquals(publicEnvelope, publicContext.signedEnvelope()); + assertEquals(publicClaimsBefore, json.writeValueAsString(publicContext.claims())); + assertArrayEquals(publicSignedPayloadBefore, publicContext.signedPayload()); + assertEquals( + SelectedTargetConnectContextTestVectors.SOURCE_ISSUED_AT + 20L, + publicContext.integer("expiresAt").longValueExact()); + + Map privateSource = + SelectedTargetConnectContextTestVectors.privateSourceConnectTokenClaims(); + String privateSourceBefore = json.writeValueAsString(privateSource); + Map privatePayload = projectContext(privateSource); + GatewayConnectContext privateContext = verify(sign(privatePayload)); + + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesGatewayContext( + privateSource, privateContext); + + assertEquals(privateSourceBefore, json.writeValueAsString(privateSource)); + assertEquals(privatePayload, privateContext.claims()); + } + + @Test + void rejectsChangedAccountTargetAuthorityMapsCountersLifecycleAndMappedClaims() throws Exception { + Map publicSource = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + GatewayConnectContext publicContext = verify(sign(projectContext(publicSource))); + + Map changedTarget = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + changedTarget.put("realmId", "018f8f0a-8c1d-7f9a-ad6a-bf4a312c0d8e"); + assertSourceMismatch(changedTarget, publicContext); + + Map changedMembershipMap = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + changedMembershipMap.put( + "membershipVersion", + Map.of( + SelectedTargetConnectContextTestVectors.TENANT_ID, + SelectedTargetConnectContextTestVectors.LARGE_COUNTER.add(BigInteger.ONE))); + assertSourceMismatch(changedMembershipMap, publicContext); + + Map changedAuthorityCounter = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + @SuppressWarnings("unchecked") + Map changedAuthorityTuple = + new LinkedHashMap<>((Map) changedAuthorityCounter.get("authorityTuple")); + changedAuthorityTuple.put( + "membershipAuthorityGeneration", + Map.of( + SelectedTargetConnectContextTestVectors.TENANT_ID, + SelectedTargetConnectContextTestVectors.LARGE_COUNTER.add(BigInteger.ONE))); + changedAuthorityCounter.put("authorityTuple", changedAuthorityTuple); + assertSourceMismatch(changedAuthorityCounter, publicContext); + + Map changedRequestId = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + changedRequestId.put("requestId", "another-connect-request"); + assertSourceMismatch(changedRequestId, publicContext); + + Map changedJti = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + changedJti.put("jti", "another-connect-token-jti"); + assertSourceMismatch(changedJti, publicContext); + + Map changedIssuedAt = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + changedIssuedAt.put( + "iat", BigInteger.valueOf(SelectedTargetConnectContextTestVectors.SOURCE_ISSUED_AT + 1L)); + changedIssuedAt.put( + "exp", BigInteger.valueOf(SelectedTargetConnectContextTestVectors.SOURCE_ISSUED_AT + 31L)); + assertSourceMismatch(changedIssuedAt, publicContext); + + Map privateSource = + SelectedTargetConnectContextTestVectors.privateSourceConnectTokenClaims(); + GatewayConnectContext privateContext = verify(sign(projectContext(privateSource))); + + Map changedLifecycle = + SelectedTargetConnectContextTestVectors.privateSourceConnectTokenClaims(); + String newLifecycle = "018f8f0a-8c1d-7f9a-ad6a-bf4a312c0d8e"; + changedLifecycle.put("playtestLifecycleId", newLifecycle); + @SuppressWarnings("unchecked") + Map lifecycleTuple = + new LinkedHashMap<>((Map) changedLifecycle.get("authorityTuple")); + @SuppressWarnings("unchecked") + List> originalGrants = + (List>) lifecycleTuple.get("privateRealmGrantVersions"); + Map changedGrant = new LinkedHashMap<>(originalGrants.getFirst()); + changedGrant.put("playtestLifecycleId", newLifecycle); + lifecycleTuple.put("privateRealmGrantVersions", List.of(changedGrant)); + changedLifecycle.put("authorityTuple", lifecycleTuple); + assertSourceMismatch(changedLifecycle, privateContext); + + Map changedLifecycleGeneration = + SelectedTargetConnectContextTestVectors.privateSourceConnectTokenClaims(); + changedLifecycleGeneration.put("playtestStateGeneration", BigInteger.valueOf(4)); + assertSourceMismatch(changedLifecycleGeneration, privateContext); + } + + @Test + void rejectsGatewayExpiryBeyondTheVerifiedAccountSourceDeadline() throws Exception { + Map source = SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + long issuedAt = SelectedTargetConnectContextTestVectors.SOURCE_ISSUED_AT; + source.put("exp", BigInteger.valueOf(issuedAt + 10L)); + Map contextPayload = projectContext(source); + contextPayload.put("expiresAt", BigInteger.valueOf(issuedAt + 11L)); + GatewayConnectContext validlySignedContext = verify(sign(contextPayload)); + + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesGatewayContext( + source, validlySignedContext)); + } + @Test void rejectsMillisecondTimesExpiredContextAndClockSkewLifetimeExtension() throws Exception { Map milliseconds = validContext(); @@ -410,6 +541,15 @@ private void assertRejected(Map claims) throws Exception { assertThrows(IllegalArgumentException.class, () -> verify(sign(claims))); } + private void assertSourceMismatch( + Map sourceClaims, GatewayConnectContext verifiedContext) { + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesGatewayContext( + sourceClaims, verifiedContext)); + } + private static BigInteger nested( Map claims, String object, String nestedObject, String key) { @SuppressWarnings("unchecked") diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 519d0b31ba..80a347e06d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -72,6 +72,7 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; +import org.springframework.data.redis.core.ValueOperations; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.DynamicPropertyRegistry; @@ -159,6 +160,8 @@ static void registerProperties(DynamicPropertyRegistry registry) { @MockitoBean private RedisTemplate redisTemplate; + @MockitoBean private ValueOperations redisValueOperations; + @MockitoBean private SetOperations redisSetOperations; @Autowired private SessionContextService sessionContextService; @@ -175,18 +178,37 @@ static void registerProperties(DynamicPropertyRegistry registry) { @Autowired private GameplayAdmissionPointerEventRepository gameplayAdmissionPointerEventRepository; + private final ConcurrentMap redisValueStore = new ConcurrentHashMap<>(); private final ConcurrentMap> redisSetStore = new ConcurrentHashMap<>(); @BeforeEach void setUp() { + redisValueStore.clear(); redisSetStore.clear(); sessionContextService.deleteBySessionId(22L, 41L); sessionContextService.deleteBySessionId(22L, 42L); sessionContextService.deleteBySessionId(22L, 1L); sessionContextService.deleteBySessionId(22L, 2L); resetAdmissionPointers(); + when(redisTemplate.opsForValue()).thenReturn(redisValueOperations); when(redisTemplate.opsForSet()).thenReturn(redisSetOperations); + when(redisValueOperations.get(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> redisValueStore.get(invocation.getArgument(0))); + org.mockito.Mockito.doAnswer( + invocation -> { + redisValueStore.put(invocation.getArgument(0), invocation.getArgument(1)); + return null; + }) + .when(redisValueOperations) + .set( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(java.time.Duration.class)); + org.mockito.Mockito.doAnswer( + invocation -> redisValueStore.remove(invocation.getArgument(0)) != null) + .when(redisTemplate) + .delete(org.mockito.ArgumentMatchers.anyString()); when(gameInstanceRepository.save(org.mockito.ArgumentMatchers.any(GameInstance.class))) .thenAnswer(invocation -> invocation.getArgument(0)); org.mockito.Mockito.doAnswer( From 03fd410ccb37552a2e1e11fdb948f99cc58005c2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 08:34:18 +1300 Subject: [PATCH 33/46] Prove disabled first-party admission with a current valid signed context --- ...essionWebSocketHandlerIntegrationTest.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 80a347e06d..8c49a8113f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -11,9 +11,12 @@ import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.ObjectMapper; +import java.math.BigInteger; import java.net.URI; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.time.Clock; +import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -983,16 +986,29 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots void websocketFirstPartySignedCompleteContextFailsClosedWithoutMutation() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("Ed25519"); KeyPair gatewayKeyPair = generator.generateKeyPair(); + long verifiedAt = Instant.now(Clock.systemUTC()).getEpochSecond(); + long issuedAt = verifiedAt - 1L; + java.util.Map sourceClaims = + new java.util.LinkedHashMap<>( + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims()); + sourceClaims.put("iat", BigInteger.valueOf(issuedAt)); + sourceClaims.put("exp", BigInteger.valueOf(issuedAt + 30L)); java.util.Map contextClaims = GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( - SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(), - SelectedTargetConnectContextTestVectors.GATEWAY_VERIFIED_AT, - "gateway-request-runtime-disabled"); + sourceClaims, verifiedAt, "gateway-request-runtime-disabled"); String signedContext = GatewayConnectContextSignature.sign( new ObjectMapper().writeValueAsBytes(contextClaims), SelectedTargetConnectContextTestVectors.GATEWAY_KID, gatewayKeyPair.getPrivate()); + assertThat( + GatewayConnectContextCodec.verifyAndDecode( + signedContext, + java.util.Map.of( + SelectedTargetConnectContextTestVectors.GATEWAY_KID, + gatewayKeyPair.getPublic()), + Clock.systemUTC())) + .isNotNull(); GameplayWebSocketDriver.CloseEvent closeEvent; try (GameplayWebSocketDriver client = GameplayWebSocketDriver.connect( From b7766564da68ab44441ae2c6e2a6e3e130e11df7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 08:53:54 +1300 Subject: [PATCH 34/46] Require executed signed-context denial proof in Game Session CI --- .github/workflows/ci.yml | 2 ++ .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9856c37a5f..20284ae3ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -971,7 +971,9 @@ jobs: bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite net.firedevops.firemud.gamesession.repository.ScriptPinOperationRepositoryIntegrationTest \ + --require-suite net.firedevops.firemud.gamesession.websocket.GameSessionWebSocketHandlerIntegrationTest \ --require-case 'net.firedevops.firemud.gamesession.repository.ScriptPinOperationRepositoryIntegrationTest#pinAdmissionBaseMustStillMatchTheRowLockedRuntimeAndIsBoundToTheReceipt()' \ + --require-case 'net.firedevops.firemud.gamesession.websocket.GameSessionWebSocketHandlerIntegrationTest#websocketFirstPartySignedCompleteContextFailsClosedWithoutMutation()' \ game-session-service - name: 📦 Build Runtime JAR 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 38abd6693f..c87202d307 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,7 +32,7 @@ The in-progress #2873 tenant bridge now has a signed Game Design migration-manif The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. -The canonical Account-signed selected-target `gameplay-connect` profile and Gateway assertion remain owned by [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema). #2911 adds the fail-closed Account/Gateway guards and shared [context codec](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java) with [signed vectors and source-correspondence tests](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java). Local affected-module checks passed; most Docker-backed cases skipped. Initial exact-head CI passed Account/Gateway but exposed a shared Redis fixture regression in 16 Game Session integration cases; its fixture restoration still requires executed correction proof. Game Session runtime parsing remains denied until key publication, canonical UUID mapping and real Account exchange/source-evidence proof are available. These components are not a live complete producer/consumer or admission path. Durable issuance, key publication/rotation, Account signature verification, current-authority comparison, runtime consumer wiring and complete negative-proof coverage remain open. No credential-granting path is activated by this checkpoint. +The canonical Account-signed selected-target `gameplay-connect` profile and Gateway assertion remain owned by [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema). #2911 adds the fail-closed Account/Gateway guards and shared [context codec](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java) with [signed vectors and source-correspondence tests](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java). Local affected-module checks passed; most Docker-backed cases skipped. Initial CI exposed a shared Redis fixture regression in 16 Game Session integration cases; corrected-head [run 36720940449](https://github.com/benhook1013/FireMUD/actions/runs/36720940449) at `9800f26ec` executed and passed Account, Gateway and Game Session test/integration tasks and their applicable strict PostgreSQL gates. This clears the shared-fixture regression, not real first-party admission. The subsequent denial fixture uses current signed timestamps and explicitly proves component validity before exercising runtime denial. [Run 36766661664](https://github.com/benhook1013/FireMUD/actions/runs/36766661664) at `03fd410cc` executed and passed the affected services and common-security tests, but its successful logs do not enumerate that fixture individually. CI now requires the complete 16-case WebSocket handler suite and that exact denial case to pass without skips, alongside the Script Pin proof; pending gate execution is not a pass. Game Session runtime parsing remains denied until key publication, canonical UUID mapping and real Account exchange/source-evidence proof are available. These components are not a live complete producer/consumer or admission path. Durable issuance, key publication/rotation, Account signature verification, current-authority comparison, runtime consumer wiring and complete negative-proof coverage remain open. No credential-granting path is activated by this checkpoint. Separately, hosted CI run `36703863842` on committed #2881 `b2a2f31b02e7ad48b0d42a9da7cf7b3acec2782e` executed 29 JOIN, 9 V35, and 9 V37 PostgreSQL cases; the Account and Game Session jobs passed, while the aggregate workflow remained red from inherited failures. These are exact-parent storage/integration results, not validation of #2911's new context path or proof of the complete credential producer/consumer flow. From 131e3d60efe2fb947a7b473430a5887cb990c1cc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 09:30:38 +1300 Subject: [PATCH 35/46] Require executed Account authority exhaustion proof in composed CI --- .github/workflows/ci.yml | 11 +++++++++++ design/project-management/ai-observations.md | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 20284ae3ac..0630ea19a2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -965,6 +965,17 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#directDeletionOfIssuanceOperationOrResponseEnvelopeIsRejected()' \ account-service + - name: 🔎 Verify Account authority exhaustion rollback proof + if: ${{ matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationIntegrationTest#exhaustedAccountCountersRollbackTheWholeCallerTransaction()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest#exhaustedSequenceRejectsAppendWithoutChangingEventCheckpointOrCallerSentinel()' \ + account-service + - name: 🔎 Verify Game Session PostgreSQL proof case if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 76086ba037..3cc7dad3f4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -156,3 +156,11 @@ Entry format: - Context: #2911 removed unreachable legacy HMAC first-party success fixtures. A Redis value store named for first-party context also served normal gameplay presence; its mock/stubs were removed with the obsolete cases. - Observation: local Docker-backed integration cases skipped, so compilation and module checks did not expose the lost shared support. Exact-head CI ran the cases and all 16 WebSocket scenarios failed at a null value-operations collaborator, before the intended assertions. The fixture support was restored without restoring HMAC admission; executed correction proof remains required. - Expected pattern: trace every consumer of a shared fixture before removing it, use neutral names for shared support, and preserve an exact executed integration gate when cleanup affects skipped local tests. A green compiled/skipped gate is not proof that fixture dependencies were retained. + +- `2026-10-01`: Shared WebSocket fixture correction gained exact executed proof + - Outcome: exact #2911 head `b7766564d` in CI run `36769172597` executed all 16 required WebSocket integration cases with no skips or failures, including the named complete-signed-context no-mutation denial. This closes the executed correction-proof gap above, not the independent real first-party credential or live browser proof. + +- `2026-10-01`: Stack ancestors may not support the tail's test-proof CLI + - Context: Account counter-exhaustion tests belong to #2876, whose test-result inspector is diagnostic-only; the strict required-suite/case interface exists only in its later descendant. + - Observation: inspection before publication caught an unsupported strict CI step in the older ancestor. The uncommitted step was removed and the required execution gate placed in #2911, preserving source-test ownership without copying future tooling into the ancestor. Local PostgreSQL skips remain explicitly unproved. + - Expected pattern: verify a workflow command against that exact branch's tooling version, not the latest tail; gate composed runtime proof where the required tool exists, then keep owning-PR and composed-descendant proof distinct. From 8501d515e1bc5b2d29c03ce4a47f34865cf35702 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 09:48:51 +1300 Subject: [PATCH 36/46] Prove complete runtime membership snapshots fence concurrent first JOIN --- .../AccountJoinPostgresIntegrationTest.java | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) 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 f3ebf35385..e278d588b0 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 @@ -22,6 +22,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; @@ -32,6 +33,7 @@ import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; @@ -1248,6 +1250,144 @@ void concurrentRuntimeSnapshotPreparationAndFirstJoinPreservePairOrdering() thro } } + @Test + void concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot() throws Exception { + JoinFixture fixture = fixture("active"); + CountDownLatch snapshotCaptured = new CountDownLatch(1); + CountDownLatch releaseSnapshotCommit = new CountDownLatch(1); + CountDownLatch joinReachedAccountFence = new CountDownLatch(1); + AtomicReference capturedSnapshot = new AtomicReference<>(); + AtomicReference joinThread = new AtomicReference<>(); + AtomicReference snapshotBackendPid = new AtomicReference<>(); + AtomicReference joinBackendPid = new AtomicReference<>(); + doAnswer( + invocation -> { + if (Thread.currentThread() == joinThread.get()) { + joinBackendPid.set( + dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class)); + joinReachedAccountFence.countDown(); + } + return invocation.callRealMethod(); + }) + .when(joinOperationRepository) + .lockAccount(fixture.accountId()); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future snapshotAttempt = + executor.submit( + () -> + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> { + capturedSnapshot.set( + membershipAuthorityEventProducer.readRuntimeMembershipSnapshot( + fixture.accountId(), fixture.tenantId())); + snapshotBackendPid.set( + dsl.resultQuery("SELECT pg_backend_pid()") + .fetchOne(0, Integer.class)); + snapshotCaptured.countDown(); + try { + if (!releaseSnapshotCommit.await(45, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "runtime snapshot transaction was not released before its bounded wait expired"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "runtime snapshot transaction was interrupted before commit", ex); + } + })); + + assertThat(snapshotCaptured.await(10, TimeUnit.SECONDS)).isTrue(); + Future joinAttempt = + executor.submit( + () -> { + joinThread.set(Thread.currentThread()); + return join(fixture); + }); + + assertThat(joinReachedAccountFence.await(10, TimeUnit.SECONDS)).isTrue(); + awaitAccountFenceLockWait(snapshotBackendPid.get(), joinBackendPid.get()); + assertThat(joinAttempt.isDone()) + .as("first JOIN must remain blocked until the snapshot owner transaction commits") + .isFalse(); + + RuntimeMembershipSnapshotDto absent = capturedSnapshot.get(); + assertThat(absent).isNotNull(); + assertThat(absent.requestAccountId()).isEqualTo(fixture.accountId()); + assertThat(absent.requestTenantId()).isEqualTo(fixture.tenantId()); + assertThat(absent.accountUuid()).isEqualTo(fixture.accountUuid().toString()); + assertThat(absent.tenantUuid()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(absent.membershipExists()).isFalse(); + assertThat(absent.gameplayAdmissionAllowed()).isFalse(); + assertThat(absent.membershipBaseline().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(absent.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(absent.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(absent.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(absent.issuanceFence()).matches("[1-9][0-9]*"); + assertThat(absent.outboxCheckpoints()) + .containsExactlyElementsOf(expectedMembershipOutboxCheckpoints(fixture, "0")); + assertThat(absent.outboxSourceEvidence()).isEmpty(); + assertThat(absent.sourceEvent()).isNull(); + assertThat(absent.roles()).isEmpty(); + + releaseSnapshotCommit.countDown(); + snapshotAttempt.get(30, TimeUnit.SECONDS); + JoinPublicProductionResult joined = joinAttempt.get(30, TimeUnit.SECONDS); + + assertThat(joined.success()).isTrue(); + assertThat(joined.outcomeCode()).isEqualTo("JOINED"); + assertThat(joined.membershipVersion()).isEqualTo(2L); + assertThat(joined.membershipAuthorityGeneration()).isEqualTo(1L); + assertAuthorityMembershipEvent(fixture, 1L, 2L, false); + + RuntimeMembershipSnapshotDto active = readRuntimeMembershipSnapshot(fixture); + var eventRow = authorityMembershipEventRow(fixture, 1L); + String canonicalEventJson = + new String(eventRow.get("payload", byte[].class), StandardCharsets.UTF_8); + MembershipAuthorityEventV1Codec.MembershipEvent event = + MembershipAuthorityEventV1Codec.verify(canonicalEventJson); + assertThat(active.membershipExists()).isTrue(); + assertThat(active.gameplayAdmissionAllowed()).isTrue(); + assertThat(active.membershipBaseline().membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(active.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(active.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(active.membershipBaseline().membershipVersion()) + .isEqualTo(event.membershipVersion()); + assertThat(active.membershipBaseline().membershipAuthorityGeneration()) + .isEqualTo(event.membershipAuthorityGeneration()); + assertThat(active.authorityTuple()).isEqualTo(event.authorityTuple()); + assertThat(active.authorityTuple()).isEqualTo(absent.authorityTuple()); + assertThat(active.issuanceFence()).isEqualTo(event.issuanceFence()); + assertThat(active.issuanceFence()).isEqualTo(absent.issuanceFence()); + assertThat(active.sourceEvent().eventId()).isEqualTo(event.eventId()); + assertThat(active.sourceEvent().eventDigest()).isEqualTo(event.eventDigest()); + assertThat(active.sourceEvent().canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(event.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(active.outboxCheckpoints()) + .containsExactlyElementsOf(expectedMembershipOutboxCheckpoints(fixture, "1")); + assertThat(active.outboxSourceEvidence()) + .containsExactly( + new OutboxSourceEvidence( + authorityStreamKey(fixture), + "1", + event.eventId(), + event.eventDigest(), + event.canonicalJson())); + assertThat(active.roles()).containsExactlyElementsOf(event.roles()); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); + assertThat(countAuthorityMembershipStreams(fixture)).isEqualTo(1L); + } finally { + releaseSnapshotCommit.countDown(); + executor.shutdownNow(); + } + } + @Test void neverJoinedSnapshotReaderRejectsMissingPairWithoutEnrollingIt() { JoinFixture missingPair = fixture("active"); @@ -2020,6 +2160,27 @@ private static void await(CountDownLatch start) { } } + private void awaitAccountFenceLockWait(Integer snapshotBackendPid, Integer joinBackendPid) + throws InterruptedException { + assertThat(snapshotBackendPid).isNotNull(); + assertThat(joinBackendPid).isNotNull(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + Boolean blockedBySnapshot = + dsl.resultQuery( + "SELECT CAST(? AS integer) = ANY(pg_blocking_pids(CAST(? AS integer)))", + snapshotBackendPid, + joinBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blockedBySnapshot)) { + return; + } + Thread.sleep(10); + } + throw new AssertionError( + "JOIN backend did not enter a PostgreSQL lock wait on the snapshot owner transaction"); + } + private void assertJoinAuthorityFailureRemainsPending(JoinFixture fixture) { assertThat(countMemberships(fixture)).isZero(); assertThat(countRoleSnapshotHeaders(fixture)).isZero(); From e8771d2e2b693bba562c8fee835147a022eae704 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 09:58:05 +1300 Subject: [PATCH 37/46] Gate snapshot JOIN race execution and align current Unit 1B proof --- .github/workflows/ci.yml | 3 ++- .../implementation-tracking/player-access-and-session.md | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0630ea19a2..bf376f34e4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -944,7 +944,7 @@ jobs: run: | echo "::group::Run Module Validation" if [[ "${{ matrix.module }}" == "account-service" || "${{ matrix.module }}" == "game-session-service" ]]; then - ./gradlew :${{ matrix.module }}:check -PfullCheck --no-build-cache + ./gradlew :${{ matrix.module }}:check -PfullCheck --no-build-cache --no-configuration-cache else ./gradlew :${{ matrix.module }}:check -PfullCheck fi @@ -959,6 +959,7 @@ jobs: --require-suite integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#concurrentExactIssuanceClaimsHaveOneTerminalFirstWriter()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#lostIssuanceResponseRecoversExactEncryptedResultFromDurableReadback(Path)' \ 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 c87202d307..771e6c3d9b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,7 +32,7 @@ The in-progress #2873 tenant bridge now has a signed Game Design migration-manif The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. -The canonical Account-signed selected-target `gameplay-connect` profile and Gateway assertion remain owned by [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema). #2911 adds the fail-closed Account/Gateway guards and shared [context codec](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java) with [signed vectors and source-correspondence tests](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java). Local affected-module checks passed; most Docker-backed cases skipped. Initial CI exposed a shared Redis fixture regression in 16 Game Session integration cases; corrected-head [run 36720940449](https://github.com/benhook1013/FireMUD/actions/runs/36720940449) at `9800f26ec` executed and passed Account, Gateway and Game Session test/integration tasks and their applicable strict PostgreSQL gates. This clears the shared-fixture regression, not real first-party admission. The subsequent denial fixture uses current signed timestamps and explicitly proves component validity before exercising runtime denial. [Run 36766661664](https://github.com/benhook1013/FireMUD/actions/runs/36766661664) at `03fd410cc` executed and passed the affected services and common-security tests, but its successful logs do not enumerate that fixture individually. CI now requires the complete 16-case WebSocket handler suite and that exact denial case to pass without skips, alongside the Script Pin proof; pending gate execution is not a pass. Game Session runtime parsing remains denied until key publication, canonical UUID mapping and real Account exchange/source-evidence proof are available. These components are not a live complete producer/consumer or admission path. Durable issuance, key publication/rotation, Account signature verification, current-authority comparison, runtime consumer wiring and complete negative-proof coverage remain open. No credential-granting path is activated by this checkpoint. +The canonical Account-signed selected-target `gameplay-connect` profile and Gateway assertion remain owned by [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#account-signed-selected-target-gameplay-connect-schema). #2911 adds the fail-closed Account/Gateway guards and shared [context codec](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java) with [signed vectors and source-correspondence tests](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java). Local affected-module checks passed; most Docker-backed cases skipped. Initial CI exposed a shared Redis fixture regression in 16 Game Session integration cases. Corrected exact-head [run 36769172597](https://github.com/benhook1013/FireMUD/actions/runs/36769172597) at `b7766564d` passed the strict complete 16-case WebSocket handler and 25-case Script Pin suites with no skips or failures; both named methods, including current-valid complete-signed-context no-mutation denial, executed once. Account's 47 required PostgreSQL cases also passed. Gateway/common-security tasks were cached in that run; unchanged source executed in preceding `03fd410cc` run, not freshly here. This clears the shared-fixture regression and proves the denial assertion, not real first-party admission. Aggregate CI remains red on recorded inherited failures. Game Session runtime parsing remains denied until key publication, canonical UUID mapping and real Account exchange/source-evidence proof are available. These components are not a live complete producer/consumer or admission path. Durable issuance, key publication/rotation, Account signature verification, current-authority comparison, runtime consumer wiring and complete negative-proof coverage remain open. No credential-granting path is activated by this checkpoint. Separately, hosted CI run `36703863842` on committed #2881 `b2a2f31b02e7ad48b0d42a9da7cf7b3acec2782e` executed 29 JOIN, 9 V35, and 9 V37 PostgreSQL cases; the Account and Game Session jobs passed, while the aggregate workflow remained red from inherited failures. These are exact-parent storage/integration results, not validation of #2911's new context path or proof of the complete credential producer/consumer flow. @@ -77,7 +77,7 @@ Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, | 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. Three earlier fresh corrected-state reviews covered the complete 16-source semantic unit across unchanged authority, implementation, proof, and owner/consumer handoffs; all three found material local corrections. After their known owner fixes, the superseding section-exit cadence requires exactly two further serial whole-unit reviews, with accepted local corrections published between them. Neither the earlier report boundary nor the new cadence is a merge-readiness claim. The Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. The current Account runtime-read denial contains new `PLAY` admissions until those dependencies converge; it does not prove that the target admission flow works. +Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Earlier whole-section discovery and its superseded serial report boundaries are historical alignment evidence, not outstanding review instructions or implementation completion. Required producer/consumer implementation and proof remain open; the [whole-corpus plan](../design-alignment/whole-corpus-authority-review-plan.md#implementation-and-review-method) owns the current implementation-first completion and whole-section review method. The Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. The current Account runtime-read denial contains new `PLAY` admissions until those dependencies converge; it does not prove that the target admission flow works or make Unit 1B merge-ready. ## Unit 1B Section-Exit Dispositions From ddd1bb7de739ffc52342b53e19cfea5588a34264 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:17:08 +1300 Subject: [PATCH 38/46] Observe JOIN intent FK contention in complete snapshot race proof --- .../AccountJoinPostgresIntegrationTest.java | 38 ++++++++++++++++--- 1 file changed, 33 insertions(+), 5 deletions(-) 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 e278d588b0..7b9188b4ec 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 @@ -17,6 +17,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -1255,22 +1256,24 @@ void concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot() t JoinFixture fixture = fixture("active"); CountDownLatch snapshotCaptured = new CountDownLatch(1); CountDownLatch releaseSnapshotCommit = new CountDownLatch(1); - CountDownLatch joinReachedAccountFence = new CountDownLatch(1); + CountDownLatch joinReachedIntentInsert = new CountDownLatch(1); AtomicReference capturedSnapshot = new AtomicReference<>(); AtomicReference joinThread = new AtomicReference<>(); AtomicReference snapshotBackendPid = new AtomicReference<>(); AtomicReference joinBackendPid = new AtomicReference<>(); + // JOIN first inserts its PENDING intent; the account_id FK can block on this row lock before + // JOIN reaches its later explicit lockAccount call. doAnswer( invocation -> { if (Thread.currentThread() == joinThread.get()) { joinBackendPid.set( dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class)); - joinReachedAccountFence.countDown(); + joinReachedIntentInsert.countDown(); } return invocation.callRealMethod(); }) .when(joinOperationRepository) - .lockAccount(fixture.accountId()); + .insertIntent(anyString(), any(), anyString(), anyString()); ExecutorService executor = Executors.newFixedThreadPool(2); try { @@ -1299,7 +1302,18 @@ void concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot() t } })); - assertThat(snapshotCaptured.await(10, TimeUnit.SECONDS)).isTrue(); + if (!snapshotCaptured.await(10, TimeUnit.SECONDS)) { + if (snapshotAttempt.isDone()) { + try { + snapshotAttempt.get(); + } catch (ExecutionException workerFailure) { + throw new AssertionError( + "runtime snapshot worker failed before capturing its result", + workerFailure.getCause()); + } + } + throw new AssertionError("runtime snapshot worker did not capture its result in time"); + } Future joinAttempt = executor.submit( () -> { @@ -1307,7 +1321,21 @@ void concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot() t return join(fixture); }); - assertThat(joinReachedAccountFence.await(10, TimeUnit.SECONDS)).isTrue(); + if (!joinReachedIntentInsert.await(10, TimeUnit.SECONDS)) { + if (joinAttempt.isDone()) { + try { + JoinPublicProductionResult earlyResult = joinAttempt.get(); + throw new AssertionError( + "JOIN completed before its intent-insert instrumentation: " + + earlyResult.outcomeCode()); + } catch (ExecutionException workerFailure) { + throw new AssertionError( + "JOIN worker failed before its intent-insert instrumentation", + workerFailure.getCause()); + } + } + throw new AssertionError("JOIN did not reach its intent insert in time"); + } awaitAccountFenceLockWait(snapshotBackendPid.get(), joinBackendPid.get()); assertThat(joinAttempt.isDone()) .as("first JOIN must remain blocked until the snapshot owner transaction commits") From 7a488cf7059a8dd4866db106e552c4841fcfc169 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:16:05 +1300 Subject: [PATCH 39/46] Prove Account committed connect source readback without admission --- .github/workflows/ci.yml | 10 + .../account-service/runtime-and-data.md | 2 + design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 +- .../AccountCommittedConnectSource.java | 58 + ...AccountConnectTokenIssuanceRepository.java | 52 + .../AccountGameplayConnectSourceVerifier.java | 337 ++++++ .../AccountCommittedConnectSourceReader.java | 312 +++++ ...tedConnectSourceReaderIntegrationTest.java | 1030 +++++++++++++++++ ...ountGameplayConnectSourceVerifierTest.java | 420 +++++++ ...CommittedConnectSourceReaderGuardTest.java | 156 +++ 11 files changed, 2387 insertions(+), 1 deletion(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf376f34e4..3bb43fe4e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -977,6 +977,16 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest#exhaustedSequenceRejectsAppendWithoutChangingEventCheckpointOrCallerSentinel()' \ account-service + - name: 🔎 Verify Account committed connect source readback proof + if: ${{ matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsExactCommittedOriginalSourceAndLostResultWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline()' \ + account-service + - name: 🔎 Verify Game Session PostgreSQL proof case if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9bbd75cbd6..5a782484e1 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -28,6 +28,8 @@ The live runtime membership response carries `accountId`, `tenantId`, `membershi The latest local Unit 1B source checkpoint also rejects both cached idempotent replay and freshly constructed success when the complete selected-target authority evidence is unavailable. This is a fail-closed guard, not a complete Account-signed `gameplay-connect` producer, durable issuance proof, or activation of the target `IssueConnectToken` RPC; end-to-end source evidence and consumer proof remain open. +The next unwired Account component reads an original successful V35 connect-issuance operation and its exact purpose-bound encrypted response envelope under the Account row fence. Its local successful-envelope payload is the strict UTF-8 compact Account JWT, not a reconstructed token or a second credential. It verifies the independently signed Gateway context, the exact Game Session workload identity, Account UUID provenance and approved retained tenant mapping, the stored token hash and identity, the original Account signature/profile, and complete original source/context correspondence. It rechecks the unchanged source and context deadlines after any fence wait. Its immutable result is original-source evidence only: stored authority/postcondition digest binding is not proof of current authority, registry readiness, or admission. This component is not registered as a runtime credential producer or RPC handler; fresh tenant handoff, complete Account-authenticated evidence, current-authority and registry consumption, protected key delivery, and end-to-end exchange remain separate activation gates. Focused proof status is recorded in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). + The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. The membership request now carries typed `PlayerExecutionContext`, and Game Session sends that typed context; Account's handler still denies before producer/data access with `FAILED_PRECONDITION`. The held-back candidate producer/consumer path remains incomplete, so this typed request is not a working admission path or proof of the target membership/entitlement snapshot. The entitlement and realm-grant reads retain their local request shapes and must likewise remain denied until their exact caller/target contracts are carried and verified. An unwired Account membership-snapshot reader now forms an exact one-tenant version map, a complete ordered four-stream checkpoint set, and separate positive membership source-event evidence only from a fenced local transaction. Its issuer, account, and tenant streams can presently prove sequence zero only while their durable generation and source-version baselines remain at one and no committed outbox head exists; advanced upstream history fails closed until its source-event proof is implemented. A never-joined pair's positive version/generation baseline and absence history are read under the same fence; a changed account-local issuance fence is preserved. This reader is not the gRPC response, does not authenticate the runtime caller, and does not enable the denied method or Game Session admission. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3cc7dad3f4..e111cd6cb8 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -164,3 +164,8 @@ Entry format: - Context: Account counter-exhaustion tests belong to #2876, whose test-result inspector is diagnostic-only; the strict required-suite/case interface exists only in its later descendant. - Observation: inspection before publication caught an unsupported strict CI step in the older ancestor. The uncommitted step was removed and the required execution gate placed in #2911, preserving source-test ownership without copying future tooling into the ancestor. Local PostgreSQL skips remain explicitly unproved. - Expected pattern: verify a workflow command against that exact branch's tooling version, not the latest tail; gate composed runtime proof where the required tool exists, then keep owning-PR and composed-descendant proof distinct. + +- `2026-10-01`: Observe the earliest actual transaction in PostgreSQL contention proof + - Context: the complete Account snapshot/first-JOIN test held the Account row `FOR UPDATE` and waited for JOIN's explicit Account-lock spy. JOIN first inserts its PENDING intent, whose foreign-key check can already wait on that same row. + - Observation: exact CI timed out at the later spy, not at a source invariant. Instrumenting the actual intent-insert backend before the real insert retained the exact `pg_blocking_pids` correlation and complete before/after DTO assertions; corrected CI `36778631119` executed the race once successfully. Worker exceptions are surfaced rather than hidden behind a latch timeout. + - Expected pattern: trace earlier foreign-key and deferred-trigger work before selecting a concurrency signal; prove the exact blocked backend/owner relation and do not fix a misplaced signal by extending timeouts or changing production transaction order. 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 771e6c3d9b..7d2fd6be1c 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,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The resumed Account runtime-authority candidate adds an Account-fenced pair-preparation boundary for runtime snapshots: a verified never-joined pair reuses durable absence enrollment and exact readback, while retained active membership requires its existing receipt/event proof and preserved counters. Unmapped tenants, inactive membership, and absent rows with retained history remain denied; neither enrollment nor exact retry creates membership or an authority event. The pure snapshot reader still rejects an absent baseline. Local `:account-service:check -PfullCheck --no-configuration-cache` passed with 389 unit cases executed and all 83 integration cases compiled/discovered but skipped without Docker, including the new concurrent preparation/first-JOIN proof and the preserved connect-issuance recovery cases. #2880 owns composing this preparation with its complete typed same-snapshot response. This is not authenticated RPC, database execution, or admission proof; the runtime membership RPC, credential paths, and Account ring mount remain disabled. +The next Account-owned committed-connect source reader is an unwired prerequisite, not an authorization or credential producer. It recovers a complete successful V35 receipt and purpose-bound envelope by exact identity, checks the original compact JWT hash/JTI and asymmetric signature against the closed selected-target profile, verifies the Gateway assertion independently, and proves source/context correspondence under the Account row fence and approved retained tenant mapping. It requires the exact Game Session peer and an active owner transaction before data access, returns no raw credential, and rechecks unchanged deadlines after a fence wait. The consolidated local Account check passed with 413 unit cases executed, including 11 original-source verifier and four early-denial cases; all 105 PostgreSQL cases compiled but skipped without Docker, including the seven new source-readback cases. The CI strict inspector requires that new suite and both exact reread and fence-expiry methods to execute without skips. This component does not supply fresh tenant authority, authenticated current-eligibility evidence, an issued-token registry, protected key delivery, or a working bare-LOGIN exchange; those gates remain open and no runtime path or mount is enabled. + +Exact #2911 `78c3fe88614708a4cd224800ac0f1bd6d03b310e` [CI 36778631119](https://github.com/benhook1013/FireMUD/actions/runs/36778631119) passed both strict Account PostgreSQL gates: JOIN 30/30, connect issuance 9/9, bare-LOGIN storage 9/9, authority-generation 2/2 and authority-outbox 4/4, all zero skips/failures. The complete nonadmitting snapshot versus concurrent first-JOIN case and both exhaustion rollback methods each executed once. Game Session strict Script Pin 25/25 and WebSocket 16/16 also passed. Account and Game Session checks disabled build/configuration cache and executed their tasks; aggregate CI remains red on separately routed shared tooling, Game Design fixture and Automation formatting failures. This closes those source/component database-proof gaps, not the live authenticated snapshot, complete immutable Account evidence bundle, credential producer/registry, or end-to-end bare-LOGIN gates below. The runtime RPC and credential paths remain denied, and the ring mount remains unpublished. + +Account-fenced runtime snapshot preparation reuses durable absence enrollment and exact readback for a verified never-joined pair, while retained active membership requires its existing receipt/event proof and preserved counters. Unmapped tenants, inactive membership, and absent rows with retained history remain denied; neither enrollment nor exact retry creates membership or an authority event. The pure snapshot reader still rejects an absent baseline. #2880 composes preparation with the complete typed same-snapshot response, and the executed PostgreSQL proof above covers that nonadmitting DTO against concurrent first JOIN. It does not prove an authenticated runtime RPC or admission; those paths and the Account ring mount remain disabled. The unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's exact one-tenant `membershipVersion` map in the producer, strict shared codec, canonical digest vectors, immutable evidence, and Account exact retry/readback comparisons. The Account producer may extract a local numeric value only after validating the map; it does not persist or transmit a scalar event field. Shared codec and Account/Game Session vector tests execute locally; PostgreSQL JOIN/reconciliation tests compile but skip without Docker, and the runtime membership RPC remains denied until its complete same-snapshot producer and consumer proof is ready. The unactivated Account ring materializer binds a dedicated service-account username in the protected source record, checks server-reported identity before Secret access, and returns a typed non-secret receipt with source generation/predecessor and exact Secret UID/resourceVersion readback. A focused read-side verifier now checks its closed typed shape, canonical digest, and exact source, writer, and Secret bindings; this remains local structural proof, not authenticated environment/secrets-channel publication. Sole-writer RBAC, protected custody, handoff, deployment readback, and live readiness remain unproved, so no Account ring mount is published. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java new file mode 100644 index 0000000000..928010f67e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.security.MessageDigest; +import java.util.Objects; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; + +/** Exact committed Account source receipt and its purpose-bound encrypted response envelope. */ +public record AccountCommittedConnectSource( + AccountConnectTokenIssuanceOperation operation, + AccountConnectTokenResponseEnvelope responseEnvelope) { + + public AccountCommittedConnectSource { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(responseEnvelope, "responseEnvelope"); + AccountEnvelopeBinding binding = responseEnvelope.binding(); + if (operation.lifecycle() != Lifecycle.COMMITTED + || !"SUCCESS".equals(operation.outcomeCode()) + || operation.tokenIdentity() == null + || operation.tokenIdentity().isBlank() + || operation.tokenHash() == null + || operation.contextEvidenceDigest() == null + || operation.authorityTupleDigest() == null + || operation.issuanceFenceDigest() == null + || operation.postconditionDigest() == null + || !operation.operationId().equals(responseEnvelope.operationId()) + || binding.operationKind() != AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE + || !operation.operationId().toString().equals(binding.operationId()) + || !operation.requestId().equals(binding.requestId()) + || !Long.toString(operation.accountId()).equals(binding.accountId()) + || !Long.toString(operation.tenantId()).equals(binding.tenantId()) + || !operation + .connectScopeHash() + .equals(AccountJoinDigest.tokenHash(binding.connectScopeId())) + || !sameDigest(operation.requestDigest(), binding.requestDigest()) + || !sameDigest(operation.contextEvidenceDigest(), binding.contextEvidenceDigest()) + || !sameDigest(operation.authorityTupleDigest(), binding.authorityTupleDigest()) + || !sameDigest(operation.issuanceFenceDigest(), binding.issuanceFenceDigest()) + || !sameDigest(operation.postconditionDigest(), binding.postconditionDigest())) { + throw new IllegalArgumentException( + "Committed Account connect source evidence is incomplete or mismatched"); + } + } + + @Override + public String toString() { + return "AccountCommittedConnectSource[operationId=" + + operation.operationId() + + ", lifecycle=" + + operation.lifecycle() + + ", encryptedResponse=]"; + } + + private static boolean sameDigest(byte[] left, byte[] right) { + return left != null && right != null && MessageDigest.isEqual(left, right); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java index 9ef48d7f71..020f06680e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java @@ -102,6 +102,58 @@ public Optional find( return operation; } + /** + * Reads a successful committed source result using only its exact caller identity. The request + * digest and all AEAD evidence are recovered from the immutable winning operation row; callers + * must not derive or substitute a digest when they only possess the original scope and request + * IDs. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCommittedResponseEnvelope( + AccountConnectTokenIssuanceIdentity identity) { + validateIdentity(identity); + Optional stored = readOperation(identity); + if (stored.isEmpty()) { + return Optional.empty(); + } + + AccountConnectTokenIssuanceOperation operation = stored.orElseThrow(); + if (operation.lifecycle() != Lifecycle.COMMITTED + || !"SUCCESS".equals(operation.outcomeCode()) + || operation.tokenIdentity() == null + || operation.tokenIdentity().isBlank() + || operation.tokenHash() == null + || operation.contextEvidenceDigest() == null + || operation.authorityTupleDigest() == null + || operation.issuanceFenceDigest() == null + || operation.postconditionDigest() == null) { + throw new IllegalStateException( + "Connect-token source operation is not a complete committed success"); + } + + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + operation.operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + null, + operation.requestDigest(), + operation.contextEvidenceDigest(), + operation.authorityTupleDigest(), + operation.issuanceFenceDigest(), + operation.postconditionDigest()); + AccountConnectTokenResponseEnvelope envelope = + readResponseEnvelope(identity, operation.requestDigest(), binding) + .orElseThrow( + () -> + new IllegalStateException( + "Committed connect-token source has no exact response envelope")); + return Optional.of(new AccountCommittedConnectSource(operation, envelope)); + } + /** * Adds previously absent token/authority evidence to the first writer's still-PENDING row. * Existing evidence is write-once; retries may confirm the same bytes but cannot replace them. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java new file mode 100644 index 0000000000..3cf47cbf1c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java @@ -0,0 +1,337 @@ +package net.firedevops.firemud.accountservice.security; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.PublicKey; +import java.security.Signature; +import java.security.interfaces.EdECPublicKey; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.json.JsonFactory; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Verifies an Account-signed selected-target gameplay-connect JWT source. + * + *

This original-source component verifies only against the Account public keys explicitly + * supplied at construction. It does not read or publish keys, issue tokens, consult current + * authority, or authorize gameplay admission. + */ +public final class AccountGameplayConnectSourceVerifier { + private static final String INVALID_TOKEN_MESSAGE = "invalid Account gameplay-connect source JWT"; + private static final String SAFE_PROJECTION_CORRELATION_ID = + "account-gameplay-connect-source-verifier"; + private static final long MAX_FUTURE_ISSUED_AT_SECONDS = 5L; + private static final Set HEADER_FIELDS = Set.of("alg", "kid", "typ"); + private static final JsonFactory JSON_FACTORY = + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + private static final JsonMapper JSON = + JsonMapper.builder(JSON_FACTORY) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS) + .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .build(); + + private final String exactIssuer; + private final Map registeredKeys; + private final int maxCompactJwtBytes; + private final Clock clock; + + /** + * Creates an isolated source verifier with the exact Account issuer and public-key registry. + * + * @param exactIssuer exact Account {@code iss} value accepted by this verifier + * @param registeredKeys Account-registered public keys indexed by their exact JOSE {@code kid} + * @param maxCompactJwtBytes maximum UTF-8 byte length of an accepted compact JWT + * @param clock clock used for current source-token time checks + */ + public AccountGameplayConnectSourceVerifier( + String exactIssuer, + Map registeredKeys, + int maxCompactJwtBytes, + Clock clock) { + if (exactIssuer == null || exactIssuer.isBlank()) { + throw new IllegalArgumentException("exact Account issuer is required"); + } + if (registeredKeys == null || registeredKeys.isEmpty()) { + throw new IllegalArgumentException("Account verification keys are required"); + } + if (maxCompactJwtBytes <= 0) { + throw new IllegalArgumentException("maximum compact JWT size must be positive"); + } + if (clock == null) { + throw new IllegalArgumentException("clock is required"); + } + + Map copiedKeys = new LinkedHashMap<>(); + for (Map.Entry entry : registeredKeys.entrySet()) { + String kid = entry.getKey(); + PublicKey key = entry.getValue(); + if (kid == null || kid.isBlank() || !isSupportedKey(key)) { + throw new IllegalArgumentException("Account verification key registry is invalid"); + } + copiedKeys.put(kid, key); + } + this.exactIssuer = exactIssuer; + this.registeredKeys = Collections.unmodifiableMap(copiedKeys); + this.maxCompactJwtBytes = maxCompactJwtBytes; + this.clock = clock; + } + + /** + * Verifies a compact Account gameplay-connect source JWT and returns its closed source claims. + * + *

Every verification failure has the same sanitized exception message. Neither the source + * token, credential material, nor detailed parser or cryptographic failures are retained. + * + * @param compactJwt compact Account-signed JWT + * @return deeply immutable exact source-claim map; the compact JWT is never included + * @throws IllegalArgumentException if the token is malformed, untrusted, expired, or outside the + * registered source profile + */ + public Map verify(String compactJwt) { + try { + return verifyInternal(compactJwt); + } catch (RuntimeException | GeneralSecurityException ex) { + throw invalidToken(); + } + } + + private Map verifyInternal(String compactJwt) throws GeneralSecurityException { + String[] segments = splitCanonicalCompactJwt(compactJwt); + byte[] protectedHeaderBytes = decodeCanonicalBase64Url(segments[0]); + byte[] payloadBytes = decodeCanonicalBase64Url(segments[1]); + byte[] signatureBytes = decodeCanonicalBase64Url(segments[2]); + + Map header = parseJsonObject(protectedHeaderBytes); + validateProtectedHeaderShape(header); + String algorithm = requireText(header, "alg"); + String kid = requireText(header, "kid"); + if (header.containsKey("typ") && !"JWT".equals(header.get("typ"))) { + throw invalidToken(); + } + + PublicKey key = registeredKeys.get(kid); + if (key == null) { + throw invalidToken(); + } + String jcaAlgorithm = requireCompatibleAlgorithm(algorithm, key); + verifySignature(segments[0], segments[1], signatureBytes, key, jcaAlgorithm); + + Map sourceClaims = parseJsonObject(payloadBytes); + Instant now = clock.instant(); + validateIssuerAudienceAndTime(sourceClaims, now); + + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + sourceClaims, now.getEpochSecond(), SAFE_PROJECTION_CORRELATION_ID); + return deepImmutableObject(sourceClaims); + } + + private String[] splitCanonicalCompactJwt(String compactJwt) { + if (compactJwt == null || compactJwt.isEmpty() || compactJwt.length() > maxCompactJwtBytes) { + throw invalidToken(); + } + for (int index = 0; index < compactJwt.length(); index++) { + if (compactJwt.charAt(index) > 0x7f) { + throw invalidToken(); + } + } + + int firstDot = compactJwt.indexOf('.'); + int secondDot = firstDot < 0 ? -1 : compactJwt.indexOf('.', firstDot + 1); + if (firstDot <= 0 + || secondDot <= firstDot + 1 + || secondDot == compactJwt.length() - 1 + || compactJwt.indexOf('.', secondDot + 1) >= 0) { + throw invalidToken(); + } + return new String[] { + compactJwt.substring(0, firstDot), + compactJwt.substring(firstDot + 1, secondDot), + compactJwt.substring(secondDot + 1) + }; + } + + private byte[] decodeCanonicalBase64Url(String segment) { + try { + byte[] decoded = Base64.getUrlDecoder().decode(segment); + String canonical = Base64.getUrlEncoder().withoutPadding().encodeToString(decoded); + if (!canonical.equals(segment)) { + throw invalidToken(); + } + return decoded; + } catch (IllegalArgumentException ex) { + throw invalidToken(); + } + } + + private Map parseJsonObject(byte[] jsonBytes) { + try (var parser = JSON_FACTORY.createParser(jsonBytes)) { + Object decoded = JSON.readValue(parser, Object.class); + if (parser.nextToken() != null || !(decoded instanceof Map rawObject)) { + throw invalidToken(); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : rawObject.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalidToken(); + } + result.put(key, entry.getValue()); + } + return result; + } catch (RuntimeException ex) { + throw invalidToken(); + } + } + + private void validateProtectedHeaderShape(Map header) { + if (!HEADER_FIELDS.containsAll(header.keySet()) + || !header.containsKey("alg") + || !header.containsKey("kid")) { + throw invalidToken(); + } + } + + private String requireCompatibleAlgorithm(String algorithm, PublicKey key) { + if (key instanceof RSAPublicKey) { + return switch (algorithm) { + case "RS256" -> "SHA256withRSA"; + case "RS384" -> "SHA384withRSA"; + case "RS512" -> "SHA512withRSA"; + default -> throw invalidToken(); + }; + } + if (key instanceof EdECPublicKey edKey + && "Ed25519".equals(edKey.getParams().getName()) + && "EdDSA".equals(algorithm)) { + return "Ed25519"; + } + throw invalidToken(); + } + + private void verifySignature( + String protectedSegment, + String payloadSegment, + byte[] signatureBytes, + PublicKey key, + String jcaAlgorithm) + throws GeneralSecurityException { + if (signatureBytes.length == 0) { + throw invalidToken(); + } + if ("Ed25519".equals(jcaAlgorithm) && signatureBytes.length != 64) { + throw invalidToken(); + } + byte[] signingInput = + (protectedSegment + "." + payloadSegment).getBytes(StandardCharsets.US_ASCII); + Signature verifier = Signature.getInstance(jcaAlgorithm); + verifier.initVerify(key); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) { + throw invalidToken(); + } + } + + private void validateIssuerAudienceAndTime(Map claims, Instant now) { + if (!exactIssuer.equals(claims.get("iss")) + || !(claims.get("iss") instanceof String) + || !"gameplay-connect".equals(claims.get("aud"))) { + throw invalidToken(); + } + BigInteger issuedAt = requireInteger(claims, "iat"); + BigInteger expiresAt = requireInteger(claims, "exp"); + if (issuedAt.signum() <= 0 || expiresAt.compareTo(issuedAt) <= 0) { + throw invalidToken(); + } + try { + Instant issuedAtInstant = Instant.ofEpochSecond(issuedAt.longValueExact()); + Instant expiresAtInstant = Instant.ofEpochSecond(expiresAt.longValueExact()); + if (!now.isBefore(expiresAtInstant) + || issuedAt + .subtract(BigInteger.valueOf(now.getEpochSecond())) + .compareTo(BigInteger.valueOf(MAX_FUTURE_ISSUED_AT_SECONDS)) + > 0) { + throw invalidToken(); + } + // Force validation of both epoch-second claims before the shared profile codec sees them. + if (issuedAtInstant.isAfter(expiresAtInstant)) { + throw invalidToken(); + } + } catch (ArithmeticException | DateTimeException ex) { + throw invalidToken(); + } + } + + private BigInteger requireInteger(Map values, String field) { + Object value = values.get(field); + if (!(value instanceof BigInteger integer)) { + throw invalidToken(); + } + return integer; + } + + private String requireText(Map values, String field) { + Object value = values.get(field); + if (!(value instanceof String text) || text.isBlank()) { + throw invalidToken(); + } + return text; + } + + private Map deepImmutableObject(Map source) { + Map copy = new LinkedHashMap<>(); + source.forEach((key, value) -> copy.put(key, deepImmutableValue(value))); + return Collections.unmodifiableMap(copy); + } + + private Object deepImmutableValue(Object value) { + if (value == null + || value instanceof String + || value instanceof Boolean + || value instanceof BigInteger + || value instanceof BigDecimal) { + return value; + } + if (value instanceof Map sourceMap) { + Map copy = new LinkedHashMap<>(); + for (Map.Entry entry : sourceMap.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalidToken(); + } + copy.put(key, deepImmutableValue(entry.getValue())); + } + return Collections.unmodifiableMap(copy); + } + if (value instanceof List sourceList) { + List copy = new ArrayList<>(sourceList.size()); + for (Object entry : sourceList) { + copy.add(deepImmutableValue(entry)); + } + return Collections.unmodifiableList(copy); + } + throw invalidToken(); + } + + private static boolean isSupportedKey(PublicKey key) { + return (key instanceof RSAPublicKey rsaKey && rsaKey.getModulus().bitLength() >= 2048) + || (key instanceof EdECPublicKey edKey && "Ed25519".equals(edKey.getParams().getName())); + } + + private static IllegalArgumentException invalidToken() { + return new IllegalArgumentException(INVALID_TOKEN_MESSAGE); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java new file mode 100644 index 0000000000..7f3f21d132 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.nio.ByteBuffer; +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.security.PublicKey; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.GatewayConnectContext; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired, non-authorizing readback of the original committed Account gameplay-connect source. This + * component verifies provenance and source/context correspondence only; it does not establish + * current gameplay authority, registry readiness, or admission. + */ +public final class AccountCommittedConnectSourceReader { + private final AccountConnectTokenIssuanceRepository issuanceRepository; + private final AccountRepository accountRepository; + private final AccountTenantIdentityResolver tenantIdentityResolver; + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountEnvelopeCrypto envelopeCrypto; + private final AccountGameplayConnectSourceVerifier sourceVerifier; + private final Map gatewayVerificationKeys; + private final Clock clock; + private final String expectedGameSessionPeerUri; + + public AccountCommittedConnectSourceReader( + AccountConnectTokenIssuanceRepository issuanceRepository, + AccountRepository accountRepository, + AccountTenantIdentityResolver tenantIdentityResolver, + AccountJoinOperationRepository joinOperationRepository, + AccountEnvelopeCrypto envelopeCrypto, + AccountGameplayConnectSourceVerifier sourceVerifier, + Map gatewayVerificationKeys, + Clock clock, + String workloadNamespace) { + this.issuanceRepository = Objects.requireNonNull(issuanceRepository, "issuanceRepository"); + this.accountRepository = Objects.requireNonNull(accountRepository, "accountRepository"); + this.tenantIdentityResolver = + Objects.requireNonNull(tenantIdentityResolver, "tenantIdentityResolver"); + this.joinOperationRepository = + Objects.requireNonNull(joinOperationRepository, "joinOperationRepository"); + this.envelopeCrypto = Objects.requireNonNull(envelopeCrypto, "envelopeCrypto"); + this.sourceVerifier = Objects.requireNonNull(sourceVerifier, "sourceVerifier"); + this.gatewayVerificationKeys = Map.copyOf(gatewayVerificationKeys); + if (this.gatewayVerificationKeys.isEmpty()) { + throw new IllegalArgumentException("Gateway verification keys are required"); + } + this.clock = Objects.requireNonNull(clock, "clock"); + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Account workload namespace is required"); + } + this.expectedGameSessionPeerUri = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .filter(identity -> workloadNamespace.equals(identity.namespace())) + .map(GrpcPeerIdentity::uri) + .orElseThrow( + () -> new IllegalArgumentException("Account workload namespace is invalid")); + } + + /** + * Reads and verifies one original committed source in the caller's owner transaction. The exact + * Game Session peer, Gateway assertion, account fence, retained tenant association, source + * envelope, Account JWT signature/profile, and complete source/context correspondence are all + * checked before returning immutable evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public OriginalSourceEvidence read( + AccountConnectTokenIssuanceIdentity identity, String signedGatewayContext) { + Objects.requireNonNull(identity, "identity"); + requireGameSessionPeer(); + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Committed Account source readback requires an active owner transaction"); + } + GatewayConnectContext initialContext = verifyGatewayContext(signedGatewayContext); + requireContextRequestIdentity(identity, initialContext); + + // The same Account row fence serializes this identity/provenance read with JOIN and other + // fenced Account work. The retained tenant association resolver separately verifies its + // approved row and exact current source-evidence digest in this owner transaction. + joinOperationRepository.lockAccount(identity.accountId()); + Account account = + accountRepository + .findById(identity.accountId()) + .orElseThrow(() -> new IllegalStateException("Account source identity is absent")); + UUID accountUuid = requireAccountIdentity(account, identity.accountId()); + requireContextValue(initialContext, "accountId", accountUuid.toString()); + + ApprovedAssociation tenantAssociation = tenantIdentityResolver.resolve(identity.tenantId()); + if (tenantAssociation.legacyTenantId() != identity.tenantId()) { + throw new IllegalStateException("Account source tenant identity is mismatched"); + } + requireContextValue( + initialContext, "tenantId", tenantAssociation.canonicalTenantId().toString()); + + AccountCommittedConnectSource committedSource = + issuanceRepository + .readCommittedResponseEnvelope(identity) + .orElseThrow(() -> new IllegalStateException("Committed Account source is absent")); + byte[] compactJwtBytes = + envelopeCrypto.decrypt( + committedSource.responseEnvelope().envelope(), + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + committedSource.responseEnvelope().binding()); + try { + String compactJwt = decodeStrictUtf8(compactJwtBytes); + byte[] actualTokenHash = sha256(compactJwtBytes); + if (!MessageDigest.isEqual(committedSource.operation().tokenHash(), actualTokenHash)) { + throw new IllegalStateException("Committed Account source token hash does not match"); + } + + Map sourceClaims = sourceVerifier.verify(compactJwt); + if (!Objects.equals(sourceClaims.get("jti"), committedSource.operation().tokenIdentity())) { + throw new IllegalStateException("Committed Account source token identity does not match"); + } + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesGatewayContext( + sourceClaims, initialContext); + + // A transaction may wait on the Account fence after the Gateway originally verified its + // short-lived context. Recheck the unchanged signed assertion at the current clock without + // restamping or extending any deadline before returning the evidence. + GatewayConnectContext currentContext = verifyGatewayContext(signedGatewayContext); + if (!initialContext.kid().equals(currentContext.kid()) + || !initialContext.claims().equals(currentContext.claims())) { + throw new IllegalStateException("Gateway source context changed during Account readback"); + } + Map currentSourceClaims = sourceVerifier.verify(compactJwt); + if (!sourceClaims.equals(currentSourceClaims)) { + throw new IllegalStateException("Account source claims changed during source readback"); + } + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesGatewayContext( + currentSourceClaims, currentContext); + + return new OriginalSourceEvidence( + committedSource.operation().operationId(), + committedSource.responseEnvelope().envelope().keyId(), + actualTokenHash, + currentContext.kid(), + currentSourceClaims, + currentContext.claims()); + } finally { + java.util.Arrays.fill(compactJwtBytes, (byte) 0); + } + } + + private GatewayConnectContext verifyGatewayContext(String signedGatewayContext) { + return GatewayConnectContextCodec.verifyAndDecode( + signedGatewayContext, gatewayVerificationKeys, clock); + } + + private void requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !expectedGameSessionPeerUri.equals(peer.uri())) { + throw new AdminAuthorizationException( + "Committed Account source readback requires the exact Game Session workload identity"); + } + } + + private static void requireContextRequestIdentity( + AccountConnectTokenIssuanceIdentity identity, GatewayConnectContext context) { + if (!identity.connectScopeId().equals(context.text("connectScopeId")) + || !identity.requestId().equals(context.text("connectRequestId"))) { + throw new IllegalArgumentException( + "Gateway context does not match the exact Account source request identity"); + } + } + + private static UUID requireAccountIdentity(Account account, long numericAccountId) { + if (account.getId() == null + || account.getId() != numericAccountId + || account.getAccountUuid() == null + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || account.getAccountUuidSourceNumericId() != numericAccountId) { + throw new IllegalStateException("Account canonical identity provenance is mismatched"); + } + return account.getAccountUuid(); + } + + private static void requireContextValue( + GatewayConnectContext context, String field, String expectedValue) { + if (!expectedValue.equals(context.text(field))) { + throw new IllegalArgumentException( + "Gateway context does not match the retained Account " + field); + } + } + + private static String decodeStrictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException exception) { + throw new IllegalStateException("Committed Account source envelope is not strict UTF-8"); + } + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** + * Immutable, non-authorizing exact original-source readback. It never exposes the compact JWT. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Verified claim maps and nested JSON values are deeply copied into immutable containers " + + "by the canonical constructor before record accessors expose them") + public record OriginalSourceEvidence( + UUID operationId, + String responseEnvelopeKeyId, + byte[] sourceTokenHash, + String gatewayKeyId, + Map originalSourceClaims, + Map gatewayContextClaims) { + public OriginalSourceEvidence { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + if (sourceTokenHash == null || sourceTokenHash.length != 32) { + throw new IllegalArgumentException("source token hash must be 32 bytes"); + } + sourceTokenHash = sourceTokenHash.clone(); + originalSourceClaims = immutableObject(originalSourceClaims); + gatewayContextClaims = immutableObject(gatewayContextClaims); + } + + @Override + public byte[] sourceTokenHash() { + return sourceTokenHash.clone(); + } + + @Override + public String toString() { + return "OriginalSourceEvidence[operationId=" + + operationId + + ", source=, gatewayContext=]"; + } + + private static Map immutableObject(Map source) { + Objects.requireNonNull(source, "claims"); + Map copy = new LinkedHashMap<>(); + source.forEach((key, value) -> copy.put(key, immutableValue(value))); + return Collections.unmodifiableMap(copy); + } + + private static Object immutableValue(Object value) { + if (value == null + || value instanceof String + || value instanceof Boolean + || value instanceof BigInteger + || value instanceof java.math.BigDecimal) { + return value; + } + if (value instanceof Map source) { + Map copy = new LinkedHashMap<>(); + source.forEach( + (key, nested) -> { + if (!(key instanceof String text)) { + throw new IllegalArgumentException("claim object keys must be strings"); + } + copy.put(text, immutableValue(nested)); + }); + return Collections.unmodifiableMap(copy); + } + if (value instanceof List source) { + List copy = new ArrayList<>(source.size()); + source.forEach(nested -> copy.add(immutableValue(nested))); + return Collections.unmodifiableList(copy); + } + throw new IllegalArgumentException("unsupported verified claim value"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java new file mode 100644 index 0000000000..0b1e04e981 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java @@ -0,0 +1,1030 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.security.Signature; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.OriginalSourceEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +// Peer identity is context-scoped here; this proves the component caller guard, not network mTLS. +class AccountCommittedConnectSourceReaderIntegrationTest { + private static final String WORKLOAD_NAMESPACE = "account-test"; + private static final String ACCOUNT_ISSUER = "https://account.example.test"; + private static final String ACCOUNT_KEY_ID = "account-test-key"; + private static final String GATEWAY_KEY_ID = "gateway-test-key"; + private static final long LEGACY_TENANT_ID = 77L; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Base64.Encoder BASE64_URL = Base64.getUrlEncoder().withoutPadding(); + private static final SecureRandom FIXTURE_RANDOM = new SecureRandom(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir Path tempDir; + + @Test + void readsExactCommittedOriginalSourceAndLostResultWithoutMutation() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + Snapshot before = sourceSnapshot(prepared, source.identity()); + + OriginalSourceEvidence first = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> prepared.reader().read(source.identity(), source.gatewayEnvelope()))); + OriginalSourceEvidence reread = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> prepared.reader().read(source.identity(), source.gatewayEnvelope()))); + + assertThat(first.operationId()).isEqualTo(reread.operationId()); + assertThat(first.responseEnvelopeKeyId()).isEqualTo(reread.responseEnvelopeKeyId()); + assertThat(first.gatewayKeyId()).isEqualTo(GATEWAY_KEY_ID); + assertThat(first.sourceTokenHash()).containsExactly(reread.sourceTokenHash()); + assertThat(first.originalSourceClaims()).isEqualTo(source.sourceClaims()); + assertThat(first.gatewayContextClaims()).isEqualTo(source.gatewayClaims()); + assertThat(first.originalSourceClaims()).containsEntry("aud", "gameplay-connect"); + assertThat(first.originalSourceClaims().get("jti")).isEqualTo(source.tokenIdentity()); + assertThat(first.toString()).doesNotContain(source.identity().connectScopeId()); + assertThatThrownBy(() -> first.originalSourceClaims().put("extra", "value")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + ((Map) first.originalSourceClaims().get("authorityTuple")) + .put("extra", BigInteger.ONE)) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + } + + @Test + void requiresExactGameSessionCallerAndRegisteredGatewayAndAccountKeys() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "account-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(AdminAuthorizationException.class); + + assertThatThrownBy( + () -> + withoutPeer( + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(AdminAuthorizationException.class); + + assertThatThrownBy( + () -> + withPeer( + peer("other-account-test", "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(AdminAuthorizationException.class); + + Snapshot beforeOutsideTransaction = sourceSnapshot(prepared, source.identity()); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> prepared.reader().read(source.identity(), source.gatewayEnvelope()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(beforeOutsideTransaction); + + SourceFixture unknownGateway = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, true, false, false)); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read( + unknownGateway.identity(), + unknownGateway.gatewayEnvelope())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown Gateway verification key"); + + SourceFixture unknownSource = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(true, false, false, false, false, false, false)); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read( + unknownSource.identity(), + unknownSource.gatewayEnvelope())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("invalid Account gameplay-connect source JWT"); + } + + @Test + void rejectsWrongStoredTokenHashJtiAndSourceTargetCorrespondence() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture wrongHash = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, true, false, false, false, false, false)); + SourceFixture wrongJti = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, true, false, false, false, false)); + SourceFixture wrongTarget = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, true, false, false, false)); + + assertReadRejected(prepared, wrongHash, IllegalStateException.class, "token hash"); + assertReadRejected(prepared, wrongJti, IllegalStateException.class, "token identity"); + assertReadRejected( + prepared, wrongTarget, IllegalArgumentException.class, "does not exactly preserve"); + } + + @Test + void requiresPresentCommittedSuccessfulV35SourceAndResponseEnvelope() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture absent = newSource(prepared, SourceState.ABSENT); + SourceFixture pending = newSource(prepared, SourceState.PENDING); + SourceFixture failed = newSource(prepared, SourceState.FAILED); + + assertReadRejected(prepared, absent, IllegalStateException.class, "source is absent"); + assertReadRejected( + prepared, pending, IllegalStateException.class, "not a complete committed success"); + assertReadRejected( + prepared, failed, IllegalStateException.class, "not a complete committed success"); + } + + @Test + void rejectsUnmappedAndChangedRetainedTenantEvidence() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture unmappedTenant = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, false, false, true)); + assertReadRejected( + prepared, + unmappedTenant, + IllegalStateException.class, + "approved Account tenant association is absent"); + + SourceFixture changedRetainedEvidence = newSource(prepared, SourceState.COMMITTED); + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .dsl() + .execute( + "UPDATE account_legacy_tenant_sources " + + "SET captured_at = captured_at + INTERVAL '1 second' " + + "WHERE legacy_tenant_id = ?", + prepared.tenantId())); + assertReadRejected( + prepared, + changedRetainedEvidence, + IllegalStateException.class, + "approved Account source evidence differs from retained rows"); + } + + @Test + void rejectsWrongPurposeAndWrongPurposeKeyForStoredEnvelope() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + AccountCommittedConnectSource stored = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .issuanceRepository() + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow()); + AccountEnvelopeBinding otherPurposeBinding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + UUID.randomUUID().toString(), + "other-request", + Long.toString(source.identity().accountId()), + Long.toString(source.identity().tenantId()), + source.identity().connectScopeId(), + UUID.randomUUID().toString(), + digest("other-request"), + digest("other-context"), + digest("other-authority"), + digest("other-fence"), + digest("other-postcondition")); + assertThatThrownBy( + () -> + prepared + .db() + .envelopeCrypto() + .decrypt( + stored.responseEnvelope().envelope(), + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + otherPurposeBinding)) + .isInstanceOf(AccountEnvelopeCryptoException.class) + .extracting(exception -> ((AccountEnvelopeCryptoException) exception).failure()) + .isEqualTo(Failure.PURPOSE_MISMATCH); + + AccountCommittedConnectSourceReader wrongKeyReader = + readerWithCrypto(prepared, differentConnectPurposeKey()); + assertReadRejected( + wrongKeyReader, + prepared, + source, + AccountEnvelopeCryptoException.class, + "AUTHENTICATION_FAILED"); + } + + @Test + void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, false, true, false)); + CountDownLatch accountRowLocked = new CountDownLatch(1); + CountDownLatch releaseAccountRow = new CountDownLatch(1); + CountDownLatch readerBackendIdentified = new CountDownLatch(1); + AtomicInteger blockerBackendPid = new AtomicInteger(); + AtomicInteger readerBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blocker = + executor.submit( + () -> + inTransaction( + prepared.db().transaction(), + () -> { + blockerBackendPid.set(requirePositiveBackendPid(prepared.db().dsl())); + prepared + .db() + .dsl() + .resultQuery( + "SELECT id FROM accounts WHERE id = ? FOR UPDATE", + prepared.accountId()) + .fetchOne(); + accountRowLocked.countDown(); + if (!await(releaseAccountRow, 20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Account fence holder was not released"); + } + return null; + })); + try { + assertThat(accountRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future reader = + executor.submit( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> { + readerBackendPid.set( + requirePositiveBackendPid(prepared.db().dsl())); + readerBackendIdentified.countDown(); + return prepared + .reader() + .read(source.identity(), source.gatewayEnvelope()); + }))); + if (!readerBackendIdentified.await(5, TimeUnit.SECONDS)) { + try { + reader.get(0, TimeUnit.MILLISECONDS); + } catch (java.util.concurrent.ExecutionException failure) { + throw new AssertionError( + "Reader failed before identifying its backend", failure.getCause()); + } catch (java.util.concurrent.TimeoutException stillRunning) { + // The bounded identity wait elapsed while the worker was still running. + } + throw new AssertionError( + "Reader backend PID was not identified before the bounded deadline"); + } + assertThat( + awaitAccountFenceBlock( + prepared.db().dsl(), + readerBackendPid.get(), + blockerBackendPid.get(), + Duration.ofSeconds(5))) + .as("the exact reader backend is blocked by the exact Account row fence backend") + .isTrue(); + + // The source token remains valid; only the Gateway's signed, shortened deadline expires. + prepared.clock().advance(Duration.ofSeconds(3)); + releaseAccountRow.countDown(); + assertThatThrownBy(() -> reader.get(10, TimeUnit.SECONDS)) + .satisfies( + thrown -> { + Throwable cause = thrown; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gateway context is expired"); + }); + } finally { + releaseAccountRow.countDown(); + blocker.get(10, TimeUnit.SECONDS); + executor.shutdownNow(); + } + } + + private PreparedAccount newPreparedAccount() throws Exception { + String schema = + "account_source_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("25") + .load() + .migrate(); + + DSLContext seedDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + long accountId = + insertRetainedRows(seedDsl, LEGACY_TENANT_ID, "source-reader-" + UUID.randomUUID()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var sourceEvidence = new LegacyTenantSourceEvidence(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + var associations = + new ApprovedLegacyTenantAssociationRepository( + dsl, sourceEvidence, WORKLOAD_NAMESPACE, generations); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + UUID tenantUuid = UUID.randomUUID(); + String retainedEvidenceDigest = sourceEvidence.digest(LEGACY_TENANT_ID); + inTransaction( + transaction, + () -> + associations.importApproved( + LEGACY_TENANT_ID, approvedAssociation(retainedEvidenceDigest, tenantUuid))); + + byte[] bareLoginKey = new byte[32]; + byte[] connectTokenKey = new byte[32]; + FIXTURE_RANDOM.nextBytes(bareLoginKey); + do { + FIXTURE_RANDOM.nextBytes(connectTokenKey); + } while (MessageDigest.isEqual(bareLoginKey, connectTokenKey)); + Path manifest = tempDir.resolve("account-response-ring-" + UUID.randomUUID() + ".v1"); + String ringManifest = + "version=1\nactiveKeyId=test-key\nkey:test-key:bare-login=" + + BASE64_URL.encodeToString(bareLoginKey) + + "\nkey:test-key:connect-token=" + + BASE64_URL.encodeToString(connectTokenKey) + + "\n"; + Files.writeString(manifest, ringManifest, StandardCharsets.US_ASCII); + AccountEnvelopeCrypto envelopeCrypto = new AccountEnvelopeCrypto(manifest); + + KeyPair accountKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair unknownAccountKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair gatewayKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair unknownGatewayKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + TestClock clock = new TestClock(Instant.parse("2026-10-01T00:00:00Z")); + AccountGameplayConnectSourceVerifier verifier = + new AccountGameplayConnectSourceVerifier( + ACCOUNT_ISSUER, Map.of(ACCOUNT_KEY_ID, accountKeyPair.getPublic()), 16 * 1024, clock); + Map gatewayKeys = + Map.of(GATEWAY_KEY_ID, gatewayKeyPair.getPublic()); + AccountConnectTokenIssuanceRepository issuanceRepository = + new AccountConnectTokenIssuanceRepository(dsl); + AccountRepository accountRepository = new AccountRepository(dsl); + AccountTenantIdentityResolver tenantResolver = + new AccountTenantIdentityResolver(associations, sourceEvidence, WORKLOAD_NAMESPACE); + AccountJoinOperationRepository joinRepository = new AccountJoinOperationRepository(dsl); + AccountCommittedConnectSourceReader reader = + new AccountCommittedConnectSourceReader( + issuanceRepository, + accountRepository, + tenantResolver, + joinRepository, + envelopeCrypto, + verifier, + gatewayKeys, + clock, + WORKLOAD_NAMESPACE); + TestContext db = new TestContext(dsl, transaction, issuanceRepository, envelopeCrypto); + return new PreparedAccount( + db, + accountId, + LEGACY_TENANT_ID, + accountUuid, + tenantUuid, + accountKeyPair, + unknownAccountKeyPair, + gatewayKeyPair, + unknownGatewayKeyPair, + verifier, + gatewayKeys, + accountRepository, + tenantResolver, + joinRepository, + reader, + clock); + } + + private SourceFixture newSource(PreparedAccount prepared, SourceState state) throws Exception { + return newSource(prepared, state, SourceOptions.NORMAL); + } + + private SourceFixture newSource( + PreparedAccount prepared, SourceState state, SourceOptions options) throws Exception { + String requestId = "source-request-" + UUID.randomUUID(); + String connectScopeId = "source-scope-" + UUID.randomUUID(); + long sourceTenantId = + options.unmappedTenant() ? prepared.tenantId() + 1000L : prepared.tenantId(); + UUID sourceTenantUuid = options.unmappedTenant() ? UUID.randomUUID() : prepared.tenantUuid(); + AccountConnectTokenIssuanceIdentity identity = + new AccountConnectTokenIssuanceIdentity( + prepared.accountId(), sourceTenantId, connectScopeId, requestId); + String tokenIdentity = "source-jti-" + UUID.randomUUID(); + Map sourceClaims = + sourceClaims( + prepared.accountUuid(), sourceTenantUuid, identity, tokenIdentity, prepared.clock()); + KeyPair tokenSigner = + options.unknownSourceKey() ? prepared.unknownAccountKeyPair() : prepared.accountKeyPair(); + String tokenKeyId = options.unknownSourceKey() ? "unregistered-account-key" : ACCOUNT_KEY_ID; + byte[] compactJwt = signAccountJwt(sourceClaims, tokenKeyId, tokenSigner); + byte[] storedHash = sha256(compactJwt); + if (options.wrongHash()) { + storedHash[0] ^= 0x01; + } + String storedTokenIdentity = options.wrongJti() ? "different-source-jti" : tokenIdentity; + + Map gatewaySourceClaims = new LinkedHashMap<>(sourceClaims); + if (options.wrongTarget()) { + gatewaySourceClaims.put("worldSlug", "different-world"); + } + Map projectedGatewayClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + gatewaySourceClaims, + prepared.clock().instant().getEpochSecond(), + "gateway-request-" + UUID.randomUUID()); + Map gatewayClaims = new LinkedHashMap<>(projectedGatewayClaims); + if (options.shortGatewayDeadline()) { + gatewayClaims.put( + "expiresAt", BigInteger.valueOf(prepared.clock().instant().getEpochSecond() + 2L)); + } + byte[] gatewayPayload = JSON.writeValueAsBytes(gatewayClaims); + KeyPair gatewaySigner = + options.unknownGatewayKey() ? prepared.unknownGatewayKeyPair() : prepared.gatewayKeyPair(); + String gatewayKid = options.unknownGatewayKey() ? "unregistered-gateway-key" : GATEWAY_KEY_ID; + String gatewayEnvelope = + GatewayConnectContextSignature.sign(gatewayPayload, gatewayKid, gatewaySigner.getPrivate()); + + if (state != SourceState.ABSENT) { + byte[] requestDigest = + sha256(("source-request-digest:" + requestId).getBytes(StandardCharsets.UTF_8)); + inTransaction( + prepared.db().transaction(), + () -> { + var claim = prepared.db().issuanceRepository().claim(identity, requestDigest); + if (state == SourceState.PENDING) { + return null; + } + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + claim.operation().operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + null, + requestDigest, + digest("context:" + requestId), + digest("authority:" + requestId), + digest("fence:" + requestId), + digest("postcondition:" + requestId)); + boolean success = state == SourceState.COMMITTED; + byte[] plaintext = + success + ? compactJwt + : "deterministic issuance failure".getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope encrypted = + prepared + .db() + .envelopeCrypto() + .encrypt(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding, plaintext); + prepared + .db() + .issuanceRepository() + .completeWithEnvelope( + claim, + requestDigest, + success ? Lifecycle.COMMITTED : Lifecycle.FAILED, + success ? "SUCCESS" : "SOURCE_UNAVAILABLE", + success ? storedTokenIdentity : null, + success ? storedHash : null, + binding, + encrypted); + return null; + }); + } + return new SourceFixture(identity, gatewayEnvelope, sourceClaims, gatewayClaims, tokenIdentity); + } + + private AccountEnvelopeCrypto differentConnectPurposeKey() throws Exception { + byte[] bareLoginKey = new byte[32]; + byte[] connectTokenKey = new byte[32]; + FIXTURE_RANDOM.nextBytes(bareLoginKey); + do { + FIXTURE_RANDOM.nextBytes(connectTokenKey); + } while (MessageDigest.isEqual(bareLoginKey, connectTokenKey)); + Path manifest = tempDir.resolve("wrong-account-response-ring-" + UUID.randomUUID() + ".v1"); + String ringManifest = + "version=1\nactiveKeyId=test-key\nkey:test-key:bare-login=" + + BASE64_URL.encodeToString(bareLoginKey) + + "\nkey:test-key:connect-token=" + + BASE64_URL.encodeToString(connectTokenKey) + + "\n"; + Files.writeString(manifest, ringManifest, StandardCharsets.US_ASCII); + return new AccountEnvelopeCrypto(manifest); + } + + private static AccountCommittedConnectSourceReader readerWithCrypto( + PreparedAccount prepared, AccountEnvelopeCrypto crypto) { + return new AccountCommittedConnectSourceReader( + prepared.db().issuanceRepository(), + prepared.accountRepository(), + prepared.tenantResolver(), + prepared.joinRepository(), + crypto, + prepared.verifier(), + prepared.gatewayKeys(), + prepared.clock(), + WORKLOAD_NAMESPACE); + } + + private static Map sourceClaims( + UUID accountUuid, + UUID tenantUuid, + AccountConnectTokenIssuanceIdentity identity, + String tokenIdentity, + Clock clock) { + BigInteger one = BigInteger.ONE; + BigInteger now = BigInteger.valueOf(clock.instant().getEpochSecond()); + Map tenantGeneration = Map.of(tenantUuid.toString(), one); + Map accountSecurityCutoff = + Map.of( + "accountAuthorityGeneration", one, + "outboxStreamKey", "account:auth-authority:v1:account/" + accountUuid, + "outboxSequence", one); + Map tenantBillingCutoffEntry = + Map.of( + "tenantAuthorityGeneration", + one, + "tenantBillingSequence", + BigInteger.ZERO, + "outboxStreamKey", + "account:auth-authority:v1:tenant/" + tenantUuid, + "outboxSequence", + one); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", one, + "accountAuthorityGeneration", one, + "tenantAuthorityGeneration", tenantGeneration, + "membershipAuthorityGeneration", tenantGeneration, + "privateRealmGrantVersions", List.of(), + "accountSecurityCutoff", accountSecurityCutoff, + "tenantBillingCutoff", Map.of(tenantUuid.toString(), tenantBillingCutoffEntry)); + Map claims = new LinkedHashMap<>(); + claims.put("iss", ACCOUNT_ISSUER); + claims.put("aud", "gameplay-connect"); + claims.put("iat", now.subtract(one)); + claims.put("exp", now.add(BigInteger.valueOf(20))); + claims.put("jti", tokenIdentity); + claims.put("accountId", accountUuid.toString()); + claims.put("tenantId", tenantUuid.toString()); + claims.put("realmId", UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb").toString()); + claims.put("worldSlug", "world"); + claims.put("realmSlug", "realm"); + claims.put( + "playableStateNamespaceId", + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc").toString()); + claims.put("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED"); + claims.put( + "gameInstanceId", UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString()); + claims.put("pointerVersion", one); + claims.put("catalogRevision", one); + claims.put("connectScopeId", identity.connectScopeId()); + claims.put("requestId", identity.requestId()); + claims.put("authorityTuple", authorityTuple); + claims.put("membershipVersion", tenantGeneration); + claims.put("replayAdmissionFence", one); + return claims; + } + + private static byte[] signAccountJwt(Map claims, String keyId, KeyPair signer) + throws Exception { + String header = "{\"alg\":\"EdDSA\",\"kid\":\"" + keyId + "\",\"typ\":\"JWT\"}"; + String encodedHeader = BASE64_URL.encodeToString(header.getBytes(StandardCharsets.US_ASCII)); + String encodedPayload = BASE64_URL.encodeToString(JSON.writeValueAsBytes(claims)); + String signingInput = encodedHeader + "." + encodedPayload; + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(signer.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return (signingInput + "." + BASE64_URL.encodeToString(signature.sign())) + .getBytes(StandardCharsets.US_ASCII); + } + + private static ResolveLegacyAccountTenantAssociationResponse approvedAssociation( + String sourceEvidenceDigest, UUID tenantUuid) { + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(LEGACY_TENANT_ID) + .setCanonicalTenantId(tenantUuid.toString()) + .setSourceLegacyGameTenantId("legacy-game-source-reader") + .setSourceGameRowId(7L) + .setAccountEvidenceDigest(sourceEvidenceDigest) + .setOperationId(UUID.randomUUID().toString()) + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace(WORKLOAD_NAMESPACE) + .setSignerKeyId("game-design-owner-test") + .setApprovedBy("owner@example.test") + .setApprovalReference("committed-connect-source-test") + .setSignedAt("2026-10-01T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } + + private static long insertRetainedRows(DSLContext dsl, long tenantId, String username) { + Number inserted = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, 'hash', ?) RETURNING id", + username, + username + "@example.test", + tenantId) + .fetchOne(0, Number.class), + "Account insertion did not return an identifier"); + long accountId = inserted.longValue(); + if (accountId <= 0L) { + throw new IllegalStateException("Account insertion returned a non-positive identifier"); + } + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed) VALUES (?, ?, TRUE)", + accountId, + tenantId); + dsl.execute("INSERT INTO profiles (account_id, tenant_id) VALUES (?, ?)", accountId, tenantId); + return accountId; + } + + private static int requirePositiveBackendPid(DSLContext dsl) { + Integer backendPid = + Objects.requireNonNull( + dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class), + "PostgreSQL did not return a backend PID"); + if (backendPid <= 0) { + throw new IllegalStateException("PostgreSQL returned a non-positive backend PID"); + } + return backendPid; + } + + private static Snapshot sourceSnapshot( + PreparedAccount prepared, AccountConnectTokenIssuanceIdentity identity) { + String scopeHash = AccountJoinDigest.tokenHash(identity.connectScopeId()); + Record row = + prepared + .db() + .dsl() + .resultQuery( + "SELECT operation_id, status, updated_at::text, " + + "(SELECT count(*) FROM account_connect_token_response_envelopes e " + + "WHERE e.operation_id = o.operation_id) " + + "FROM account_connect_token_issuance_operations o " + + "WHERE account_id = ? AND tenant_id = ? AND connect_scope_hash = ? AND request_id = ?", + identity.accountId(), + identity.tenantId(), + scopeHash, + identity.requestId()) + .fetchOne(); + return row == null + ? new Snapshot(null, null, null, 0L) + : new Snapshot( + row.get(0, UUID.class), + row.get(1, String.class), + row.get(2, String.class), + row.get(3, Long.class)); + } + + private static boolean awaitAccountFenceBlock( + DSLContext dsl, int readerBackendPid, int blockerBackendPid, Duration timeout) + throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + dsl.resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity waiting " + + "WHERE waiting.pid = ? " + + "AND waiting.wait_event_type = 'Lock' " + + "AND waiting.query ILIKE '%for update%' " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)))", + readerBackendPid, blockerBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private static boolean await(CountDownLatch latch, long timeout, TimeUnit unit) { + try { + return latch.await(timeout, unit); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + return false; + } + } + + private static void assertReadRejected( + PreparedAccount prepared, + SourceFixture source, + Class exceptionType, + String messageFragment) { + assertReadRejected(prepared.reader(), prepared, source, exceptionType, messageFragment); + } + + private static void assertReadRejected( + AccountCommittedConnectSourceReader reader, + PreparedAccount prepared, + SourceFixture source, + Class exceptionType, + String messageFragment) { + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> reader.read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(exceptionType) + .hasMessageContaining(messageFragment); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context scoped = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = scoped.attach(); + try { + return action.get(); + } finally { + scoped.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static byte[] digest(String value) { + return sha256(value.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (Exception exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static T inTransaction(TransactionTemplate transaction, Supplier work) { + return transaction.execute(status -> work.get()); + } + + private enum SourceState { + ABSENT, + PENDING, + COMMITTED, + FAILED + } + + private record SourceOptions( + boolean unknownSourceKey, + boolean wrongHash, + boolean wrongJti, + boolean wrongTarget, + boolean unknownGatewayKey, + boolean shortGatewayDeadline, + boolean unmappedTenant) { + private static final SourceOptions NORMAL = + new SourceOptions(false, false, false, false, false, false, false); + } + + private record TestContext( + DSLContext dsl, + TransactionTemplate transaction, + AccountConnectTokenIssuanceRepository issuanceRepository, + AccountEnvelopeCrypto envelopeCrypto) {} + + private record PreparedAccount( + TestContext db, + long accountId, + long tenantId, + UUID accountUuid, + UUID tenantUuid, + KeyPair accountKeyPair, + KeyPair unknownAccountKeyPair, + KeyPair gatewayKeyPair, + KeyPair unknownGatewayKeyPair, + AccountGameplayConnectSourceVerifier verifier, + Map gatewayKeys, + AccountRepository accountRepository, + AccountTenantIdentityResolver tenantResolver, + AccountJoinOperationRepository joinRepository, + AccountCommittedConnectSourceReader reader, + TestClock clock) {} + + private record SourceFixture( + AccountConnectTokenIssuanceIdentity identity, + String gatewayEnvelope, + Map sourceClaims, + Map gatewayClaims, + String tokenIdentity) {} + + private record Snapshot(UUID operationId, String status, String updatedAt, long envelopeCount) {} + + private static final class TestClock extends Clock { + private volatile Instant now; + private final ZoneId zone; + + private TestClock(Instant initial) { + this(initial, ZoneOffset.UTC); + } + + private TestClock(Instant initial, ZoneId zone) { + now = initial; + this.zone = zone; + } + + private void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId zone) { + return new TestClock(now, zone); + } + + @Override + public Instant instant() { + return now; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java new file mode 100644 index 0000000000..546a4a97fd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java @@ -0,0 +1,420 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayConnectSourceVerifierTest { + private static final String ISSUER = "https://account.example.test"; + private static final String RSA_KID = "account-rsa-current"; + private static final String ED_KID = "account-ed-current"; + private static final int MAX_COMPACT_JWT_BYTES = 16 * 1024; + private static final Instant NOW = Instant.parse("2026-04-06T12:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final long NOW_SECONDS = NOW.getEpochSecond(); + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000001"; + private static final String TENANT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String REALM_ID = "00000000-0000-4000-8000-000000000003"; + private static final String GAME_INSTANCE_ID = "00000000-0000-4000-8000-000000000004"; + private static final String NAMESPACE_ID = "00000000-0000-4000-8000-000000000005"; + private static final String TEST_LIFECYCLE_ID = "00000000-0000-4000-8000-000000000006"; + private static final BigInteger LARGE_ACCOUNT_GENERATION = + new BigInteger("123456789012345678901234567890"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private KeyPair rsaKeyPair; + private KeyPair edKeyPair; + + @BeforeEach + void setUp() throws Exception { + KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); + rsa.initialize(2048); + rsaKeyPair = rsa.generateKeyPair(); + edKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + } + + @Test + void verifiesRsaSourceAndPreservesExactDeeplyImmutableClaims() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String compactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + + Map verified = verifier().verify(compactJwt); + + assertEquals(ISSUER, verified.get("iss")); + assertEquals("gameplay-connect", verified.get("aud")); + assertEquals(BigInteger.valueOf(NOW_SECONDS - 1), verified.get("iat")); + assertEquals(BigInteger.valueOf(NOW_SECONDS + 29), verified.get("exp")); + assertEquals( + BigInteger.valueOf(19), + verified.get("membershipVersion") instanceof Map map ? map.get(TENANT_ID) : null); + assertEquals( + LARGE_ACCOUNT_GENERATION, + ((Map) verified.get("authorityTuple")).get("accountAuthorityGeneration")); + assertFalse(verified.containsKey("rawJWT")); + assertFalse(verified.containsValue(compactJwt)); + + assertThrows(UnsupportedOperationException.class, () -> verified.put("extra", "value")); + Map tuple = objectMap(verified.get("authorityTuple")); + assertThrows(UnsupportedOperationException.class, () -> tuple.put("extra", "value")); + Map tenantGenerations = objectMap(tuple.get("tenantAuthorityGeneration")); + assertThrows( + UnsupportedOperationException.class, + () -> tenantGenerations.put(TENANT_ID, BigInteger.TEN)); + Map billingCutoffs = objectMap(tuple.get("tenantBillingCutoff")); + Map tenantCutoff = objectMap(billingCutoffs.get(TENANT_ID)); + assertThrows( + UnsupportedOperationException.class, + () -> tenantCutoff.put("outboxSequence", BigInteger.TEN)); + } + + @Test + void verifiesEd25519SourceAndOptionalProtectedHeaderType() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String compactJwt = sign(claims, "EdDSA", ED_KID, null, edKeyPair.getPrivate()); + AccountGameplayConnectSourceVerifier verifier = + new AccountGameplayConnectSourceVerifier( + ISSUER, Map.of(ED_KID, edKeyPair.getPublic()), MAX_COMPACT_JWT_BYTES, CLOCK); + + assertEquals("request-1", verifier.verify(compactJwt).get("requestId")); + } + + @Test + void rejectsRsaVerificationKeysBelow2048BitsAtConstruction() throws Exception { + KeyPairGenerator weakRsa = KeyPairGenerator.getInstance("RSA"); + weakRsa.initialize(1024); + KeyPair weakKeyPair = weakRsa.generateKeyPair(); + + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> + new AccountGameplayConnectSourceVerifier( + ISSUER, + Map.of("account-rsa-weak", weakKeyPair.getPublic()), + MAX_COMPACT_JWT_BYTES, + CLOCK)); + + assertEquals("Account verification key registry is invalid", failure.getMessage()); + } + + @Test + void acceptsLifecycleBoundNonPublicTargetAndKeepsGrantValuesImmutable() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + claims.put("realmSlug", "preview"); + claims.put("playtestLifecycleId", TEST_LIFECYCLE_ID); + claims.put("playtestStateGeneration", BigInteger.valueOf(3)); + Map tuple = objectMap(claims.get("authorityTuple")); + tuple.put( + "privateRealmGrantVersions", + List.of( + Map.of( + "tenantId", + TENANT_ID, + "worldSlug", + "emberfall", + "realmSlug", + "preview", + "playtestLifecycleId", + TEST_LIFECYCLE_ID, + "grantVersion", + BigInteger.valueOf(7)))); + String compactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + + Map verified = verifier().verify(compactJwt); + + Map verifiedTuple = objectMap(verified.get("authorityTuple")); + List grants = (List) verifiedTuple.get("privateRealmGrantVersions"); + assertThrows(UnsupportedOperationException.class, grants::clear); + Map grant = objectMap(grants.getFirst()); + assertThrows( + UnsupportedOperationException.class, () -> grant.put("grantVersion", BigInteger.TEN)); + } + + @Test + void rejectsUnknownKidWrongSignatureAndWrongIssuerWithOneSanitizedFailure() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String unknownKid = sign(claims, "RS256", "other-account-key", "JWT", rsaKeyPair.getPrivate()); + KeyPair wrongPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + String wrongSignature = sign(claims, "RS256", RSA_KID, "JWT", wrongPair.getPrivate()); + Map wrongIssuerClaims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + wrongIssuerClaims.put("iss", "https://other-account.example.test"); + String wrongIssuer = sign(wrongIssuerClaims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + + assertSanitizedFailure(unknownKid); + assertSanitizedFailure(wrongSignature); + assertSanitizedFailure(wrongIssuer); + } + + @Test + void rejectsExpiredFutureAndOverlongSourceTimesBeforeProjection() throws Exception { + Map expired = sourceClaims(NOW_SECONDS - 5, NOW_SECONDS); + Map future = sourceClaims(NOW_SECONDS + 6, NOW_SECONDS + 20); + Map overlong = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 30); + + assertSanitizedFailure(sign(expired, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + assertSanitizedFailure(sign(future, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + assertSanitizedFailure(sign(overlong, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + } + + @Test + void rejectsNonCanonicalMalformedAndOversizedCompactJwts() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String compactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + String[] segments = compactJwt.split("\\.", -1); + + assertSanitizedFailure(null); + assertSanitizedFailure("one.two"); + assertSanitizedFailure(compactJwt + ".fourth"); + assertSanitizedFailure(segments[0] + "=." + segments[1] + "." + segments[2]); + AccountGameplayConnectSourceVerifier tinyLimitVerifier = + new AccountGameplayConnectSourceVerifier( + ISSUER, Map.of(RSA_KID, rsaKeyPair.getPublic()), 8, CLOCK); + assertSanitizedFailure(tinyLimitVerifier, compactJwt); + } + + @Test + void rejectsDuplicateAndUnregisteredProtectedHeaderFields() throws Exception { + String payload = JSON.writeValueAsString(sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29)); + String duplicateKidHeader = + "{\"alg\":\"RS256\",\"kid\":\"" + + RSA_KID + + "\",\"kid\":\"" + + RSA_KID + + "\",\"typ\":\"JWT\"}"; + String remoteKeyHeader = + "{\"alg\":\"RS256\",\"kid\":\"" + + RSA_KID + + "\",\"typ\":\"JWT\",\"jku\":\"https://attacker.invalid/keys\"}"; + String criticalHeader = + "{\"alg\":\"RS256\",\"kid\":\"" + RSA_KID + "\",\"typ\":\"JWT\",\"crit\":[]}"; + String embeddedKeyHeader = + "{\"alg\":\"RS256\",\"kid\":\"" + RSA_KID + "\",\"typ\":\"JWT\",\"jwk\":{\"kty\":\"RSA\"}}"; + + assertSanitizedFailure( + signRaw(duplicateKidHeader, payload, "SHA256withRSA", rsaKeyPair.getPrivate())); + assertSanitizedFailure( + signRaw(remoteKeyHeader, payload, "SHA256withRSA", rsaKeyPair.getPrivate())); + assertSanitizedFailure( + signRaw(criticalHeader, payload, "SHA256withRSA", rsaKeyPair.getPrivate())); + assertSanitizedFailure( + signRaw(embeddedKeyHeader, payload, "SHA256withRSA", rsaKeyPair.getPrivate())); + } + + @Test + void rejectsDuplicateClaimsExtraFieldsWrongProfileAndMalformedNumericValues() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String validPayload = JSON.writeValueAsString(claims); + String duplicateClaimPayload = + validPayload.replaceFirst( + "\"iss\":\"[^\"]+\",", "\"iss\":\"" + ISSUER + "\",\"iss\":\"" + ISSUER + "\","); + assertSanitizedFailure( + signRaw( + canonicalHeader(RSA_KID, "RS256", "JWT"), + duplicateClaimPayload, + "SHA256withRSA", + rsaKeyPair.getPrivate())); + + Map extra = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + extra.put("rawJWT", "must-not-escape"); + assertSanitizedFailure(sign(extra, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + + Map otherProfile = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + otherProfile.put("aud", "player-bootstrap"); + assertSanitizedFailure(sign(otherProfile, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + + Map stringCounter = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + Map stringTuple = objectMap(stringCounter.get("authorityTuple")); + stringTuple.put("tenantAuthorityGeneration", new LinkedHashMap<>(Map.of(TENANT_ID, "13"))); + assertSanitizedFailure(sign(stringCounter, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + + Map fractionalTime = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + fractionalTime.put("iat", new BigDecimal(NOW_SECONDS - 1 + ".0")); + assertSanitizedFailure(sign(fractionalTime, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + } + + @Test + void rejectsSelectedTargetAndMembershipMapChanges() throws Exception { + Map wrongTenant = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + wrongTenant.put("tenantId", "00000000-0000-4000-8000-000000000099"); + + Map wrongMembershipKey = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + wrongMembershipKey.put( + "membershipVersion", + Map.of("00000000-0000-4000-8000-000000000099", BigInteger.valueOf(19))); + + assertSanitizedFailure(sign(wrongTenant, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + assertSanitizedFailure( + sign(wrongMembershipKey, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + } + + @Test + void rejectsAlgorithmAndKeyTypeMismatchAndNoneOrHmacAlgorithms() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String payload = JSON.writeValueAsString(claims); + String rsaWithEdAlgorithm = + signRaw( + canonicalHeader(RSA_KID, "EdDSA", "JWT"), + payload, + "SHA256withRSA", + rsaKeyPair.getPrivate()); + String none = + signRaw( + canonicalHeader(RSA_KID, "none", "JWT"), + payload, + "SHA256withRSA", + rsaKeyPair.getPrivate()); + String hmac = + signRaw( + canonicalHeader(RSA_KID, "HS256", "JWT"), + payload, + "SHA256withRSA", + rsaKeyPair.getPrivate()); + + assertSanitizedFailure(rsaWithEdAlgorithm); + assertSanitizedFailure(none); + assertSanitizedFailure(hmac); + } + + private AccountGameplayConnectSourceVerifier verifier() { + return new AccountGameplayConnectSourceVerifier( + ISSUER, Map.of(RSA_KID, rsaKeyPair.getPublic()), MAX_COMPACT_JWT_BYTES, CLOCK); + } + + private void assertSanitizedFailure(String compactJwt) { + assertSanitizedFailure(verifier(), compactJwt); + } + + private void assertSanitizedFailure( + AccountGameplayConnectSourceVerifier verifier, String compactJwt) { + IllegalArgumentException failure = + assertThrows(IllegalArgumentException.class, () -> verifier.verify(compactJwt)); + assertEquals("invalid Account gameplay-connect source JWT", failure.getMessage()); + assertNull(failure.getCause()); + if (compactJwt != null) { + assertFalse(failure.getMessage().contains(compactJwt)); + } + } + + private static Map sourceClaims(long issuedAt, long expiresAt) { + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("aud", "gameplay-connect"); + claims.put("iat", BigInteger.valueOf(issuedAt)); + claims.put("exp", BigInteger.valueOf(expiresAt)); + claims.put("jti", "connect-jti-1"); + claims.put("accountId", ACCOUNT_ID); + claims.put("tenantId", TENANT_ID); + claims.put("realmId", REALM_ID); + claims.put("worldSlug", "emberfall"); + claims.put("realmSlug", "public-production"); + claims.put("playableStateNamespaceId", NAMESPACE_ID); + claims.put("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED"); + claims.put("gameInstanceId", GAME_INSTANCE_ID); + claims.put("pointerVersion", BigInteger.valueOf(23)); + claims.put("catalogRevision", BigInteger.valueOf(41)); + claims.put("connectScopeId", "scope-1"); + claims.put("requestId", "request-1"); + claims.put("authorityTuple", authorityTuple()); + claims.put("membershipVersion", Map.of(TENANT_ID, BigInteger.valueOf(19))); + claims.put("replayAdmissionFence", BigInteger.valueOf(29)); + return claims; + } + + private static Map authorityTuple() { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", BigInteger.valueOf(2)); + tuple.put("accountAuthorityGeneration", LARGE_ACCOUNT_GENERATION); + tuple.put("tenantAuthorityGeneration", Map.of(TENANT_ID, BigInteger.valueOf(13))); + tuple.put("membershipAuthorityGeneration", Map.of(TENANT_ID, BigInteger.valueOf(17))); + tuple.put("privateRealmGrantVersions", List.of()); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + LARGE_ACCOUNT_GENERATION, + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT_ID, + "outboxSequence", + BigInteger.valueOf(31))); + tuple.put( + "tenantBillingCutoff", + Map.of( + TENANT_ID, + Map.of( + "tenantAuthorityGeneration", BigInteger.valueOf(13), + "tenantBillingSequence", BigInteger.valueOf(5), + "outboxStreamKey", "account:auth-authority:v1:tenant/" + TENANT_ID, + "outboxSequence", BigInteger.valueOf(37)))); + return tuple; + } + + private static String sign( + Map claims, + String algorithm, + String kid, + String type, + java.security.PrivateKey privateKey) + throws Exception { + String header = canonicalHeader(kid, algorithm, type); + String payload = JSON.writeValueAsString(claims); + String jcaAlgorithm = + switch (algorithm) { + case "RS256" -> "SHA256withRSA"; + case "RS384" -> "SHA384withRSA"; + case "RS512" -> "SHA512withRSA"; + case "EdDSA" -> "Ed25519"; + default -> "SHA256withRSA"; + }; + return signRaw(header, payload, jcaAlgorithm, privateKey); + } + + private static String signRaw( + String header, String payload, String jcaAlgorithm, java.security.PrivateKey privateKey) + throws Exception { + String protectedSegment = encode(header.getBytes(StandardCharsets.UTF_8)); + String payloadSegment = encode(payload.getBytes(StandardCharsets.UTF_8)); + byte[] signingInput = + (protectedSegment + "." + payloadSegment).getBytes(StandardCharsets.US_ASCII); + Signature signer = Signature.getInstance(jcaAlgorithm); + signer.initSign(privateKey); + signer.update(signingInput); + return protectedSegment + "." + payloadSegment + "." + encode(signer.sign()); + } + + private static String canonicalHeader(String kid, String algorithm, String type) { + if (type == null) { + return "{\"alg\":\"" + algorithm + "\",\"kid\":\"" + kid + "\"}"; + } + return "{\"alg\":\"" + algorithm + "\",\"kid\":\"" + kid + "\",\"typ\":\"" + type + "\"}"; + } + + private static String encode(byte[] value) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } + + @SuppressWarnings("unchecked") + private static Map objectMap(Object value) { + assertInstanceOf(Map.class, value); + return (Map) value; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java new file mode 100644 index 0000000000..4952b4afcf --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java @@ -0,0 +1,156 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.security.KeyPairGenerator; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountCommittedConnectSourceReaderGuardTest { + private static final String WORKLOAD_NAMESPACE = "account-unit"; + private static final AccountConnectTokenIssuanceIdentity IDENTITY = + new AccountConnectTokenIssuanceIdentity(101L, 202L, "connect-scope-1", "request-1"); + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-04-06T12:00:00Z"), ZoneOffset.UTC); + + private AccountConnectTokenIssuanceRepository issuanceRepository; + private AccountRepository accountRepository; + private AccountTenantIdentityResolver tenantIdentityResolver; + private AccountJoinOperationRepository joinOperationRepository; + private AccountEnvelopeCrypto envelopeCrypto; + private AccountGameplayConnectSourceVerifier sourceVerifier; + private AccountCommittedConnectSourceReader reader; + private GrpcPeerIdentity expectedGameSessionPeer; + + @BeforeEach + void setUp() throws Exception { + issuanceRepository = mock(AccountConnectTokenIssuanceRepository.class); + accountRepository = mock(AccountRepository.class); + tenantIdentityResolver = mock(AccountTenantIdentityResolver.class); + joinOperationRepository = mock(AccountJoinOperationRepository.class); + envelopeCrypto = mock(AccountEnvelopeCrypto.class); + sourceVerifier = mock(AccountGameplayConnectSourceVerifier.class); + expectedGameSessionPeer = peer(WORKLOAD_NAMESPACE, "game-session-service"); + + var gatewayKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair().getPublic(); + reader = + new AccountCommittedConnectSourceReader( + issuanceRepository, + accountRepository, + tenantIdentityResolver, + joinOperationRepository, + envelopeCrypto, + sourceVerifier, + Map.of("gateway-test", gatewayKey), + CLOCK, + WORKLOAD_NAMESPACE); + } + + @Test + void missingPeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + AdminAuthorizationException failure = + assertThrows( + AdminAuthorizationException.class, + () -> withoutPeer(() -> reader.read(IDENTITY, "unparsed-gateway-context"))); + + assertEquals( + "Committed Account source readback requires the exact Game Session workload identity", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + @Test + void wrongServicePeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + assertPeerDeniedBeforeInteractions(peer(WORKLOAD_NAMESPACE, "world-management-service")); + } + + @Test + void wrongNamespaceGameSessionPeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + assertPeerDeniedBeforeInteractions(peer("other-account-unit", "game-session-service")); + } + + @Test + void exactPeerWithoutOwnerTransactionIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + withPeer( + expectedGameSessionPeer, + () -> reader.read(IDENTITY, "unparsed-gateway-context"))); + + assertEquals( + "Committed Account source readback requires an active owner transaction", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + private void assertPeerDeniedBeforeInteractions(GrpcPeerIdentity peer) { + AdminAuthorizationException failure = + assertThrows( + AdminAuthorizationException.class, + () -> withPeer(peer, () -> reader.read(IDENTITY, "unparsed-gateway-context"))); + + assertEquals( + "Committed Account source readback requires the exact Game Session workload identity", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + private void verifyNoCollaboratorInteractions() { + verifyNoInteractions( + issuanceRepository, + accountRepository, + tenantIdentityResolver, + joinOperationRepository, + envelopeCrypto, + sourceVerifier); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context scoped = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = scoped.attach(); + try { + return action.get(); + } finally { + scoped.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } +} From ac8d52758384e16a2c5f1fc086af40589ad86350 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:19:59 +1300 Subject: [PATCH 40/46] Track committed connect source prerequisite in Unit 1B index --- 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 0bb07841a4..8b057933b3 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work was rebuilt into #2826 Schema, the dependen | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2881](https://github.com/benhook1013/FireMUD/pull/2881) → [#2911](https://github.com/benhook1013/FireMUD/pull/2911) | Earlier discovery and train pre-review did not complete the section. The tail contains JOIN recovery, retained tenant mapping, durable pair authority, authenticated snapshot preparation, purpose-separated envelopes and one-use exchange storage. Exact #2881 `b2a2f31b0` [CI 36703863842](https://github.com/benhook1013/FireMUD/actions/runs/36703863842) executed 29 JOIN, 9 connect-issuance and 9 bare-LOGIN storage PostgreSQL cases without skips or failures; Account and Game Session jobs passed, while aggregate CI remains red on recorded inherited failures. These are storage/snapshot proofs, not end-to-end credential issuance or live admission. #2911 converges the complete selected-target contract and shared signed-context component proof while denying obsolete incomplete/HMAC first-party issuance and admission; it does not enable the producer/consumer path. Required Account connect/delegation producers, full authority/consumer proof, fresh Game Design tenant handoff, protected ring delivery, durable reconnect, HTTPS/mail/abuse and live browser proof remain open in the [Player Access tracker](../implementation-tracking/player-access-and-session.md). Membership RPC and credential activation stay denied; the ring mount stays unpublished. | +| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2881](https://github.com/benhook1013/FireMUD/pull/2881) → [#2911](https://github.com/benhook1013/FireMUD/pull/2911) → [#2914](https://github.com/benhook1013/FireMUD/pull/2914) | Earlier discovery and train pre-review did not complete the section. Exact #2911 `78c3fe886` [CI 36778631119](https://github.com/benhook1013/FireMUD/actions/runs/36778631119) executed 30 JOIN, 9 connect-issuance and 9 bare-LOGIN storage PostgreSQL cases without skips or failures, including the complete snapshot/first-JOIN race; both authority-exhaustion methods and Game Session strict cases also passed. Aggregate CI remains red on routed inherited failures. #2914 adds unwired original committed-connect source readback and strict signed-source/context correspondence; its seven new PostgreSQL cases are pending executed proof. These are component prerequisites, not credential issuance or live admission. Required complete Account authority/consumer evidence, connect/delegation producers and registry, fresh Game Design tenant handoff, protected ring delivery, durable reconnect, HTTPS/mail/abuse and live browser proof remain open in the [Player Access tracker](../implementation-tracking/player-access-and-session.md). Membership RPC and credential activation stay denied; the ring mount stays unpublished. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | From fa3d060cb9aeb763f00a51acb84c07f07bf3944e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 19:48:08 +1300 Subject: [PATCH 41/46] Clarify closed first-party authentication runtime boundary --- design/architecture/system-architecture-authentication.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 1b4ea65b2f..baf90950ee 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -21,8 +21,8 @@ For every private/playtest grant consequence, the exact Account target is `{acco ## Implementation Status - **Current gameplay authentication and transport boundary:** Current gameplay authentication supports `LOGIN ` / `LOGON ` to request a verified-email login code and `LOGIN ` / `LOGON ` for an immediate password-or-code attempt on raw Telnet and other non-WebSocket text clients. Bare raw-text `LOGIN`/`LOGON` prompt exchange is target-only and currently returns `PROMPT_LOGIN_UNSUPPORTED`. Control-plane clients use `/auth/login`. First-party gameplay uses `POST /auth/player-bootstrap` to establish the `player-bootstrap` identity, then uses `/auth/bootstrap/*` discovery/action routes and `/auth/connect-token` before the gameplay socket. Clients are stateless; current Account-owned legacy authentication session records persist `tokenHash` and session metadata under the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key, while gameplay bindings remain in Redis. These records never persist the raw delegation JWT; their runtime/data ownership is defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#session-and-token-model). Target issued-token registry issuance, storage, and consumer enforcement in Coordination Redis are unimplemented. The Game Session Service restores gameplay session state from Redis, while the Account Service validates the supplied login secret and issues the exact `control-ui`, `player-bootstrap`, or receiver-specific private player-delegation JWT profile required by the destination. Raw Telnet gameplay command streams never carry JWT authorization. Target browser and mobile-browser gameplay uses a `player-bootstrap` JWT for HTTPS bootstrap calls and a cookie-carried one-use connect token for the `/ws/game/**` handshake; target first-party native-mobile clients that use a cookie jar remain cookie-only. Public non-browser issuance and the dedicated handshake-header carrier are target-only and unavailable until a dedicated route is fully registered and its issuance, registry, profile, and carrier proof is complete; the target design uses protected secure storage plus `X-Firemud-Connect-Token`. First-party admin/creator UIs and backend services use their own permitted token profiles. Provider-specific HTTPS sign-in remains unavailable until the provider-specific verification, collision, recovery, and end-to-end proof required by [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md) is complete. -- **Current first-party endpoint and runtime boundary:** The current first-party browser/mobile runtime includes dedicated `POST /auth/player-bootstrap` and `POST /auth/connect-token` surfaces, Gateway rejection for missing, expired, replayed, or scope-mismatched connect tokens, and Game Session validation of the signed connect context before bare `LOGIN`, but these remain partial implementation surfaces rather than proof of the complete target flow. Current `PLAY` resolves the admissible `gameInstanceId` from realm routing and binds the legacy `{tenantId, gameInstanceId, characterId}` identity; that per-instance binding is implementation drift. Target `PLAY` binds the controller identity `{tenantId, playableStateNamespaceId, characterId}`, carries server-derived `playableStateScope`, and retains `{gameInstanceId, sessionId, bindingGeneration}` as runtime/value evidence. Current behavior does not claim authoritative `regionId`, `regionEpoch`, lease-owner, or lease-fence resolution. Public non-browser issuance and the dedicated handshake-header carrier remain unavailable. -- **Current bare first-party `LOGIN` containment:** The #2881 candidate retains malformed-context and pointer-mismatch rejection, then returns retryable `AUTH_UNAVAILABLE` for an otherwise valid bare `LOGIN` before command enqueue or authenticated Game Session state is saved. The unauthenticated bootstrap shell remains available for a later explicit retry. Gateway context or a connect-token `jti` alone does not authenticate Account; the Account-owned one-use exchange, committed issuance, private delegation, and recovery proof remain unimplemented. Credential-bearing `LOGIN` is unchanged. +- **Current first-party endpoint and runtime boundary:** Dedicated `POST /auth/player-bootstrap` and `POST /auth/connect-token` surfaces exist, but the complete first-party browser/mobile runtime remains fail-closed. Gateway rejects an otherwise valid connect token with `POLICY_DENY` before replay mutation or signed-context publication; Game Session's runtime connect-context parser is disabled, and Account rejects cached successful issuance rather than replaying its response. These surfaces do not prove live replay continuity, signed-context admission, or the complete Account exchange. Fresh `PLAY` remains contained by unavailable Account runtime authority and exact stable-namespace character proof before legacy gameplay binding. The retained downstream `{tenantId, gameInstanceId, characterId}` binding model is implementation drift, not proof of an available first-party path. Target `PLAY` binds the controller identity `{tenantId, playableStateNamespaceId, characterId}`, carries server-derived `playableStateScope`, and retains `{gameInstanceId, sessionId, bindingGeneration}` as runtime/value evidence. Current behavior does not claim authoritative `regionId`, `regionEpoch`, lease-owner, or lease-fence resolution. Public non-browser issuance and the dedicated handshake-header carrier remain unavailable. See [Gateway API Contracts](./microservices/spring-cloud-gateway/api-contracts.md) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md). +- **Bare first-party `LOGIN` candidate/test containment:** With an injected valid connect context, the candidate retains malformed-context and pointer-mismatch rejection, then returns retryable `AUTH_UNAVAILABLE` before command enqueue or authenticated Game Session state is saved. That conditional test path is not current end-to-end behavior: the runtime parser cannot supply the context. The unauthenticated bootstrap shell remains available for a later explicit retry. Gateway context or a connect-token `jti` alone does not authenticate Account; the Account-owned one-use exchange, committed issuance, private delegation, and recovery proof remain unimplemented. Credential-bearing `LOGIN` is unchanged. - **Current realm-identity gap:** Current discovery, admission-pointer mutation/read models, gameplay-connect claims, and the Gateway signed context do not carry and prove durable `realmId` end to end; several runtime surfaces still key or resolve routes directly from `worldSlug`/`realmSlug`. The target resolves those selectors to `{tenantId, realmId}` before pointer lookup and carries `realmId` in the exact selected-target snapshot and signed context. - **Current provider-specific sign-in boundary:** Optional provider-specific HTTPS sign-in is permitted only after complete provider proof; password and verified-email code remain the Account-owned baseline and fallback, and Telnet never carries provider credentials. See [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md). - **Current raw-text challenge semantics:** The current raw-text email-code challenge is two commands: `LOGIN ` (or `LOGON `) requests an Account-owned, server-side verified-email challenge bound to the normalized account/email and its configured expiry without authenticating the session, then `LOGIN ` (or `LOGON `) submits that code. The separate immediate-auth form is `LOGIN ` (or `LOGON `) with one secret. Account selects the `EMAIL_OTP` validator first when the supplied secret matches the live challenge; otherwise it verifies `PASSWORD` when that account mode is enabled. The client does not select the validator, and a code is not valid outside its server-side challenge and expiry. From 76a422578b0388da392b6c3e5e0e894c68b7449f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:40:18 +1300 Subject: [PATCH 42/46] Preserve canonical membership version strings at connect boundaries --- .../system-architecture-session-behavior.md | 2 +- ...tedConnectSourceReaderIntegrationTest.java | 3 +- ...ountGameplayConnectSourceVerifierTest.java | 36 +++++++++- .../security/GatewayConnectContextCodec.java | 24 ++++++- .../GatewayConnectContextCodecTest.java | 71 +++++++++++++++++++ ...lectedTargetConnectContextTestVectors.java | 2 +- 6 files changed, 131 insertions(+), 7 deletions(-) diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index 216815088d..66020e7542 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -30,7 +30,7 @@ Retained per-sequence duplicate evidence is a separate same-snapshot carrier, no ## Implementation Status -Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` proto declares `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`, but Account's gRPC handler fails closed before its producer read because the request cannot authenticate the player and target binding. Game Session `PLAY` calls that denied route; it does not receive an admitting Account snapshot. Roles, the complete `authorityTuple`, `outboxCheckpoints`, authenticated caller/target context, the binding's exact one-tenant `membershipBaseline` carrier, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. +Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` proto declares `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`, but Account's gRPC handler fails closed before its producer read because the request cannot authenticate the player and target binding. Game Session `PLAY` calls that denied route; it does not receive an admitting Account snapshot. The proto also declares role, complete `authorityTuple`, `outboxCheckpoints`, and authenticated caller/target context fields; the authenticated producer, runtime consumer and wiring, binding's exact one-tenant `membershipBaseline` carrier, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the declared contract as implemented until its producer, consumers, runtime wiring, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. Account Service is the sole writer of account authority-generation advances and all canonical `session:auth:generation:*` projections, including `session:auth:generation:account:`. Account commits every applicable canonical tuple field, cutoff, `issuanceFence`, and monotonic outbox event together; the generation projection is an asynchronous outbox output, not an atomically committed part of that durable generation/event transaction. Game Session and other downstream services consume Account-owned generation events and projections; they must not advance canonical authority or write canonical projections directly, and they fail closed while projection or freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Game Session's only generation projection write is its derived `session:game:auth:issuer-generation:v1:` consumer-local record under the ADR 0022 schema. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java index 0b1e04e981..97f37affea 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java @@ -699,6 +699,7 @@ private static Map sourceClaims( BigInteger one = BigInteger.ONE; BigInteger now = BigInteger.valueOf(clock.instant().getEpochSecond()); Map tenantGeneration = Map.of(tenantUuid.toString(), one); + Map membershipVersion = Map.of(tenantUuid.toString(), one.toString()); Map accountSecurityCutoff = Map.of( "accountAuthorityGeneration", one, @@ -745,7 +746,7 @@ private static Map sourceClaims( claims.put("connectScopeId", identity.connectScopeId()); claims.put("requestId", identity.requestId()); claims.put("authorityTuple", authorityTuple); - claims.put("membershipVersion", tenantGeneration); + claims.put("membershipVersion", membershipVersion); claims.put("replayAdmissionFence", one); return claims; } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java index 546a4a97fd..eadd9ed0f5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java @@ -65,7 +65,7 @@ void verifiesRsaSourceAndPreservesExactDeeplyImmutableClaims() throws Exception assertEquals(BigInteger.valueOf(NOW_SECONDS - 1), verified.get("iat")); assertEquals(BigInteger.valueOf(NOW_SECONDS + 29), verified.get("exp")); assertEquals( - BigInteger.valueOf(19), + "19", verified.get("membershipVersion") instanceof Map map ? map.get(TENANT_ID) : null); assertEquals( LARGE_ACCOUNT_GENERATION, @@ -252,6 +252,38 @@ void rejectsDuplicateClaimsExtraFieldsWrongProfileAndMalformedNumericValues() th assertSanitizedFailure(sign(fractionalTime, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); } + @Test + void rejectsNonCanonicalMembershipVersionStringsAndJsonNumbers() throws Exception { + for (Object malformedVersion : + List.of( + BigInteger.valueOf(19), + new BigDecimal("19.0"), + new BigDecimal("1E2"), + "0", + "00", + "+19", + "-19", + " 19", + "19 ", + "1e2", + "19.0", + Boolean.TRUE)) { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + claims.put( + "membershipVersion", java.util.Collections.singletonMap(TENANT_ID, malformedVersion)); + assertSanitizedFailure(sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + } + + Map nullVersion = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + nullVersion.put("membershipVersion", java.util.Collections.singletonMap(TENANT_ID, null)); + assertSanitizedFailure(sign(nullVersion, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + + Map extraTenant = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + extraTenant.put( + "membershipVersion", Map.of(TENANT_ID, "19", "00000000-0000-4000-8000-000000000099", "20")); + assertSanitizedFailure(sign(extraTenant, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + } + @Test void rejectsSelectedTargetAndMembershipMapChanges() throws Exception { Map wrongTenant = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); @@ -335,7 +367,7 @@ private static Map sourceClaims(long issuedAt, long expiresAt) { claims.put("connectScopeId", "scope-1"); claims.put("requestId", "request-1"); claims.put("authorityTuple", authorityTuple()); - claims.put("membershipVersion", Map.of(TENANT_ID, BigInteger.valueOf(19))); + claims.put("membershipVersion", Map.of(TENANT_ID, "19")); claims.put("replayAdmissionFence", BigInteger.valueOf(29)); return claims; } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java index 1b1a3728ce..30766ff602 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java @@ -316,7 +316,7 @@ private static void validate(Map claims, Instant now) { validateAuthorityTuple(tuple, tenantId, claims, lifecycleId); Map membershipVersion = requireObject(claims.get("membershipVersion"), "membershipVersion"); - requireSingleTenantCounter(membershipVersion, tenantId, "membershipVersion"); + requireSingleTenantPositiveDecimalString(membershipVersion, tenantId, "membershipVersion"); requirePositiveInteger(claims, "replayAdmissionFence"); BigInteger issuedAt = requirePositiveInteger(claims, "issuedAt"); @@ -472,7 +472,7 @@ private static void validateSourceClaims(Map source, long gatewa tenantId, source, lifecycleId); - requireSingleTenantCounter( + requireSingleTenantPositiveDecimalString( requireObject(source.get("membershipVersion"), "membershipVersion"), tenantId, "membershipVersion"); @@ -531,6 +531,26 @@ private static Object normalizeJsonValue(Object value) { throw invalid("Account gameplay-connect claims contain a non-JSON or non-integral value"); } + private static void requireSingleTenantPositiveDecimalString( + Map values, String tenantId, String field) { + if (values.size() != 1 || !values.containsKey(tenantId)) { + throw invalid(field + " must contain exactly the selected tenant"); + } + Object value = values.get(tenantId); + if (!(value instanceof String decimal) + || decimal.isEmpty() + || decimal.charAt(0) < '1' + || decimal.charAt(0) > '9') { + throw invalid(field + " must be a canonical positive decimal string"); + } + for (int index = 1; index < decimal.length(); index++) { + char digit = decimal.charAt(index); + if (digit < '0' || digit > '9') { + throw invalid(field + " must be a canonical positive decimal string"); + } + } + } + private static void requireSingleTenantCounter( Map counters, String tenantId, String field) { if (counters.size() != 1 || !counters.containsKey(tenantId)) { diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java index 4611b393cf..43826a1f2b 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.fasterxml.jackson.databind.ObjectMapper; +import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.KeyPair; @@ -55,6 +56,12 @@ void verifiesRealEd25519ContextAndPreservesExactEnvelopeAndEveryAcceptedField() assertEquals(source.get("tenantId"), context.text("tenantId")); assertEquals(source.get("requestId"), context.text("connectRequestId")); assertEquals(source.get("jti"), context.text("connectTokenJti")); + assertEquals( + SelectedTargetConnectContextTestVectors.LARGE_COUNTER.toString(), + nestedString( + context.claims(), + "membershipVersion", + SelectedTargetConnectContextTestVectors.TENANT_ID)); assertEquals(source.get("iat"), context.integer("issuedAt")); long sourceDeadline = GatewayConnectContextCodec.requireGatewayDeadline( @@ -179,6 +186,64 @@ void rejectsMalformedMapsAndNonCanonicalCounters() throws Exception { missingMembership.put("membershipVersion", Map.of()); assertRejected(missingMembership); + for (Object malformedVersion : + List.of( + BigInteger.ONE, + new BigDecimal("1.0"), + new BigDecimal("1E2"), + "0", + "00", + "+1", + "-1", + " 1", + "1 ", + "1e2", + "1.0", + Boolean.TRUE)) { + Map malformedMembership = validContext(); + malformedMembership.put( + "membershipVersion", + Map.of(SelectedTargetConnectContextTestVectors.TENANT_ID, malformedVersion)); + assertRejected(malformedMembership); + } + + Map nullMembership = validContext(); + nullMembership.put( + "membershipVersion", + java.util.Collections.singletonMap( + SelectedTargetConnectContextTestVectors.TENANT_ID, null)); + assertRejected(nullMembership); + + Map extraMembership = validContext(); + extraMembership.put( + "membershipVersion", + Map.of( + SelectedTargetConnectContextTestVectors.TENANT_ID, + "1", + "018f8f0a-8c1d-7f9a-ad6a-bf4a312c0d8e", + "2")); + assertRejected(extraMembership); + + Map wrongMembershipTenant = validContext(); + wrongMembershipTenant.put( + "membershipVersion", Map.of("018f8f0a-8c1d-7f9a-ad6a-bf4a312c0d8e", "1")); + assertRejected(wrongMembershipTenant); + + Map sourceWithNumericMembership = + SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + sourceWithNumericMembership.put( + "membershipVersion", + Map.of( + SelectedTargetConnectContextTestVectors.TENANT_ID, + SelectedTargetConnectContextTestVectors.LARGE_COUNTER)); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + sourceWithNumericMembership, + SelectedTargetConnectContextTestVectors.GATEWAY_VERIFIED_AT, + "gateway-request-42")); + Map malformedAuthority = validContext(); @SuppressWarnings("unchecked") Map tuple = @@ -559,6 +624,12 @@ private static BigInteger nested( return (BigInteger) second.get(key); } + private static String nestedString(Map claims, String object, String key) { + @SuppressWarnings("unchecked") + Map nested = (Map) claims.get(object); + return (String) nested.get(key); + } + private static Map validContext() { return projectContext(SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims()); } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/SelectedTargetConnectContextTestVectors.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/SelectedTargetConnectContextTestVectors.java index ee57feff63..8550c11022 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/SelectedTargetConnectContextTestVectors.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/SelectedTargetConnectContextTestVectors.java @@ -40,7 +40,7 @@ public static Map sourceConnectTokenClaims() { claims.put("connectScopeId", "connect-scope-17"); claims.put("requestId", "connect-request-42"); claims.put("authorityTuple", authorityTuple()); - claims.put("membershipVersion", Map.of(TENANT_ID, LARGE_COUNTER)); + claims.put("membershipVersion", Map.of(TENANT_ID, LARGE_COUNTER.toString())); claims.put("replayAdmissionFence", LARGE_COUNTER); claims.put("jti", "connect-token-jti-42"); claims.put("iat", BigInteger.valueOf(SOURCE_ISSUED_AT)); From 3bcf0c9620962730aa01374bc17d99b8a21f4649 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 23:11:51 +1300 Subject: [PATCH 43/46] Clarify target-only protected-cookie gameplay transport --- design/architecture/system-architecture-frontend.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index a1ed6c6537..4f5e7428d9 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -102,7 +102,7 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - **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 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 exact one-tenant `membershipVersion` map 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 complete map 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 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 target transport behavior; current first-party bare-`LOGIN` availability and fail-closed status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). 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. - The React client does not store or expose `control-ui` JWTs for gameplay. It may hold only the short-lived, memory-only `player-bootstrap` token described in the authentication design and use it solely for gameplay bootstrap surfaces such as bootstrap discovery, bootstrap-authenticated character discovery and character creation, `POST /auth/bootstrap/join`, and `POST /auth/connect-token`. - **Target-only player logout:** Explicit player logout would revoke the current `player-bootstrap` token with Account Service `POST /auth/logout`, clear local reconnect/client state, and use the Gateway `POST /ws/game/connect-token/revoke` operation. That Account endpoint and Gateway operation are unavailable in the current runtime. The current fallback only clears local reconnect/client state and relies on bounded credential expiry; it does not perform Account revocation, immediate Gateway revocation, an edge deny/replay fence, or client-side clearing of the HttpOnly cookie. The target Gateway revoke operation is an HTTP operation, not a WebSocket upgrade: it would read the HttpOnly cookie server-side, record a bounded deny marker for its `jti` or equivalent edge revocation fence checked before token consumption, and return the clearing `Set-Cookie` response where that response surface supports it. The browser must satisfy the fail-closed `Origin` and anti-CSRF policy defined by [ADR 0021](./decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); the React client never reads the token. The client clears active player state immediately even if Account is unavailable. The shared frontend auth/session controller is the sole owner of one dedicated, memory-only pending-revocation slot and never persists, logs, or uses its credential for gameplay/bootstrap calls. The pending-revocation copy is never used as an alternate active credential: the active in-memory `player-bootstrap` token remains the sole usable bootstrap credential until logout atomically captures it, after which the captured copy is used only for the logout/revocation request and is never reused for gameplay or bootstrap. From 9dbf34c24bcae4d0233f4509eb459d32578699b8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 23:55:03 +1300 Subject: [PATCH 44/46] Reject unknown runtime membership authority tuple fields --- .../command/text/PlayCommandHandler.java | 3 ++ .../command/text/PlayCommandHandlerTest.java | 42 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index bccfebe7c0..f62f8ea18d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -828,6 +828,9 @@ private static boolean hasCompleteMembershipAuthorityCarrier( if (!response.hasMembershipBaseline() || !response.hasAuthorityTuple()) { return false; } + if (!response.getAuthorityTuple().getUnknownFields().asMap().isEmpty()) { + return false; + } if (!isCanonicalUuid(response.getAccountId()) || !isCanonicalUuid(response.getTenantId())) { return false; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index fc32dde859..d4d63b3d0f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.protobuf.UnknownFieldSet; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.IOException; import java.time.Instant; @@ -1780,6 +1781,47 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void playWhenMembershipAuthorityTupleHasUnknownFieldsIsDeniedBeforeAdmission() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var response = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1")); + var tupleWithUnknownField = + response.getAuthorityTuple().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 999, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + response.toBuilder().setAuthorityTuple(tupleWithUnknownField).build(), + invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.world-access-denied"); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + } + @Test void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { SessionContext context = From 900a6517256724e3a8f3428447c80517a3b39817 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:23:29 +1300 Subject: [PATCH 45/46] 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 d2f54c8ffd..7e3ba79e59 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 e39946df60cd658bb21311ff6ec7ea300eb811d6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:34:39 +1300 Subject: [PATCH 46/46] 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 7e3ba79e59..8d072d15d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1068,7 +1068,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) {