diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9856c37a5f..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,19 +959,33 @@ 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)' \ --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: | 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/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/ai-observations.md b/design/project-management/ai-observations.md index 7bd20f9d59..3cc7dad3f4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -151,3 +151,16 @@ 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. + +- `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. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 7274d1a03a..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; 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) → [#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 ebbdeb133a..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,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 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/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f9abcc5dfc..771e6c3d9b 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,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 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. + 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. @@ -73,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 @@ -81,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. | @@ -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/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) 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..1b1a3728ce --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java @@ -0,0 +1,654 @@ +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); + } + + /** + * 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. + */ + 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..4611b393cf --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java @@ -0,0 +1,576 @@ +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 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(); + 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 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") + 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..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 @@ -10,8 +10,13 @@ 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.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; @@ -22,6 +27,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 +52,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 +59,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; @@ -93,7 +100,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", @@ -175,13 +181,13 @@ static void registerProperties(DynamicPropertyRegistry registry) { @Autowired private GameplayAdmissionPointerEventRepository gameplayAdmissionPointerEventRepository; - private final ConcurrentMap firstPartyConnectStore = new ConcurrentHashMap<>(); + private final ConcurrentMap redisValueStore = new ConcurrentHashMap<>(); private final ConcurrentMap> redisSetStore = new ConcurrentHashMap<>(); @BeforeEach void setUp() { - firstPartyConnectStore.clear(); + redisValueStore.clear(); redisSetStore.clear(); sessionContextService.deleteBySessionId(22L, 41L); sessionContextService.deleteBySessionId(22L, 42L); @@ -191,10 +197,10 @@ void setUp() { when(redisTemplate.opsForValue()).thenReturn(redisValueOperations); when(redisTemplate.opsForSet()).thenReturn(redisSetOperations); when(redisValueOperations.get(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> firstPartyConnectStore.get(invocation.getArgument(0))); + .thenAnswer(invocation -> redisValueStore.get(invocation.getArgument(0))); org.mockito.Mockito.doAnswer( invocation -> { - firstPartyConnectStore.put(invocation.getArgument(0), invocation.getArgument(1)); + redisValueStore.put(invocation.getArgument(0), invocation.getArgument(1)); return null; }) .when(redisValueOperations) @@ -203,10 +209,7 @@ void setUp() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(java.time.Duration.class)); org.mockito.Mockito.doAnswer( - invocation -> { - firstPartyConnectStore.remove(invocation.getArgument(0)); - return null; - }) + invocation -> redisValueStore.remove(invocation.getArgument(0)) != null) .when(redisTemplate) .delete(org.mockito.ArgumentMatchers.anyString()); when(gameInstanceRepository.save(org.mockito.ArgumentMatchers.any(GameInstance.class))) @@ -790,47 +793,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 +836,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 +983,32 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots } @Test - void websocketFirstPartyInvalidConnectContextClosesImmediately() throws Exception { + 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( + 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( @@ -1289,235 +1016,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 +1055,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 +1148,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) {